example.e31bb0bc.js 1.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629
  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/three/build/three.module.js":[function(require,module,exports) {
  101. "use strict";
  102. Object.defineProperty(exports, "__esModule", {
  103. value: true
  104. });
  105. exports.AmbientLight = AmbientLight;
  106. exports.AmbientLightProbe = AmbientLightProbe;
  107. exports.AnimationClip = AnimationClip;
  108. exports.AnimationLoader = AnimationLoader;
  109. exports.AnimationMixer = AnimationMixer;
  110. exports.AnimationObjectGroup = AnimationObjectGroup;
  111. exports.ArcCurve = ArcCurve;
  112. exports.ArrayCamera = ArrayCamera;
  113. exports.ArrowHelper = ArrowHelper;
  114. exports.Audio = Audio;
  115. exports.AudioAnalyser = AudioAnalyser;
  116. exports.AudioListener = AudioListener;
  117. exports.AudioLoader = AudioLoader;
  118. exports.AxesHelper = AxesHelper;
  119. exports.AxisHelper = AxisHelper;
  120. exports.BinaryTextureLoader = BinaryTextureLoader;
  121. exports.Bone = Bone;
  122. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  123. exports.BoundingBoxHelper = BoundingBoxHelper;
  124. exports.Box2 = Box2;
  125. exports.Box3 = Box3;
  126. exports.Box3Helper = Box3Helper;
  127. exports.BoxHelper = BoxHelper;
  128. exports.BufferAttribute = BufferAttribute;
  129. exports.BufferGeometry = BufferGeometry;
  130. exports.BufferGeometryLoader = BufferGeometryLoader;
  131. exports.Camera = Camera;
  132. exports.CameraHelper = CameraHelper;
  133. exports.CanvasRenderer = CanvasRenderer;
  134. exports.CanvasTexture = CanvasTexture;
  135. exports.CatmullRomCurve3 = CatmullRomCurve3;
  136. exports.CircleBufferGeometry = CircleBufferGeometry;
  137. exports.CircleGeometry = CircleGeometry;
  138. exports.Clock = Clock;
  139. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  140. exports.Color = Color;
  141. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  142. exports.CompressedTexture = CompressedTexture;
  143. exports.CompressedTextureLoader = CompressedTextureLoader;
  144. exports.ConeBufferGeometry = ConeBufferGeometry;
  145. exports.ConeGeometry = ConeGeometry;
  146. exports.CubeCamera = CubeCamera;
  147. exports.CubeTexture = CubeTexture;
  148. exports.CubeTextureLoader = CubeTextureLoader;
  149. exports.CubicBezierCurve = CubicBezierCurve;
  150. exports.CubicBezierCurve3 = CubicBezierCurve3;
  151. exports.CubicInterpolant = CubicInterpolant;
  152. exports.Curve = Curve;
  153. exports.CurvePath = CurvePath;
  154. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  155. exports.CylinderGeometry = CylinderGeometry;
  156. exports.Cylindrical = Cylindrical;
  157. exports.DataTexture = DataTexture;
  158. exports.DataTexture2DArray = DataTexture2DArray;
  159. exports.DataTexture3D = DataTexture3D;
  160. exports.DataTextureLoader = DataTextureLoader;
  161. exports.DepthTexture = DepthTexture;
  162. exports.DirectionalLight = DirectionalLight;
  163. exports.DirectionalLightHelper = DirectionalLightHelper;
  164. exports.DirectionalLightShadow = DirectionalLightShadow;
  165. exports.DiscreteInterpolant = DiscreteInterpolant;
  166. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  167. exports.DodecahedronGeometry = DodecahedronGeometry;
  168. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  169. exports.EdgesGeometry = EdgesGeometry;
  170. exports.EdgesHelper = EdgesHelper;
  171. exports.EllipseCurve = EllipseCurve;
  172. exports.Euler = Euler;
  173. exports.EventDispatcher = EventDispatcher;
  174. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  175. exports.ExtrudeGeometry = ExtrudeGeometry;
  176. exports.Face3 = Face3;
  177. exports.Face4 = Face4;
  178. exports.FileLoader = FileLoader;
  179. exports.Float32Attribute = Float32Attribute;
  180. exports.Float32BufferAttribute = Float32BufferAttribute;
  181. exports.Float64Attribute = Float64Attribute;
  182. exports.Float64BufferAttribute = Float64BufferAttribute;
  183. exports.Fog = Fog;
  184. exports.FogExp2 = FogExp2;
  185. exports.Font = Font;
  186. exports.FontLoader = FontLoader;
  187. exports.Frustum = Frustum;
  188. exports.Geometry = Geometry;
  189. exports.GridHelper = GridHelper;
  190. exports.Group = Group;
  191. exports.HemisphereLight = HemisphereLight;
  192. exports.HemisphereLightHelper = HemisphereLightHelper;
  193. exports.HemisphereLightProbe = HemisphereLightProbe;
  194. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  195. exports.IcosahedronGeometry = IcosahedronGeometry;
  196. exports.ImageBitmapLoader = ImageBitmapLoader;
  197. exports.ImageLoader = ImageLoader;
  198. exports.ImmediateRenderObject = ImmediateRenderObject;
  199. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  200. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  201. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  202. exports.InstancedMesh = InstancedMesh;
  203. exports.Int16Attribute = Int16Attribute;
  204. exports.Int16BufferAttribute = Int16BufferAttribute;
  205. exports.Int32Attribute = Int32Attribute;
  206. exports.Int32BufferAttribute = Int32BufferAttribute;
  207. exports.Int8Attribute = Int8Attribute;
  208. exports.Int8BufferAttribute = Int8BufferAttribute;
  209. exports.InterleavedBuffer = InterleavedBuffer;
  210. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  211. exports.Interpolant = Interpolant;
  212. exports.JSONLoader = JSONLoader;
  213. exports.KeyframeTrack = KeyframeTrack;
  214. exports.LOD = LOD;
  215. exports.LatheBufferGeometry = LatheBufferGeometry;
  216. exports.LatheGeometry = LatheGeometry;
  217. exports.Layers = Layers;
  218. exports.LensFlare = LensFlare;
  219. exports.Light = Light;
  220. exports.LightProbe = LightProbe;
  221. exports.LightShadow = LightShadow;
  222. exports.Line = Line;
  223. exports.Line3 = Line3;
  224. exports.LineBasicMaterial = LineBasicMaterial;
  225. exports.LineCurve = LineCurve;
  226. exports.LineCurve3 = LineCurve3;
  227. exports.LineDashedMaterial = LineDashedMaterial;
  228. exports.LineLoop = LineLoop;
  229. exports.LineSegments = LineSegments;
  230. exports.LinearInterpolant = LinearInterpolant;
  231. exports.Loader = Loader;
  232. exports.LoadingManager = LoadingManager;
  233. exports.Material = Material;
  234. exports.MaterialLoader = MaterialLoader;
  235. exports.Matrix3 = Matrix3;
  236. exports.Matrix4 = Matrix4;
  237. exports.Mesh = Mesh;
  238. exports.MeshBasicMaterial = MeshBasicMaterial;
  239. exports.MeshDepthMaterial = MeshDepthMaterial;
  240. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  241. exports.MeshFaceMaterial = MeshFaceMaterial;
  242. exports.MeshLambertMaterial = MeshLambertMaterial;
  243. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  244. exports.MeshNormalMaterial = MeshNormalMaterial;
  245. exports.MeshPhongMaterial = MeshPhongMaterial;
  246. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  247. exports.MeshStandardMaterial = MeshStandardMaterial;
  248. exports.MeshToonMaterial = MeshToonMaterial;
  249. exports.MultiMaterial = MultiMaterial;
  250. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  251. exports.Object3D = Object3D;
  252. exports.ObjectLoader = ObjectLoader;
  253. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  254. exports.OctahedronGeometry = OctahedronGeometry;
  255. exports.OrthographicCamera = OrthographicCamera;
  256. exports.PMREMGenerator = PMREMGenerator;
  257. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  258. exports.ParametricGeometry = ParametricGeometry;
  259. exports.Particle = Particle;
  260. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  261. exports.ParticleSystem = ParticleSystem;
  262. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  263. exports.Path = Path;
  264. exports.PerspectiveCamera = PerspectiveCamera;
  265. exports.Plane = Plane;
  266. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  267. exports.PlaneGeometry = PlaneGeometry;
  268. exports.PlaneHelper = PlaneHelper;
  269. exports.PointCloud = PointCloud;
  270. exports.PointCloudMaterial = PointCloudMaterial;
  271. exports.PointLight = PointLight;
  272. exports.PointLightHelper = PointLightHelper;
  273. exports.Points = Points;
  274. exports.PointsMaterial = PointsMaterial;
  275. exports.PolarGridHelper = PolarGridHelper;
  276. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  277. exports.PolyhedronGeometry = PolyhedronGeometry;
  278. exports.PositionalAudio = PositionalAudio;
  279. exports.PropertyBinding = PropertyBinding;
  280. exports.PropertyMixer = PropertyMixer;
  281. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  282. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  283. exports.Quaternion = Quaternion;
  284. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  285. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  286. exports.RawShaderMaterial = RawShaderMaterial;
  287. exports.Ray = Ray;
  288. exports.Raycaster = Raycaster;
  289. exports.RectAreaLight = RectAreaLight;
  290. exports.RingBufferGeometry = RingBufferGeometry;
  291. exports.RingGeometry = RingGeometry;
  292. exports.Scene = Scene;
  293. exports.ShaderMaterial = ShaderMaterial;
  294. exports.ShadowMaterial = ShadowMaterial;
  295. exports.Shape = Shape;
  296. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  297. exports.ShapeGeometry = ShapeGeometry;
  298. exports.ShapePath = ShapePath;
  299. exports.Skeleton = Skeleton;
  300. exports.SkeletonHelper = SkeletonHelper;
  301. exports.SkinnedMesh = SkinnedMesh;
  302. exports.Sphere = Sphere;
  303. exports.SphereBufferGeometry = SphereBufferGeometry;
  304. exports.SphereGeometry = SphereGeometry;
  305. exports.Spherical = Spherical;
  306. exports.SphericalHarmonics3 = SphericalHarmonics3;
  307. exports.Spline = Spline;
  308. exports.SplineCurve = SplineCurve;
  309. exports.SplineCurve3 = SplineCurve3;
  310. exports.SpotLight = SpotLight;
  311. exports.SpotLightHelper = SpotLightHelper;
  312. exports.SpotLightShadow = SpotLightShadow;
  313. exports.Sprite = Sprite;
  314. exports.SpriteMaterial = SpriteMaterial;
  315. exports.StereoCamera = StereoCamera;
  316. exports.StringKeyframeTrack = StringKeyframeTrack;
  317. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  318. exports.TetrahedronGeometry = TetrahedronGeometry;
  319. exports.TextBufferGeometry = TextBufferGeometry;
  320. exports.TextGeometry = TextGeometry;
  321. exports.Texture = Texture;
  322. exports.TextureLoader = TextureLoader;
  323. exports.TorusBufferGeometry = TorusBufferGeometry;
  324. exports.TorusGeometry = TorusGeometry;
  325. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  326. exports.TorusKnotGeometry = TorusKnotGeometry;
  327. exports.Triangle = Triangle;
  328. exports.TubeBufferGeometry = TubeBufferGeometry;
  329. exports.TubeGeometry = TubeGeometry;
  330. exports.Uint16Attribute = Uint16Attribute;
  331. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  332. exports.Uint32Attribute = Uint32Attribute;
  333. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  334. exports.Uint8Attribute = Uint8Attribute;
  335. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  336. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  337. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  338. exports.Uniform = Uniform;
  339. exports.Vector2 = Vector2;
  340. exports.Vector3 = Vector3;
  341. exports.Vector4 = Vector4;
  342. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  343. exports.Vertex = Vertex;
  344. exports.VideoTexture = VideoTexture;
  345. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  346. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  347. exports.WebGLRenderTarget = WebGLRenderTarget;
  348. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  349. exports.WebGLRenderer = WebGLRenderer;
  350. exports.WebGLUtils = WebGLUtils;
  351. exports.WireframeGeometry = WireframeGeometry;
  352. exports.WireframeHelper = WireframeHelper;
  353. exports.XHRLoader = XHRLoader;
  354. 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.MathUtils = 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.DynamicReadUsage = exports.DynamicDrawUsage = exports.DynamicCopyUsage = 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;
  355. exports.UniformsLib = exports.Uncharted2ToneMapping = exports.UVMapping = exports.TrianglesDrawMode = exports.TriangleStripDrawMode = exports.TriangleFanDrawMode = exports.TangentSpaceNormalMap = exports.TOUCH = exports.SubtractiveBlending = exports.SubtractEquation = exports.StreamReadUsage = exports.StreamDrawUsage = exports.StreamCopyUsage = exports.StaticReadUsage = exports.StaticDrawUsage = exports.StaticCopyUsage = exports.SrcColorFactor = exports.SrcAlphaSaturateFactor = exports.SrcAlphaFactor = exports.SphericalReflectionMapping = exports.SmoothShading = exports.ShortType = exports.ShapeUtils = exports.ShaderLib = exports.ShaderChunk = exports.SceneUtils = exports.SRGB8_ALPHA8_ASTC_8x8_Format = exports.SRGB8_ALPHA8_ASTC_8x6_Format = exports.SRGB8_ALPHA8_ASTC_8x5_Format = exports.SRGB8_ALPHA8_ASTC_6x6_Format = exports.SRGB8_ALPHA8_ASTC_6x5_Format = exports.SRGB8_ALPHA8_ASTC_5x5_Format = exports.SRGB8_ALPHA8_ASTC_5x4_Format = exports.SRGB8_ALPHA8_ASTC_4x4_Format = exports.SRGB8_ALPHA8_ASTC_12x12_Format = exports.SRGB8_ALPHA8_ASTC_12x10_Format = exports.SRGB8_ALPHA8_ASTC_10x8_Format = exports.SRGB8_ALPHA8_ASTC_10x6_Format = exports.SRGB8_ALPHA8_ASTC_10x5_Format = exports.SRGB8_ALPHA8_ASTC_10x10_Format = exports.ReverseSubtractEquation = exports.ReplaceStencilOp = exports.RepeatWrapping = exports.ReinhardToneMapping = exports.RedIntegerFormat = exports.RedFormat = exports.RGIntegerFormat = exports.RGFormat = exports.RGB_S3TC_DXT1_Format = exports.RGB_PVRTC_4BPPV1_Format = exports.RGB_PVRTC_2BPPV1_Format = exports.RGB_ETC2_Format = exports.RGB_ETC1_Format = exports.RGBM7Encoding = exports.RGBM16Encoding = exports.RGBIntegerFormat = 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_ETC2_EAC_Format = exports.RGBA_BPTC_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.RGBAIntegerFormat = 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 = exports.NoToneMapping = exports.NoColors = exports.NoBlending = exports.NeverStencilFunc = void 0;
  356. 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 = void 0;
  357. // Polyfills
  358. if (Number.EPSILON === undefined) {
  359. Number.EPSILON = Math.pow(2, -52);
  360. }
  361. if (Number.isInteger === undefined) {
  362. // Missing in IE
  363. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  364. Number.isInteger = function (value) {
  365. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  366. };
  367. } //
  368. if (Math.sign === undefined) {
  369. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  370. Math.sign = function (x) {
  371. return x < 0 ? -1 : x > 0 ? 1 : +x;
  372. };
  373. }
  374. if ('name' in Function.prototype === false) {
  375. // Missing in IE
  376. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  377. Object.defineProperty(Function.prototype, 'name', {
  378. get: function () {
  379. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  380. }
  381. });
  382. }
  383. if (Object.assign === undefined) {
  384. // Missing in IE
  385. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  386. Object.assign = function (target) {
  387. if (target === undefined || target === null) {
  388. throw new TypeError('Cannot convert undefined or null to object');
  389. }
  390. var output = Object(target);
  391. for (var index = 1; index < arguments.length; index++) {
  392. var source = arguments[index];
  393. if (source !== undefined && source !== null) {
  394. for (var nextKey in source) {
  395. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  396. output[nextKey] = source[nextKey];
  397. }
  398. }
  399. }
  400. }
  401. return output;
  402. };
  403. }
  404. var REVISION = '115';
  405. exports.REVISION = REVISION;
  406. var MOUSE = {
  407. LEFT: 0,
  408. MIDDLE: 1,
  409. RIGHT: 2,
  410. ROTATE: 0,
  411. DOLLY: 1,
  412. PAN: 2
  413. };
  414. exports.MOUSE = MOUSE;
  415. var TOUCH = {
  416. ROTATE: 0,
  417. PAN: 1,
  418. DOLLY_PAN: 2,
  419. DOLLY_ROTATE: 3
  420. };
  421. exports.TOUCH = TOUCH;
  422. var CullFaceNone = 0;
  423. exports.CullFaceNone = CullFaceNone;
  424. var CullFaceBack = 1;
  425. exports.CullFaceBack = CullFaceBack;
  426. var CullFaceFront = 2;
  427. exports.CullFaceFront = CullFaceFront;
  428. var CullFaceFrontBack = 3;
  429. exports.CullFaceFrontBack = CullFaceFrontBack;
  430. var FrontFaceDirectionCW = 0;
  431. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  432. var FrontFaceDirectionCCW = 1;
  433. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  434. var BasicShadowMap = 0;
  435. exports.BasicShadowMap = BasicShadowMap;
  436. var PCFShadowMap = 1;
  437. exports.PCFShadowMap = PCFShadowMap;
  438. var PCFSoftShadowMap = 2;
  439. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  440. var VSMShadowMap = 3;
  441. exports.VSMShadowMap = VSMShadowMap;
  442. var FrontSide = 0;
  443. exports.FrontSide = FrontSide;
  444. var BackSide = 1;
  445. exports.BackSide = BackSide;
  446. var DoubleSide = 2;
  447. exports.DoubleSide = DoubleSide;
  448. var FlatShading = 1;
  449. exports.FlatShading = FlatShading;
  450. var SmoothShading = 2;
  451. exports.SmoothShading = SmoothShading;
  452. var NoBlending = 0;
  453. exports.NoBlending = NoBlending;
  454. var NormalBlending = 1;
  455. exports.NormalBlending = NormalBlending;
  456. var AdditiveBlending = 2;
  457. exports.AdditiveBlending = AdditiveBlending;
  458. var SubtractiveBlending = 3;
  459. exports.SubtractiveBlending = SubtractiveBlending;
  460. var MultiplyBlending = 4;
  461. exports.MultiplyBlending = MultiplyBlending;
  462. var CustomBlending = 5;
  463. exports.CustomBlending = CustomBlending;
  464. var AddEquation = 100;
  465. exports.AddEquation = AddEquation;
  466. var SubtractEquation = 101;
  467. exports.SubtractEquation = SubtractEquation;
  468. var ReverseSubtractEquation = 102;
  469. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  470. var MinEquation = 103;
  471. exports.MinEquation = MinEquation;
  472. var MaxEquation = 104;
  473. exports.MaxEquation = MaxEquation;
  474. var ZeroFactor = 200;
  475. exports.ZeroFactor = ZeroFactor;
  476. var OneFactor = 201;
  477. exports.OneFactor = OneFactor;
  478. var SrcColorFactor = 202;
  479. exports.SrcColorFactor = SrcColorFactor;
  480. var OneMinusSrcColorFactor = 203;
  481. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  482. var SrcAlphaFactor = 204;
  483. exports.SrcAlphaFactor = SrcAlphaFactor;
  484. var OneMinusSrcAlphaFactor = 205;
  485. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  486. var DstAlphaFactor = 206;
  487. exports.DstAlphaFactor = DstAlphaFactor;
  488. var OneMinusDstAlphaFactor = 207;
  489. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  490. var DstColorFactor = 208;
  491. exports.DstColorFactor = DstColorFactor;
  492. var OneMinusDstColorFactor = 209;
  493. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  494. var SrcAlphaSaturateFactor = 210;
  495. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  496. var NeverDepth = 0;
  497. exports.NeverDepth = NeverDepth;
  498. var AlwaysDepth = 1;
  499. exports.AlwaysDepth = AlwaysDepth;
  500. var LessDepth = 2;
  501. exports.LessDepth = LessDepth;
  502. var LessEqualDepth = 3;
  503. exports.LessEqualDepth = LessEqualDepth;
  504. var EqualDepth = 4;
  505. exports.EqualDepth = EqualDepth;
  506. var GreaterEqualDepth = 5;
  507. exports.GreaterEqualDepth = GreaterEqualDepth;
  508. var GreaterDepth = 6;
  509. exports.GreaterDepth = GreaterDepth;
  510. var NotEqualDepth = 7;
  511. exports.NotEqualDepth = NotEqualDepth;
  512. var MultiplyOperation = 0;
  513. exports.MultiplyOperation = MultiplyOperation;
  514. var MixOperation = 1;
  515. exports.MixOperation = MixOperation;
  516. var AddOperation = 2;
  517. exports.AddOperation = AddOperation;
  518. var NoToneMapping = 0;
  519. exports.NoToneMapping = NoToneMapping;
  520. var LinearToneMapping = 1;
  521. exports.LinearToneMapping = LinearToneMapping;
  522. var ReinhardToneMapping = 2;
  523. exports.ReinhardToneMapping = ReinhardToneMapping;
  524. var Uncharted2ToneMapping = 3;
  525. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  526. var CineonToneMapping = 4;
  527. exports.CineonToneMapping = CineonToneMapping;
  528. var ACESFilmicToneMapping = 5;
  529. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  530. var UVMapping = 300;
  531. exports.UVMapping = UVMapping;
  532. var CubeReflectionMapping = 301;
  533. exports.CubeReflectionMapping = CubeReflectionMapping;
  534. var CubeRefractionMapping = 302;
  535. exports.CubeRefractionMapping = CubeRefractionMapping;
  536. var EquirectangularReflectionMapping = 303;
  537. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  538. var EquirectangularRefractionMapping = 304;
  539. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  540. var SphericalReflectionMapping = 305;
  541. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  542. var CubeUVReflectionMapping = 306;
  543. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  544. var CubeUVRefractionMapping = 307;
  545. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  546. var RepeatWrapping = 1000;
  547. exports.RepeatWrapping = RepeatWrapping;
  548. var ClampToEdgeWrapping = 1001;
  549. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  550. var MirroredRepeatWrapping = 1002;
  551. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  552. var NearestFilter = 1003;
  553. exports.NearestFilter = NearestFilter;
  554. var NearestMipmapNearestFilter = 1004;
  555. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  556. var NearestMipMapNearestFilter = 1004;
  557. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  558. var NearestMipmapLinearFilter = 1005;
  559. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  560. var NearestMipMapLinearFilter = 1005;
  561. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  562. var LinearFilter = 1006;
  563. exports.LinearFilter = LinearFilter;
  564. var LinearMipmapNearestFilter = 1007;
  565. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  566. var LinearMipMapNearestFilter = 1007;
  567. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  568. var LinearMipmapLinearFilter = 1008;
  569. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  570. var LinearMipMapLinearFilter = 1008;
  571. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  572. var UnsignedByteType = 1009;
  573. exports.UnsignedByteType = UnsignedByteType;
  574. var ByteType = 1010;
  575. exports.ByteType = ByteType;
  576. var ShortType = 1011;
  577. exports.ShortType = ShortType;
  578. var UnsignedShortType = 1012;
  579. exports.UnsignedShortType = UnsignedShortType;
  580. var IntType = 1013;
  581. exports.IntType = IntType;
  582. var UnsignedIntType = 1014;
  583. exports.UnsignedIntType = UnsignedIntType;
  584. var FloatType = 1015;
  585. exports.FloatType = FloatType;
  586. var HalfFloatType = 1016;
  587. exports.HalfFloatType = HalfFloatType;
  588. var UnsignedShort4444Type = 1017;
  589. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  590. var UnsignedShort5551Type = 1018;
  591. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  592. var UnsignedShort565Type = 1019;
  593. exports.UnsignedShort565Type = UnsignedShort565Type;
  594. var UnsignedInt248Type = 1020;
  595. exports.UnsignedInt248Type = UnsignedInt248Type;
  596. var AlphaFormat = 1021;
  597. exports.AlphaFormat = AlphaFormat;
  598. var RGBFormat = 1022;
  599. exports.RGBFormat = RGBFormat;
  600. var RGBAFormat = 1023;
  601. exports.RGBAFormat = RGBAFormat;
  602. var LuminanceFormat = 1024;
  603. exports.LuminanceFormat = LuminanceFormat;
  604. var LuminanceAlphaFormat = 1025;
  605. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  606. var RGBEFormat = RGBAFormat;
  607. exports.RGBEFormat = RGBEFormat;
  608. var DepthFormat = 1026;
  609. exports.DepthFormat = DepthFormat;
  610. var DepthStencilFormat = 1027;
  611. exports.DepthStencilFormat = DepthStencilFormat;
  612. var RedFormat = 1028;
  613. exports.RedFormat = RedFormat;
  614. var RedIntegerFormat = 1029;
  615. exports.RedIntegerFormat = RedIntegerFormat;
  616. var RGFormat = 1030;
  617. exports.RGFormat = RGFormat;
  618. var RGIntegerFormat = 1031;
  619. exports.RGIntegerFormat = RGIntegerFormat;
  620. var RGBIntegerFormat = 1032;
  621. exports.RGBIntegerFormat = RGBIntegerFormat;
  622. var RGBAIntegerFormat = 1033;
  623. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  624. var RGB_S3TC_DXT1_Format = 33776;
  625. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  626. var RGBA_S3TC_DXT1_Format = 33777;
  627. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  628. var RGBA_S3TC_DXT3_Format = 33778;
  629. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  630. var RGBA_S3TC_DXT5_Format = 33779;
  631. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  632. var RGB_PVRTC_4BPPV1_Format = 35840;
  633. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  634. var RGB_PVRTC_2BPPV1_Format = 35841;
  635. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  636. var RGBA_PVRTC_4BPPV1_Format = 35842;
  637. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  638. var RGBA_PVRTC_2BPPV1_Format = 35843;
  639. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  640. var RGB_ETC1_Format = 36196;
  641. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  642. var RGB_ETC2_Format = 37492;
  643. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  644. var RGBA_ETC2_EAC_Format = 37496;
  645. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  646. var RGBA_ASTC_4x4_Format = 37808;
  647. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  648. var RGBA_ASTC_5x4_Format = 37809;
  649. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  650. var RGBA_ASTC_5x5_Format = 37810;
  651. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  652. var RGBA_ASTC_6x5_Format = 37811;
  653. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  654. var RGBA_ASTC_6x6_Format = 37812;
  655. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  656. var RGBA_ASTC_8x5_Format = 37813;
  657. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  658. var RGBA_ASTC_8x6_Format = 37814;
  659. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  660. var RGBA_ASTC_8x8_Format = 37815;
  661. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  662. var RGBA_ASTC_10x5_Format = 37816;
  663. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  664. var RGBA_ASTC_10x6_Format = 37817;
  665. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  666. var RGBA_ASTC_10x8_Format = 37818;
  667. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  668. var RGBA_ASTC_10x10_Format = 37819;
  669. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  670. var RGBA_ASTC_12x10_Format = 37820;
  671. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  672. var RGBA_ASTC_12x12_Format = 37821;
  673. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  674. var RGBA_BPTC_Format = 36492;
  675. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  676. var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  677. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  678. var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  679. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  680. var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  681. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  682. var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  683. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  684. var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  685. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  686. var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  687. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  688. var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  689. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  690. var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  691. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  692. var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  693. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  694. var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  695. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  696. var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  697. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  698. var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  699. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  700. var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  701. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  702. var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  703. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  704. var LoopOnce = 2200;
  705. exports.LoopOnce = LoopOnce;
  706. var LoopRepeat = 2201;
  707. exports.LoopRepeat = LoopRepeat;
  708. var LoopPingPong = 2202;
  709. exports.LoopPingPong = LoopPingPong;
  710. var InterpolateDiscrete = 2300;
  711. exports.InterpolateDiscrete = InterpolateDiscrete;
  712. var InterpolateLinear = 2301;
  713. exports.InterpolateLinear = InterpolateLinear;
  714. var InterpolateSmooth = 2302;
  715. exports.InterpolateSmooth = InterpolateSmooth;
  716. var ZeroCurvatureEnding = 2400;
  717. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  718. var ZeroSlopeEnding = 2401;
  719. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  720. var WrapAroundEnding = 2402;
  721. exports.WrapAroundEnding = WrapAroundEnding;
  722. var TrianglesDrawMode = 0;
  723. exports.TrianglesDrawMode = TrianglesDrawMode;
  724. var TriangleStripDrawMode = 1;
  725. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  726. var TriangleFanDrawMode = 2;
  727. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  728. var LinearEncoding = 3000;
  729. exports.LinearEncoding = LinearEncoding;
  730. var sRGBEncoding = 3001;
  731. exports.sRGBEncoding = sRGBEncoding;
  732. var GammaEncoding = 3007;
  733. exports.GammaEncoding = GammaEncoding;
  734. var RGBEEncoding = 3002;
  735. exports.RGBEEncoding = RGBEEncoding;
  736. var LogLuvEncoding = 3003;
  737. exports.LogLuvEncoding = LogLuvEncoding;
  738. var RGBM7Encoding = 3004;
  739. exports.RGBM7Encoding = RGBM7Encoding;
  740. var RGBM16Encoding = 3005;
  741. exports.RGBM16Encoding = RGBM16Encoding;
  742. var RGBDEncoding = 3006;
  743. exports.RGBDEncoding = RGBDEncoding;
  744. var BasicDepthPacking = 3200;
  745. exports.BasicDepthPacking = BasicDepthPacking;
  746. var RGBADepthPacking = 3201;
  747. exports.RGBADepthPacking = RGBADepthPacking;
  748. var TangentSpaceNormalMap = 0;
  749. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  750. var ObjectSpaceNormalMap = 1;
  751. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  752. var ZeroStencilOp = 0;
  753. exports.ZeroStencilOp = ZeroStencilOp;
  754. var KeepStencilOp = 7680;
  755. exports.KeepStencilOp = KeepStencilOp;
  756. var ReplaceStencilOp = 7681;
  757. exports.ReplaceStencilOp = ReplaceStencilOp;
  758. var IncrementStencilOp = 7682;
  759. exports.IncrementStencilOp = IncrementStencilOp;
  760. var DecrementStencilOp = 7683;
  761. exports.DecrementStencilOp = DecrementStencilOp;
  762. var IncrementWrapStencilOp = 34055;
  763. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  764. var DecrementWrapStencilOp = 34056;
  765. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  766. var InvertStencilOp = 5386;
  767. exports.InvertStencilOp = InvertStencilOp;
  768. var NeverStencilFunc = 512;
  769. exports.NeverStencilFunc = NeverStencilFunc;
  770. var LessStencilFunc = 513;
  771. exports.LessStencilFunc = LessStencilFunc;
  772. var EqualStencilFunc = 514;
  773. exports.EqualStencilFunc = EqualStencilFunc;
  774. var LessEqualStencilFunc = 515;
  775. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  776. var GreaterStencilFunc = 516;
  777. exports.GreaterStencilFunc = GreaterStencilFunc;
  778. var NotEqualStencilFunc = 517;
  779. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  780. var GreaterEqualStencilFunc = 518;
  781. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  782. var AlwaysStencilFunc = 519;
  783. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  784. var StaticDrawUsage = 35044;
  785. exports.StaticDrawUsage = StaticDrawUsage;
  786. var DynamicDrawUsage = 35048;
  787. exports.DynamicDrawUsage = DynamicDrawUsage;
  788. var StreamDrawUsage = 35040;
  789. exports.StreamDrawUsage = StreamDrawUsage;
  790. var StaticReadUsage = 35045;
  791. exports.StaticReadUsage = StaticReadUsage;
  792. var DynamicReadUsage = 35049;
  793. exports.DynamicReadUsage = DynamicReadUsage;
  794. var StreamReadUsage = 35041;
  795. exports.StreamReadUsage = StreamReadUsage;
  796. var StaticCopyUsage = 35046;
  797. exports.StaticCopyUsage = StaticCopyUsage;
  798. var DynamicCopyUsage = 35050;
  799. exports.DynamicCopyUsage = DynamicCopyUsage;
  800. var StreamCopyUsage = 35042;
  801. /**
  802. * https://github.com/mrdoob/eventdispatcher.js/
  803. */
  804. exports.StreamCopyUsage = StreamCopyUsage;
  805. function EventDispatcher() {}
  806. Object.assign(EventDispatcher.prototype, {
  807. addEventListener: function (type, listener) {
  808. if (this._listeners === undefined) this._listeners = {};
  809. var listeners = this._listeners;
  810. if (listeners[type] === undefined) {
  811. listeners[type] = [];
  812. }
  813. if (listeners[type].indexOf(listener) === -1) {
  814. listeners[type].push(listener);
  815. }
  816. },
  817. hasEventListener: function (type, listener) {
  818. if (this._listeners === undefined) return false;
  819. var listeners = this._listeners;
  820. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  821. },
  822. removeEventListener: function (type, listener) {
  823. if (this._listeners === undefined) return;
  824. var listeners = this._listeners;
  825. var listenerArray = listeners[type];
  826. if (listenerArray !== undefined) {
  827. var index = listenerArray.indexOf(listener);
  828. if (index !== -1) {
  829. listenerArray.splice(index, 1);
  830. }
  831. }
  832. },
  833. dispatchEvent: function (event) {
  834. if (this._listeners === undefined) return;
  835. var listeners = this._listeners;
  836. var listenerArray = listeners[event.type];
  837. if (listenerArray !== undefined) {
  838. event.target = this; // Make a copy, in case listeners are removed while iterating.
  839. var array = listenerArray.slice(0);
  840. for (var i = 0, l = array.length; i < l; i++) {
  841. array[i].call(this, event);
  842. }
  843. }
  844. }
  845. });
  846. /**
  847. * @author alteredq / http://alteredqualia.com/
  848. * @author mrdoob / http://mrdoob.com/
  849. * @author WestLangley / http://github.com/WestLangley
  850. * @author thezwap
  851. */
  852. var _lut = [];
  853. for (var i = 0; i < 256; i++) {
  854. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  855. }
  856. var MathUtils = {
  857. DEG2RAD: Math.PI / 180,
  858. RAD2DEG: 180 / Math.PI,
  859. generateUUID: function () {
  860. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  861. var d0 = Math.random() * 0xffffffff | 0;
  862. var d1 = Math.random() * 0xffffffff | 0;
  863. var d2 = Math.random() * 0xffffffff | 0;
  864. var d3 = Math.random() * 0xffffffff | 0;
  865. 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.
  866. return uuid.toUpperCase();
  867. },
  868. clamp: function (value, min, max) {
  869. return Math.max(min, Math.min(max, value));
  870. },
  871. // compute euclidian modulo of m % n
  872. // https://en.wikipedia.org/wiki/Modulo_operation
  873. euclideanModulo: function (n, m) {
  874. return (n % m + m) % m;
  875. },
  876. // Linear mapping from range <a1, a2> to range <b1, b2>
  877. mapLinear: function (x, a1, a2, b1, b2) {
  878. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  879. },
  880. // https://en.wikipedia.org/wiki/Linear_interpolation
  881. lerp: function (x, y, t) {
  882. return (1 - t) * x + t * y;
  883. },
  884. // http://en.wikipedia.org/wiki/Smoothstep
  885. smoothstep: function (x, min, max) {
  886. if (x <= min) return 0;
  887. if (x >= max) return 1;
  888. x = (x - min) / (max - min);
  889. return x * x * (3 - 2 * x);
  890. },
  891. smootherstep: function (x, min, max) {
  892. if (x <= min) return 0;
  893. if (x >= max) return 1;
  894. x = (x - min) / (max - min);
  895. return x * x * x * (x * (x * 6 - 15) + 10);
  896. },
  897. // Random integer from <low, high> interval
  898. randInt: function (low, high) {
  899. return low + Math.floor(Math.random() * (high - low + 1));
  900. },
  901. // Random float from <low, high> interval
  902. randFloat: function (low, high) {
  903. return low + Math.random() * (high - low);
  904. },
  905. // Random float from <-range/2, range/2> interval
  906. randFloatSpread: function (range) {
  907. return range * (0.5 - Math.random());
  908. },
  909. degToRad: function (degrees) {
  910. return degrees * MathUtils.DEG2RAD;
  911. },
  912. radToDeg: function (radians) {
  913. return radians * MathUtils.RAD2DEG;
  914. },
  915. isPowerOfTwo: function (value) {
  916. return (value & value - 1) === 0 && value !== 0;
  917. },
  918. ceilPowerOfTwo: function (value) {
  919. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  920. },
  921. floorPowerOfTwo: function (value) {
  922. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  923. },
  924. setQuaternionFromProperEuler: function (q, a, b, c, order) {
  925. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  926. // rotations are applied to the axes in the order specified by 'order'
  927. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  928. // angles are in radians
  929. var cos = Math.cos;
  930. var sin = Math.sin;
  931. var c2 = cos(b / 2);
  932. var s2 = sin(b / 2);
  933. var c13 = cos((a + c) / 2);
  934. var s13 = sin((a + c) / 2);
  935. var c1_3 = cos((a - c) / 2);
  936. var s1_3 = sin((a - c) / 2);
  937. var c3_1 = cos((c - a) / 2);
  938. var s3_1 = sin((c - a) / 2);
  939. if (order === 'XYX') {
  940. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  941. } else if (order === 'YZY') {
  942. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  943. } else if (order === 'ZXZ') {
  944. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  945. } else if (order === 'XZX') {
  946. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  947. } else if (order === 'YXY') {
  948. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  949. } else if (order === 'ZYZ') {
  950. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  951. } else {
  952. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order.');
  953. }
  954. }
  955. };
  956. /**
  957. * @author mrdoob / http://mrdoob.com/
  958. * @author philogb / http://blog.thejit.org/
  959. * @author egraether / http://egraether.com/
  960. * @author zz85 / http://www.lab4games.net/zz85/blog
  961. */
  962. exports.MathUtils = exports.Math = MathUtils;
  963. function Vector2(x, y) {
  964. this.x = x || 0;
  965. this.y = y || 0;
  966. }
  967. Object.defineProperties(Vector2.prototype, {
  968. "width": {
  969. get: function () {
  970. return this.x;
  971. },
  972. set: function (value) {
  973. this.x = value;
  974. }
  975. },
  976. "height": {
  977. get: function () {
  978. return this.y;
  979. },
  980. set: function (value) {
  981. this.y = value;
  982. }
  983. }
  984. });
  985. Object.assign(Vector2.prototype, {
  986. isVector2: true,
  987. set: function (x, y) {
  988. this.x = x;
  989. this.y = y;
  990. return this;
  991. },
  992. setScalar: function (scalar) {
  993. this.x = scalar;
  994. this.y = scalar;
  995. return this;
  996. },
  997. setX: function (x) {
  998. this.x = x;
  999. return this;
  1000. },
  1001. setY: function (y) {
  1002. this.y = y;
  1003. return this;
  1004. },
  1005. setComponent: function (index, value) {
  1006. switch (index) {
  1007. case 0:
  1008. this.x = value;
  1009. break;
  1010. case 1:
  1011. this.y = value;
  1012. break;
  1013. default:
  1014. throw new Error('index is out of range: ' + index);
  1015. }
  1016. return this;
  1017. },
  1018. getComponent: function (index) {
  1019. switch (index) {
  1020. case 0:
  1021. return this.x;
  1022. case 1:
  1023. return this.y;
  1024. default:
  1025. throw new Error('index is out of range: ' + index);
  1026. }
  1027. },
  1028. clone: function () {
  1029. return new this.constructor(this.x, this.y);
  1030. },
  1031. copy: function (v) {
  1032. this.x = v.x;
  1033. this.y = v.y;
  1034. return this;
  1035. },
  1036. add: function (v, w) {
  1037. if (w !== undefined) {
  1038. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1039. return this.addVectors(v, w);
  1040. }
  1041. this.x += v.x;
  1042. this.y += v.y;
  1043. return this;
  1044. },
  1045. addScalar: function (s) {
  1046. this.x += s;
  1047. this.y += s;
  1048. return this;
  1049. },
  1050. addVectors: function (a, b) {
  1051. this.x = a.x + b.x;
  1052. this.y = a.y + b.y;
  1053. return this;
  1054. },
  1055. addScaledVector: function (v, s) {
  1056. this.x += v.x * s;
  1057. this.y += v.y * s;
  1058. return this;
  1059. },
  1060. sub: function (v, w) {
  1061. if (w !== undefined) {
  1062. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1063. return this.subVectors(v, w);
  1064. }
  1065. this.x -= v.x;
  1066. this.y -= v.y;
  1067. return this;
  1068. },
  1069. subScalar: function (s) {
  1070. this.x -= s;
  1071. this.y -= s;
  1072. return this;
  1073. },
  1074. subVectors: function (a, b) {
  1075. this.x = a.x - b.x;
  1076. this.y = a.y - b.y;
  1077. return this;
  1078. },
  1079. multiply: function (v) {
  1080. this.x *= v.x;
  1081. this.y *= v.y;
  1082. return this;
  1083. },
  1084. multiplyScalar: function (scalar) {
  1085. this.x *= scalar;
  1086. this.y *= scalar;
  1087. return this;
  1088. },
  1089. divide: function (v) {
  1090. this.x /= v.x;
  1091. this.y /= v.y;
  1092. return this;
  1093. },
  1094. divideScalar: function (scalar) {
  1095. return this.multiplyScalar(1 / scalar);
  1096. },
  1097. applyMatrix3: function (m) {
  1098. var x = this.x,
  1099. y = this.y;
  1100. var e = m.elements;
  1101. this.x = e[0] * x + e[3] * y + e[6];
  1102. this.y = e[1] * x + e[4] * y + e[7];
  1103. return this;
  1104. },
  1105. min: function (v) {
  1106. this.x = Math.min(this.x, v.x);
  1107. this.y = Math.min(this.y, v.y);
  1108. return this;
  1109. },
  1110. max: function (v) {
  1111. this.x = Math.max(this.x, v.x);
  1112. this.y = Math.max(this.y, v.y);
  1113. return this;
  1114. },
  1115. clamp: function (min, max) {
  1116. // assumes min < max, componentwise
  1117. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1118. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1119. return this;
  1120. },
  1121. clampScalar: function (minVal, maxVal) {
  1122. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1123. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1124. return this;
  1125. },
  1126. clampLength: function (min, max) {
  1127. var length = this.length();
  1128. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1129. },
  1130. floor: function () {
  1131. this.x = Math.floor(this.x);
  1132. this.y = Math.floor(this.y);
  1133. return this;
  1134. },
  1135. ceil: function () {
  1136. this.x = Math.ceil(this.x);
  1137. this.y = Math.ceil(this.y);
  1138. return this;
  1139. },
  1140. round: function () {
  1141. this.x = Math.round(this.x);
  1142. this.y = Math.round(this.y);
  1143. return this;
  1144. },
  1145. roundToZero: function () {
  1146. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1147. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1148. return this;
  1149. },
  1150. negate: function () {
  1151. this.x = -this.x;
  1152. this.y = -this.y;
  1153. return this;
  1154. },
  1155. dot: function (v) {
  1156. return this.x * v.x + this.y * v.y;
  1157. },
  1158. cross: function (v) {
  1159. return this.x * v.y - this.y * v.x;
  1160. },
  1161. lengthSq: function () {
  1162. return this.x * this.x + this.y * this.y;
  1163. },
  1164. length: function () {
  1165. return Math.sqrt(this.x * this.x + this.y * this.y);
  1166. },
  1167. manhattanLength: function () {
  1168. return Math.abs(this.x) + Math.abs(this.y);
  1169. },
  1170. normalize: function () {
  1171. return this.divideScalar(this.length() || 1);
  1172. },
  1173. angle: function () {
  1174. // computes the angle in radians with respect to the positive x-axis
  1175. var angle = Math.atan2(-this.y, -this.x) + Math.PI;
  1176. return angle;
  1177. },
  1178. distanceTo: function (v) {
  1179. return Math.sqrt(this.distanceToSquared(v));
  1180. },
  1181. distanceToSquared: function (v) {
  1182. var dx = this.x - v.x,
  1183. dy = this.y - v.y;
  1184. return dx * dx + dy * dy;
  1185. },
  1186. manhattanDistanceTo: function (v) {
  1187. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  1188. },
  1189. setLength: function (length) {
  1190. return this.normalize().multiplyScalar(length);
  1191. },
  1192. lerp: function (v, alpha) {
  1193. this.x += (v.x - this.x) * alpha;
  1194. this.y += (v.y - this.y) * alpha;
  1195. return this;
  1196. },
  1197. lerpVectors: function (v1, v2, alpha) {
  1198. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  1199. },
  1200. equals: function (v) {
  1201. return v.x === this.x && v.y === this.y;
  1202. },
  1203. fromArray: function (array, offset) {
  1204. if (offset === undefined) offset = 0;
  1205. this.x = array[offset];
  1206. this.y = array[offset + 1];
  1207. return this;
  1208. },
  1209. toArray: function (array, offset) {
  1210. if (array === undefined) array = [];
  1211. if (offset === undefined) offset = 0;
  1212. array[offset] = this.x;
  1213. array[offset + 1] = this.y;
  1214. return array;
  1215. },
  1216. fromBufferAttribute: function (attribute, index, offset) {
  1217. if (offset !== undefined) {
  1218. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  1219. }
  1220. this.x = attribute.getX(index);
  1221. this.y = attribute.getY(index);
  1222. return this;
  1223. },
  1224. rotateAround: function (center, angle) {
  1225. var c = Math.cos(angle),
  1226. s = Math.sin(angle);
  1227. var x = this.x - center.x;
  1228. var y = this.y - center.y;
  1229. this.x = x * c - y * s + center.x;
  1230. this.y = x * s + y * c + center.y;
  1231. return this;
  1232. }
  1233. });
  1234. /**
  1235. * @author alteredq / http://alteredqualia.com/
  1236. * @author WestLangley / http://github.com/WestLangley
  1237. * @author bhouston / http://clara.io
  1238. * @author tschw
  1239. */
  1240. function Matrix3() {
  1241. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  1242. if (arguments.length > 0) {
  1243. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  1244. }
  1245. }
  1246. Object.assign(Matrix3.prototype, {
  1247. isMatrix3: true,
  1248. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  1249. var te = this.elements;
  1250. te[0] = n11;
  1251. te[1] = n21;
  1252. te[2] = n31;
  1253. te[3] = n12;
  1254. te[4] = n22;
  1255. te[5] = n32;
  1256. te[6] = n13;
  1257. te[7] = n23;
  1258. te[8] = n33;
  1259. return this;
  1260. },
  1261. identity: function () {
  1262. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  1263. return this;
  1264. },
  1265. clone: function () {
  1266. return new this.constructor().fromArray(this.elements);
  1267. },
  1268. copy: function (m) {
  1269. var te = this.elements;
  1270. var me = m.elements;
  1271. te[0] = me[0];
  1272. te[1] = me[1];
  1273. te[2] = me[2];
  1274. te[3] = me[3];
  1275. te[4] = me[4];
  1276. te[5] = me[5];
  1277. te[6] = me[6];
  1278. te[7] = me[7];
  1279. te[8] = me[8];
  1280. return this;
  1281. },
  1282. extractBasis: function (xAxis, yAxis, zAxis) {
  1283. xAxis.setFromMatrix3Column(this, 0);
  1284. yAxis.setFromMatrix3Column(this, 1);
  1285. zAxis.setFromMatrix3Column(this, 2);
  1286. return this;
  1287. },
  1288. setFromMatrix4: function (m) {
  1289. var me = m.elements;
  1290. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  1291. return this;
  1292. },
  1293. multiply: function (m) {
  1294. return this.multiplyMatrices(this, m);
  1295. },
  1296. premultiply: function (m) {
  1297. return this.multiplyMatrices(m, this);
  1298. },
  1299. multiplyMatrices: function (a, b) {
  1300. var ae = a.elements;
  1301. var be = b.elements;
  1302. var te = this.elements;
  1303. var a11 = ae[0],
  1304. a12 = ae[3],
  1305. a13 = ae[6];
  1306. var a21 = ae[1],
  1307. a22 = ae[4],
  1308. a23 = ae[7];
  1309. var a31 = ae[2],
  1310. a32 = ae[5],
  1311. a33 = ae[8];
  1312. var b11 = be[0],
  1313. b12 = be[3],
  1314. b13 = be[6];
  1315. var b21 = be[1],
  1316. b22 = be[4],
  1317. b23 = be[7];
  1318. var b31 = be[2],
  1319. b32 = be[5],
  1320. b33 = be[8];
  1321. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  1322. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  1323. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  1324. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  1325. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  1326. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  1327. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  1328. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  1329. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  1330. return this;
  1331. },
  1332. multiplyScalar: function (s) {
  1333. var te = this.elements;
  1334. te[0] *= s;
  1335. te[3] *= s;
  1336. te[6] *= s;
  1337. te[1] *= s;
  1338. te[4] *= s;
  1339. te[7] *= s;
  1340. te[2] *= s;
  1341. te[5] *= s;
  1342. te[8] *= s;
  1343. return this;
  1344. },
  1345. determinant: function () {
  1346. var te = this.elements;
  1347. var a = te[0],
  1348. b = te[1],
  1349. c = te[2],
  1350. d = te[3],
  1351. e = te[4],
  1352. f = te[5],
  1353. g = te[6],
  1354. h = te[7],
  1355. i = te[8];
  1356. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1357. },
  1358. getInverse: function (matrix, throwOnDegenerate) {
  1359. if (throwOnDegenerate !== undefined) {
  1360. console.warn("THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate.");
  1361. }
  1362. var me = matrix.elements,
  1363. te = this.elements,
  1364. n11 = me[0],
  1365. n21 = me[1],
  1366. n31 = me[2],
  1367. n12 = me[3],
  1368. n22 = me[4],
  1369. n32 = me[5],
  1370. n13 = me[6],
  1371. n23 = me[7],
  1372. n33 = me[8],
  1373. t11 = n33 * n22 - n32 * n23,
  1374. t12 = n32 * n13 - n33 * n12,
  1375. t13 = n23 * n12 - n22 * n13,
  1376. det = n11 * t11 + n21 * t12 + n31 * t13;
  1377. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  1378. var detInv = 1 / det;
  1379. te[0] = t11 * detInv;
  1380. te[1] = (n31 * n23 - n33 * n21) * detInv;
  1381. te[2] = (n32 * n21 - n31 * n22) * detInv;
  1382. te[3] = t12 * detInv;
  1383. te[4] = (n33 * n11 - n31 * n13) * detInv;
  1384. te[5] = (n31 * n12 - n32 * n11) * detInv;
  1385. te[6] = t13 * detInv;
  1386. te[7] = (n21 * n13 - n23 * n11) * detInv;
  1387. te[8] = (n22 * n11 - n21 * n12) * detInv;
  1388. return this;
  1389. },
  1390. transpose: function () {
  1391. var tmp,
  1392. m = this.elements;
  1393. tmp = m[1];
  1394. m[1] = m[3];
  1395. m[3] = tmp;
  1396. tmp = m[2];
  1397. m[2] = m[6];
  1398. m[6] = tmp;
  1399. tmp = m[5];
  1400. m[5] = m[7];
  1401. m[7] = tmp;
  1402. return this;
  1403. },
  1404. getNormalMatrix: function (matrix4) {
  1405. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  1406. },
  1407. transposeIntoArray: function (r) {
  1408. var m = this.elements;
  1409. r[0] = m[0];
  1410. r[1] = m[3];
  1411. r[2] = m[6];
  1412. r[3] = m[1];
  1413. r[4] = m[4];
  1414. r[5] = m[7];
  1415. r[6] = m[2];
  1416. r[7] = m[5];
  1417. r[8] = m[8];
  1418. return this;
  1419. },
  1420. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  1421. var c = Math.cos(rotation);
  1422. var s = Math.sin(rotation);
  1423. 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);
  1424. },
  1425. scale: function (sx, sy) {
  1426. var te = this.elements;
  1427. te[0] *= sx;
  1428. te[3] *= sx;
  1429. te[6] *= sx;
  1430. te[1] *= sy;
  1431. te[4] *= sy;
  1432. te[7] *= sy;
  1433. return this;
  1434. },
  1435. rotate: function (theta) {
  1436. var c = Math.cos(theta);
  1437. var s = Math.sin(theta);
  1438. var te = this.elements;
  1439. var a11 = te[0],
  1440. a12 = te[3],
  1441. a13 = te[6];
  1442. var a21 = te[1],
  1443. a22 = te[4],
  1444. a23 = te[7];
  1445. te[0] = c * a11 + s * a21;
  1446. te[3] = c * a12 + s * a22;
  1447. te[6] = c * a13 + s * a23;
  1448. te[1] = -s * a11 + c * a21;
  1449. te[4] = -s * a12 + c * a22;
  1450. te[7] = -s * a13 + c * a23;
  1451. return this;
  1452. },
  1453. translate: function (tx, ty) {
  1454. var te = this.elements;
  1455. te[0] += tx * te[2];
  1456. te[3] += tx * te[5];
  1457. te[6] += tx * te[8];
  1458. te[1] += ty * te[2];
  1459. te[4] += ty * te[5];
  1460. te[7] += ty * te[8];
  1461. return this;
  1462. },
  1463. equals: function (matrix) {
  1464. var te = this.elements;
  1465. var me = matrix.elements;
  1466. for (var i = 0; i < 9; i++) {
  1467. if (te[i] !== me[i]) return false;
  1468. }
  1469. return true;
  1470. },
  1471. fromArray: function (array, offset) {
  1472. if (offset === undefined) offset = 0;
  1473. for (var i = 0; i < 9; i++) {
  1474. this.elements[i] = array[i + offset];
  1475. }
  1476. return this;
  1477. },
  1478. toArray: function (array, offset) {
  1479. if (array === undefined) array = [];
  1480. if (offset === undefined) offset = 0;
  1481. var te = this.elements;
  1482. array[offset] = te[0];
  1483. array[offset + 1] = te[1];
  1484. array[offset + 2] = te[2];
  1485. array[offset + 3] = te[3];
  1486. array[offset + 4] = te[4];
  1487. array[offset + 5] = te[5];
  1488. array[offset + 6] = te[6];
  1489. array[offset + 7] = te[7];
  1490. array[offset + 8] = te[8];
  1491. return array;
  1492. }
  1493. });
  1494. /**
  1495. * @author mrdoob / http://mrdoob.com/
  1496. * @author alteredq / http://alteredqualia.com/
  1497. * @author szimek / https://github.com/szimek/
  1498. */
  1499. var _canvas;
  1500. var ImageUtils = {
  1501. getDataURL: function (image) {
  1502. var canvas;
  1503. if (typeof HTMLCanvasElement == 'undefined') {
  1504. return image.src;
  1505. } else if (image instanceof HTMLCanvasElement) {
  1506. canvas = image;
  1507. } else {
  1508. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  1509. _canvas.width = image.width;
  1510. _canvas.height = image.height;
  1511. var context = _canvas.getContext('2d');
  1512. if (image instanceof ImageData) {
  1513. context.putImageData(image, 0, 0);
  1514. } else {
  1515. context.drawImage(image, 0, 0, image.width, image.height);
  1516. }
  1517. canvas = _canvas;
  1518. }
  1519. if (canvas.width > 2048 || canvas.height > 2048) {
  1520. return canvas.toDataURL('image/jpeg', 0.6);
  1521. } else {
  1522. return canvas.toDataURL('image/png');
  1523. }
  1524. }
  1525. };
  1526. /**
  1527. * @author mrdoob / http://mrdoob.com/
  1528. * @author alteredq / http://alteredqualia.com/
  1529. * @author szimek / https://github.com/szimek/
  1530. */
  1531. exports.ImageUtils = ImageUtils;
  1532. var textureId = 0;
  1533. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  1534. Object.defineProperty(this, 'id', {
  1535. value: textureId++
  1536. });
  1537. this.uuid = MathUtils.generateUUID();
  1538. this.name = '';
  1539. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  1540. this.mipmaps = [];
  1541. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  1542. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  1543. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  1544. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  1545. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  1546. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  1547. this.format = format !== undefined ? format : RGBAFormat;
  1548. this.internalFormat = null;
  1549. this.type = type !== undefined ? type : UnsignedByteType;
  1550. this.offset = new Vector2(0, 0);
  1551. this.repeat = new Vector2(1, 1);
  1552. this.center = new Vector2(0, 0);
  1553. this.rotation = 0;
  1554. this.matrixAutoUpdate = true;
  1555. this.matrix = new Matrix3();
  1556. this.generateMipmaps = true;
  1557. this.premultiplyAlpha = false;
  1558. this.flipY = true;
  1559. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1560. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1561. //
  1562. // Also changing the encoding after already used by a Material will not automatically make the Material
  1563. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1564. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  1565. this.version = 0;
  1566. this.onUpdate = null;
  1567. }
  1568. Texture.DEFAULT_IMAGE = undefined;
  1569. Texture.DEFAULT_MAPPING = UVMapping;
  1570. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  1571. constructor: Texture,
  1572. isTexture: true,
  1573. updateMatrix: function () {
  1574. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1575. },
  1576. clone: function () {
  1577. return new this.constructor().copy(this);
  1578. },
  1579. copy: function (source) {
  1580. this.name = source.name;
  1581. this.image = source.image;
  1582. this.mipmaps = source.mipmaps.slice(0);
  1583. this.mapping = source.mapping;
  1584. this.wrapS = source.wrapS;
  1585. this.wrapT = source.wrapT;
  1586. this.magFilter = source.magFilter;
  1587. this.minFilter = source.minFilter;
  1588. this.anisotropy = source.anisotropy;
  1589. this.format = source.format;
  1590. this.internalFormat = source.internalFormat;
  1591. this.type = source.type;
  1592. this.offset.copy(source.offset);
  1593. this.repeat.copy(source.repeat);
  1594. this.center.copy(source.center);
  1595. this.rotation = source.rotation;
  1596. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1597. this.matrix.copy(source.matrix);
  1598. this.generateMipmaps = source.generateMipmaps;
  1599. this.premultiplyAlpha = source.premultiplyAlpha;
  1600. this.flipY = source.flipY;
  1601. this.unpackAlignment = source.unpackAlignment;
  1602. this.encoding = source.encoding;
  1603. return this;
  1604. },
  1605. toJSON: function (meta) {
  1606. var isRootObject = meta === undefined || typeof meta === 'string';
  1607. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1608. return meta.textures[this.uuid];
  1609. }
  1610. var output = {
  1611. metadata: {
  1612. version: 4.5,
  1613. type: 'Texture',
  1614. generator: 'Texture.toJSON'
  1615. },
  1616. uuid: this.uuid,
  1617. name: this.name,
  1618. mapping: this.mapping,
  1619. repeat: [this.repeat.x, this.repeat.y],
  1620. offset: [this.offset.x, this.offset.y],
  1621. center: [this.center.x, this.center.y],
  1622. rotation: this.rotation,
  1623. wrap: [this.wrapS, this.wrapT],
  1624. format: this.format,
  1625. type: this.type,
  1626. encoding: this.encoding,
  1627. minFilter: this.minFilter,
  1628. magFilter: this.magFilter,
  1629. anisotropy: this.anisotropy,
  1630. flipY: this.flipY,
  1631. premultiplyAlpha: this.premultiplyAlpha,
  1632. unpackAlignment: this.unpackAlignment
  1633. };
  1634. if (this.image !== undefined) {
  1635. // TODO: Move to THREE.Image
  1636. var image = this.image;
  1637. if (image.uuid === undefined) {
  1638. image.uuid = MathUtils.generateUUID(); // UGH
  1639. }
  1640. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1641. var url;
  1642. if (Array.isArray(image)) {
  1643. // process array of images e.g. CubeTexture
  1644. url = [];
  1645. for (var i = 0, l = image.length; i < l; i++) {
  1646. url.push(ImageUtils.getDataURL(image[i]));
  1647. }
  1648. } else {
  1649. // process single image
  1650. url = ImageUtils.getDataURL(image);
  1651. }
  1652. meta.images[image.uuid] = {
  1653. uuid: image.uuid,
  1654. url: url
  1655. };
  1656. }
  1657. output.image = image.uuid;
  1658. }
  1659. if (!isRootObject) {
  1660. meta.textures[this.uuid] = output;
  1661. }
  1662. return output;
  1663. },
  1664. dispose: function () {
  1665. this.dispatchEvent({
  1666. type: 'dispose'
  1667. });
  1668. },
  1669. transformUv: function (uv) {
  1670. if (this.mapping !== UVMapping) return uv;
  1671. uv.applyMatrix3(this.matrix);
  1672. if (uv.x < 0 || uv.x > 1) {
  1673. switch (this.wrapS) {
  1674. case RepeatWrapping:
  1675. uv.x = uv.x - Math.floor(uv.x);
  1676. break;
  1677. case ClampToEdgeWrapping:
  1678. uv.x = uv.x < 0 ? 0 : 1;
  1679. break;
  1680. case MirroredRepeatWrapping:
  1681. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1682. uv.x = Math.ceil(uv.x) - uv.x;
  1683. } else {
  1684. uv.x = uv.x - Math.floor(uv.x);
  1685. }
  1686. break;
  1687. }
  1688. }
  1689. if (uv.y < 0 || uv.y > 1) {
  1690. switch (this.wrapT) {
  1691. case RepeatWrapping:
  1692. uv.y = uv.y - Math.floor(uv.y);
  1693. break;
  1694. case ClampToEdgeWrapping:
  1695. uv.y = uv.y < 0 ? 0 : 1;
  1696. break;
  1697. case MirroredRepeatWrapping:
  1698. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1699. uv.y = Math.ceil(uv.y) - uv.y;
  1700. } else {
  1701. uv.y = uv.y - Math.floor(uv.y);
  1702. }
  1703. break;
  1704. }
  1705. }
  1706. if (this.flipY) {
  1707. uv.y = 1 - uv.y;
  1708. }
  1709. return uv;
  1710. }
  1711. });
  1712. Object.defineProperty(Texture.prototype, "needsUpdate", {
  1713. set: function (value) {
  1714. if (value === true) this.version++;
  1715. }
  1716. });
  1717. /**
  1718. * @author supereggbert / http://www.paulbrunt.co.uk/
  1719. * @author philogb / http://blog.thejit.org/
  1720. * @author mikael emtinger / http://gomo.se/
  1721. * @author egraether / http://egraether.com/
  1722. * @author WestLangley / http://github.com/WestLangley
  1723. */
  1724. function Vector4(x, y, z, w) {
  1725. this.x = x || 0;
  1726. this.y = y || 0;
  1727. this.z = z || 0;
  1728. this.w = w !== undefined ? w : 1;
  1729. }
  1730. Object.defineProperties(Vector4.prototype, {
  1731. "width": {
  1732. get: function () {
  1733. return this.z;
  1734. },
  1735. set: function (value) {
  1736. this.z = value;
  1737. }
  1738. },
  1739. "height": {
  1740. get: function () {
  1741. return this.w;
  1742. },
  1743. set: function (value) {
  1744. this.w = value;
  1745. }
  1746. }
  1747. });
  1748. Object.assign(Vector4.prototype, {
  1749. isVector4: true,
  1750. set: function (x, y, z, w) {
  1751. this.x = x;
  1752. this.y = y;
  1753. this.z = z;
  1754. this.w = w;
  1755. return this;
  1756. },
  1757. setScalar: function (scalar) {
  1758. this.x = scalar;
  1759. this.y = scalar;
  1760. this.z = scalar;
  1761. this.w = scalar;
  1762. return this;
  1763. },
  1764. setX: function (x) {
  1765. this.x = x;
  1766. return this;
  1767. },
  1768. setY: function (y) {
  1769. this.y = y;
  1770. return this;
  1771. },
  1772. setZ: function (z) {
  1773. this.z = z;
  1774. return this;
  1775. },
  1776. setW: function (w) {
  1777. this.w = w;
  1778. return this;
  1779. },
  1780. setComponent: function (index, value) {
  1781. switch (index) {
  1782. case 0:
  1783. this.x = value;
  1784. break;
  1785. case 1:
  1786. this.y = value;
  1787. break;
  1788. case 2:
  1789. this.z = value;
  1790. break;
  1791. case 3:
  1792. this.w = value;
  1793. break;
  1794. default:
  1795. throw new Error('index is out of range: ' + index);
  1796. }
  1797. return this;
  1798. },
  1799. getComponent: function (index) {
  1800. switch (index) {
  1801. case 0:
  1802. return this.x;
  1803. case 1:
  1804. return this.y;
  1805. case 2:
  1806. return this.z;
  1807. case 3:
  1808. return this.w;
  1809. default:
  1810. throw new Error('index is out of range: ' + index);
  1811. }
  1812. },
  1813. clone: function () {
  1814. return new this.constructor(this.x, this.y, this.z, this.w);
  1815. },
  1816. copy: function (v) {
  1817. this.x = v.x;
  1818. this.y = v.y;
  1819. this.z = v.z;
  1820. this.w = v.w !== undefined ? v.w : 1;
  1821. return this;
  1822. },
  1823. add: function (v, w) {
  1824. if (w !== undefined) {
  1825. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1826. return this.addVectors(v, w);
  1827. }
  1828. this.x += v.x;
  1829. this.y += v.y;
  1830. this.z += v.z;
  1831. this.w += v.w;
  1832. return this;
  1833. },
  1834. addScalar: function (s) {
  1835. this.x += s;
  1836. this.y += s;
  1837. this.z += s;
  1838. this.w += s;
  1839. return this;
  1840. },
  1841. addVectors: function (a, b) {
  1842. this.x = a.x + b.x;
  1843. this.y = a.y + b.y;
  1844. this.z = a.z + b.z;
  1845. this.w = a.w + b.w;
  1846. return this;
  1847. },
  1848. addScaledVector: function (v, s) {
  1849. this.x += v.x * s;
  1850. this.y += v.y * s;
  1851. this.z += v.z * s;
  1852. this.w += v.w * s;
  1853. return this;
  1854. },
  1855. sub: function (v, w) {
  1856. if (w !== undefined) {
  1857. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1858. return this.subVectors(v, w);
  1859. }
  1860. this.x -= v.x;
  1861. this.y -= v.y;
  1862. this.z -= v.z;
  1863. this.w -= v.w;
  1864. return this;
  1865. },
  1866. subScalar: function (s) {
  1867. this.x -= s;
  1868. this.y -= s;
  1869. this.z -= s;
  1870. this.w -= s;
  1871. return this;
  1872. },
  1873. subVectors: function (a, b) {
  1874. this.x = a.x - b.x;
  1875. this.y = a.y - b.y;
  1876. this.z = a.z - b.z;
  1877. this.w = a.w - b.w;
  1878. return this;
  1879. },
  1880. multiplyScalar: function (scalar) {
  1881. this.x *= scalar;
  1882. this.y *= scalar;
  1883. this.z *= scalar;
  1884. this.w *= scalar;
  1885. return this;
  1886. },
  1887. applyMatrix4: function (m) {
  1888. var x = this.x,
  1889. y = this.y,
  1890. z = this.z,
  1891. w = this.w;
  1892. var e = m.elements;
  1893. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1894. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1895. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1896. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1897. return this;
  1898. },
  1899. divideScalar: function (scalar) {
  1900. return this.multiplyScalar(1 / scalar);
  1901. },
  1902. setAxisAngleFromQuaternion: function (q) {
  1903. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1904. // q is assumed to be normalized
  1905. this.w = 2 * Math.acos(q.w);
  1906. var s = Math.sqrt(1 - q.w * q.w);
  1907. if (s < 0.0001) {
  1908. this.x = 1;
  1909. this.y = 0;
  1910. this.z = 0;
  1911. } else {
  1912. this.x = q.x / s;
  1913. this.y = q.y / s;
  1914. this.z = q.z / s;
  1915. }
  1916. return this;
  1917. },
  1918. setAxisAngleFromRotationMatrix: function (m) {
  1919. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1920. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1921. var angle,
  1922. x,
  1923. y,
  1924. z,
  1925. // variables for result
  1926. epsilon = 0.01,
  1927. // margin to allow for rounding errors
  1928. epsilon2 = 0.1,
  1929. // margin to distinguish between 0 and 180 degrees
  1930. te = m.elements,
  1931. m11 = te[0],
  1932. m12 = te[4],
  1933. m13 = te[8],
  1934. m21 = te[1],
  1935. m22 = te[5],
  1936. m23 = te[9],
  1937. m31 = te[2],
  1938. m32 = te[6],
  1939. m33 = te[10];
  1940. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1941. // singularity found
  1942. // first check for identity matrix which must have +1 for all terms
  1943. // in leading diagonal and zero in other terms
  1944. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1945. // this singularity is identity matrix so angle = 0
  1946. this.set(1, 0, 0, 0);
  1947. return this; // zero angle, arbitrary axis
  1948. } // otherwise this singularity is angle = 180
  1949. angle = Math.PI;
  1950. var xx = (m11 + 1) / 2;
  1951. var yy = (m22 + 1) / 2;
  1952. var zz = (m33 + 1) / 2;
  1953. var xy = (m12 + m21) / 4;
  1954. var xz = (m13 + m31) / 4;
  1955. var yz = (m23 + m32) / 4;
  1956. if (xx > yy && xx > zz) {
  1957. // m11 is the largest diagonal term
  1958. if (xx < epsilon) {
  1959. x = 0;
  1960. y = 0.707106781;
  1961. z = 0.707106781;
  1962. } else {
  1963. x = Math.sqrt(xx);
  1964. y = xy / x;
  1965. z = xz / x;
  1966. }
  1967. } else if (yy > zz) {
  1968. // m22 is the largest diagonal term
  1969. if (yy < epsilon) {
  1970. x = 0.707106781;
  1971. y = 0;
  1972. z = 0.707106781;
  1973. } else {
  1974. y = Math.sqrt(yy);
  1975. x = xy / y;
  1976. z = yz / y;
  1977. }
  1978. } else {
  1979. // m33 is the largest diagonal term so base result on this
  1980. if (zz < epsilon) {
  1981. x = 0.707106781;
  1982. y = 0.707106781;
  1983. z = 0;
  1984. } else {
  1985. z = Math.sqrt(zz);
  1986. x = xz / z;
  1987. y = yz / z;
  1988. }
  1989. }
  1990. this.set(x, y, z, angle);
  1991. return this; // return 180 deg rotation
  1992. } // as we have reached here there are no singularities so we can handle normally
  1993. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1994. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1995. // caught by singularity test above, but I've left it in just in case
  1996. this.x = (m32 - m23) / s;
  1997. this.y = (m13 - m31) / s;
  1998. this.z = (m21 - m12) / s;
  1999. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2000. return this;
  2001. },
  2002. min: function (v) {
  2003. this.x = Math.min(this.x, v.x);
  2004. this.y = Math.min(this.y, v.y);
  2005. this.z = Math.min(this.z, v.z);
  2006. this.w = Math.min(this.w, v.w);
  2007. return this;
  2008. },
  2009. max: function (v) {
  2010. this.x = Math.max(this.x, v.x);
  2011. this.y = Math.max(this.y, v.y);
  2012. this.z = Math.max(this.z, v.z);
  2013. this.w = Math.max(this.w, v.w);
  2014. return this;
  2015. },
  2016. clamp: function (min, max) {
  2017. // assumes min < max, componentwise
  2018. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2019. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2020. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2021. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2022. return this;
  2023. },
  2024. clampScalar: function (minVal, maxVal) {
  2025. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2026. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2027. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2028. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2029. return this;
  2030. },
  2031. clampLength: function (min, max) {
  2032. var length = this.length();
  2033. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2034. },
  2035. floor: function () {
  2036. this.x = Math.floor(this.x);
  2037. this.y = Math.floor(this.y);
  2038. this.z = Math.floor(this.z);
  2039. this.w = Math.floor(this.w);
  2040. return this;
  2041. },
  2042. ceil: function () {
  2043. this.x = Math.ceil(this.x);
  2044. this.y = Math.ceil(this.y);
  2045. this.z = Math.ceil(this.z);
  2046. this.w = Math.ceil(this.w);
  2047. return this;
  2048. },
  2049. round: function () {
  2050. this.x = Math.round(this.x);
  2051. this.y = Math.round(this.y);
  2052. this.z = Math.round(this.z);
  2053. this.w = Math.round(this.w);
  2054. return this;
  2055. },
  2056. roundToZero: function () {
  2057. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2058. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2059. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2060. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2061. return this;
  2062. },
  2063. negate: function () {
  2064. this.x = -this.x;
  2065. this.y = -this.y;
  2066. this.z = -this.z;
  2067. this.w = -this.w;
  2068. return this;
  2069. },
  2070. dot: function (v) {
  2071. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2072. },
  2073. lengthSq: function () {
  2074. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2075. },
  2076. length: function () {
  2077. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2078. },
  2079. manhattanLength: function () {
  2080. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2081. },
  2082. normalize: function () {
  2083. return this.divideScalar(this.length() || 1);
  2084. },
  2085. setLength: function (length) {
  2086. return this.normalize().multiplyScalar(length);
  2087. },
  2088. lerp: function (v, alpha) {
  2089. this.x += (v.x - this.x) * alpha;
  2090. this.y += (v.y - this.y) * alpha;
  2091. this.z += (v.z - this.z) * alpha;
  2092. this.w += (v.w - this.w) * alpha;
  2093. return this;
  2094. },
  2095. lerpVectors: function (v1, v2, alpha) {
  2096. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2097. },
  2098. equals: function (v) {
  2099. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2100. },
  2101. fromArray: function (array, offset) {
  2102. if (offset === undefined) offset = 0;
  2103. this.x = array[offset];
  2104. this.y = array[offset + 1];
  2105. this.z = array[offset + 2];
  2106. this.w = array[offset + 3];
  2107. return this;
  2108. },
  2109. toArray: function (array, offset) {
  2110. if (array === undefined) array = [];
  2111. if (offset === undefined) offset = 0;
  2112. array[offset] = this.x;
  2113. array[offset + 1] = this.y;
  2114. array[offset + 2] = this.z;
  2115. array[offset + 3] = this.w;
  2116. return array;
  2117. },
  2118. fromBufferAttribute: function (attribute, index, offset) {
  2119. if (offset !== undefined) {
  2120. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  2121. }
  2122. this.x = attribute.getX(index);
  2123. this.y = attribute.getY(index);
  2124. this.z = attribute.getZ(index);
  2125. this.w = attribute.getW(index);
  2126. return this;
  2127. }
  2128. });
  2129. /**
  2130. * @author szimek / https://github.com/szimek/
  2131. * @author alteredq / http://alteredqualia.com/
  2132. * @author Marius Kintel / https://github.com/kintel
  2133. */
  2134. /*
  2135. In options, we can specify:
  2136. * Texture parameters for an auto-generated target texture
  2137. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2138. */
  2139. function WebGLRenderTarget(width, height, options) {
  2140. this.width = width;
  2141. this.height = height;
  2142. this.scissor = new Vector4(0, 0, width, height);
  2143. this.scissorTest = false;
  2144. this.viewport = new Vector4(0, 0, width, height);
  2145. options = options || {};
  2146. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2147. this.texture.image = {};
  2148. this.texture.image.width = width;
  2149. this.texture.image.height = height;
  2150. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2151. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2152. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2153. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  2154. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2155. }
  2156. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  2157. constructor: WebGLRenderTarget,
  2158. isWebGLRenderTarget: true,
  2159. setSize: function (width, height) {
  2160. if (this.width !== width || this.height !== height) {
  2161. this.width = width;
  2162. this.height = height;
  2163. this.texture.image.width = width;
  2164. this.texture.image.height = height;
  2165. this.dispose();
  2166. }
  2167. this.viewport.set(0, 0, width, height);
  2168. this.scissor.set(0, 0, width, height);
  2169. },
  2170. clone: function () {
  2171. return new this.constructor().copy(this);
  2172. },
  2173. copy: function (source) {
  2174. this.width = source.width;
  2175. this.height = source.height;
  2176. this.viewport.copy(source.viewport);
  2177. this.texture = source.texture.clone();
  2178. this.depthBuffer = source.depthBuffer;
  2179. this.stencilBuffer = source.stencilBuffer;
  2180. this.depthTexture = source.depthTexture;
  2181. return this;
  2182. },
  2183. dispose: function () {
  2184. this.dispatchEvent({
  2185. type: 'dispose'
  2186. });
  2187. }
  2188. });
  2189. /**
  2190. * @author Mugen87 / https://github.com/Mugen87
  2191. * @author Matt DesLauriers / @mattdesl
  2192. */
  2193. function WebGLMultisampleRenderTarget(width, height, options) {
  2194. WebGLRenderTarget.call(this, width, height, options);
  2195. this.samples = 4;
  2196. }
  2197. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  2198. constructor: WebGLMultisampleRenderTarget,
  2199. isWebGLMultisampleRenderTarget: true,
  2200. copy: function (source) {
  2201. WebGLRenderTarget.prototype.copy.call(this, source);
  2202. this.samples = source.samples;
  2203. return this;
  2204. }
  2205. });
  2206. /**
  2207. * @author mikael emtinger / http://gomo.se/
  2208. * @author alteredq / http://alteredqualia.com/
  2209. * @author WestLangley / http://github.com/WestLangley
  2210. * @author bhouston / http://clara.io
  2211. */
  2212. function Quaternion(x, y, z, w) {
  2213. this._x = x || 0;
  2214. this._y = y || 0;
  2215. this._z = z || 0;
  2216. this._w = w !== undefined ? w : 1;
  2217. }
  2218. Object.assign(Quaternion, {
  2219. slerp: function (qa, qb, qm, t) {
  2220. return qm.copy(qa).slerp(qb, t);
  2221. },
  2222. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2223. // fuzz-free, array-based Quaternion SLERP operation
  2224. var x0 = src0[srcOffset0 + 0],
  2225. y0 = src0[srcOffset0 + 1],
  2226. z0 = src0[srcOffset0 + 2],
  2227. w0 = src0[srcOffset0 + 3],
  2228. x1 = src1[srcOffset1 + 0],
  2229. y1 = src1[srcOffset1 + 1],
  2230. z1 = src1[srcOffset1 + 2],
  2231. w1 = src1[srcOffset1 + 3];
  2232. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2233. var s = 1 - t,
  2234. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2235. dir = cos >= 0 ? 1 : -1,
  2236. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2237. if (sqrSin > Number.EPSILON) {
  2238. var sin = Math.sqrt(sqrSin),
  2239. len = Math.atan2(sin, cos * dir);
  2240. s = Math.sin(s * len) / sin;
  2241. t = Math.sin(t * len) / sin;
  2242. }
  2243. var tDir = t * dir;
  2244. x0 = x0 * s + x1 * tDir;
  2245. y0 = y0 * s + y1 * tDir;
  2246. z0 = z0 * s + z1 * tDir;
  2247. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2248. if (s === 1 - t) {
  2249. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2250. x0 *= f;
  2251. y0 *= f;
  2252. z0 *= f;
  2253. w0 *= f;
  2254. }
  2255. }
  2256. dst[dstOffset] = x0;
  2257. dst[dstOffset + 1] = y0;
  2258. dst[dstOffset + 2] = z0;
  2259. dst[dstOffset + 3] = w0;
  2260. }
  2261. });
  2262. Object.defineProperties(Quaternion.prototype, {
  2263. x: {
  2264. get: function () {
  2265. return this._x;
  2266. },
  2267. set: function (value) {
  2268. this._x = value;
  2269. this._onChangeCallback();
  2270. }
  2271. },
  2272. y: {
  2273. get: function () {
  2274. return this._y;
  2275. },
  2276. set: function (value) {
  2277. this._y = value;
  2278. this._onChangeCallback();
  2279. }
  2280. },
  2281. z: {
  2282. get: function () {
  2283. return this._z;
  2284. },
  2285. set: function (value) {
  2286. this._z = value;
  2287. this._onChangeCallback();
  2288. }
  2289. },
  2290. w: {
  2291. get: function () {
  2292. return this._w;
  2293. },
  2294. set: function (value) {
  2295. this._w = value;
  2296. this._onChangeCallback();
  2297. }
  2298. }
  2299. });
  2300. Object.assign(Quaternion.prototype, {
  2301. isQuaternion: true,
  2302. set: function (x, y, z, w) {
  2303. this._x = x;
  2304. this._y = y;
  2305. this._z = z;
  2306. this._w = w;
  2307. this._onChangeCallback();
  2308. return this;
  2309. },
  2310. clone: function () {
  2311. return new this.constructor(this._x, this._y, this._z, this._w);
  2312. },
  2313. copy: function (quaternion) {
  2314. this._x = quaternion.x;
  2315. this._y = quaternion.y;
  2316. this._z = quaternion.z;
  2317. this._w = quaternion.w;
  2318. this._onChangeCallback();
  2319. return this;
  2320. },
  2321. setFromEuler: function (euler, update) {
  2322. if (!(euler && euler.isEuler)) {
  2323. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2324. }
  2325. var x = euler._x,
  2326. y = euler._y,
  2327. z = euler._z,
  2328. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2329. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2330. // content/SpinCalc.m
  2331. var cos = Math.cos;
  2332. var sin = Math.sin;
  2333. var c1 = cos(x / 2);
  2334. var c2 = cos(y / 2);
  2335. var c3 = cos(z / 2);
  2336. var s1 = sin(x / 2);
  2337. var s2 = sin(y / 2);
  2338. var s3 = sin(z / 2);
  2339. if (order === 'XYZ') {
  2340. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2341. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2342. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2343. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2344. } else if (order === 'YXZ') {
  2345. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2346. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2347. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2348. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2349. } else if (order === 'ZXY') {
  2350. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2351. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2352. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2353. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2354. } else if (order === 'ZYX') {
  2355. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2356. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2357. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2358. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2359. } else if (order === 'YZX') {
  2360. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2361. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2362. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2363. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2364. } else if (order === 'XZY') {
  2365. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2366. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2367. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2368. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2369. }
  2370. if (update !== false) this._onChangeCallback();
  2371. return this;
  2372. },
  2373. setFromAxisAngle: function (axis, angle) {
  2374. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2375. // assumes axis is normalized
  2376. var halfAngle = angle / 2,
  2377. s = Math.sin(halfAngle);
  2378. this._x = axis.x * s;
  2379. this._y = axis.y * s;
  2380. this._z = axis.z * s;
  2381. this._w = Math.cos(halfAngle);
  2382. this._onChangeCallback();
  2383. return this;
  2384. },
  2385. setFromRotationMatrix: function (m) {
  2386. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2387. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2388. var te = m.elements,
  2389. m11 = te[0],
  2390. m12 = te[4],
  2391. m13 = te[8],
  2392. m21 = te[1],
  2393. m22 = te[5],
  2394. m23 = te[9],
  2395. m31 = te[2],
  2396. m32 = te[6],
  2397. m33 = te[10],
  2398. trace = m11 + m22 + m33,
  2399. s;
  2400. if (trace > 0) {
  2401. s = 0.5 / Math.sqrt(trace + 1.0);
  2402. this._w = 0.25 / s;
  2403. this._x = (m32 - m23) * s;
  2404. this._y = (m13 - m31) * s;
  2405. this._z = (m21 - m12) * s;
  2406. } else if (m11 > m22 && m11 > m33) {
  2407. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2408. this._w = (m32 - m23) / s;
  2409. this._x = 0.25 * s;
  2410. this._y = (m12 + m21) / s;
  2411. this._z = (m13 + m31) / s;
  2412. } else if (m22 > m33) {
  2413. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2414. this._w = (m13 - m31) / s;
  2415. this._x = (m12 + m21) / s;
  2416. this._y = 0.25 * s;
  2417. this._z = (m23 + m32) / s;
  2418. } else {
  2419. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2420. this._w = (m21 - m12) / s;
  2421. this._x = (m13 + m31) / s;
  2422. this._y = (m23 + m32) / s;
  2423. this._z = 0.25 * s;
  2424. }
  2425. this._onChangeCallback();
  2426. return this;
  2427. },
  2428. setFromUnitVectors: function (vFrom, vTo) {
  2429. // assumes direction vectors vFrom and vTo are normalized
  2430. var EPS = 0.000001;
  2431. var r = vFrom.dot(vTo) + 1;
  2432. if (r < EPS) {
  2433. r = 0;
  2434. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2435. this._x = -vFrom.y;
  2436. this._y = vFrom.x;
  2437. this._z = 0;
  2438. this._w = r;
  2439. } else {
  2440. this._x = 0;
  2441. this._y = -vFrom.z;
  2442. this._z = vFrom.y;
  2443. this._w = r;
  2444. }
  2445. } else {
  2446. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2447. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2448. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2449. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2450. this._w = r;
  2451. }
  2452. return this.normalize();
  2453. },
  2454. angleTo: function (q) {
  2455. return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
  2456. },
  2457. rotateTowards: function (q, step) {
  2458. var angle = this.angleTo(q);
  2459. if (angle === 0) return this;
  2460. var t = Math.min(1, step / angle);
  2461. this.slerp(q, t);
  2462. return this;
  2463. },
  2464. inverse: function () {
  2465. // quaternion is assumed to have unit length
  2466. return this.conjugate();
  2467. },
  2468. conjugate: function () {
  2469. this._x *= -1;
  2470. this._y *= -1;
  2471. this._z *= -1;
  2472. this._onChangeCallback();
  2473. return this;
  2474. },
  2475. dot: function (v) {
  2476. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2477. },
  2478. lengthSq: function () {
  2479. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2480. },
  2481. length: function () {
  2482. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2483. },
  2484. normalize: function () {
  2485. var l = this.length();
  2486. if (l === 0) {
  2487. this._x = 0;
  2488. this._y = 0;
  2489. this._z = 0;
  2490. this._w = 1;
  2491. } else {
  2492. l = 1 / l;
  2493. this._x = this._x * l;
  2494. this._y = this._y * l;
  2495. this._z = this._z * l;
  2496. this._w = this._w * l;
  2497. }
  2498. this._onChangeCallback();
  2499. return this;
  2500. },
  2501. multiply: function (q, p) {
  2502. if (p !== undefined) {
  2503. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2504. return this.multiplyQuaternions(q, p);
  2505. }
  2506. return this.multiplyQuaternions(this, q);
  2507. },
  2508. premultiply: function (q) {
  2509. return this.multiplyQuaternions(q, this);
  2510. },
  2511. multiplyQuaternions: function (a, b) {
  2512. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2513. var qax = a._x,
  2514. qay = a._y,
  2515. qaz = a._z,
  2516. qaw = a._w;
  2517. var qbx = b._x,
  2518. qby = b._y,
  2519. qbz = b._z,
  2520. qbw = b._w;
  2521. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2522. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2523. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2524. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2525. this._onChangeCallback();
  2526. return this;
  2527. },
  2528. slerp: function (qb, t) {
  2529. if (t === 0) return this;
  2530. if (t === 1) return this.copy(qb);
  2531. var x = this._x,
  2532. y = this._y,
  2533. z = this._z,
  2534. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2535. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2536. if (cosHalfTheta < 0) {
  2537. this._w = -qb._w;
  2538. this._x = -qb._x;
  2539. this._y = -qb._y;
  2540. this._z = -qb._z;
  2541. cosHalfTheta = -cosHalfTheta;
  2542. } else {
  2543. this.copy(qb);
  2544. }
  2545. if (cosHalfTheta >= 1.0) {
  2546. this._w = w;
  2547. this._x = x;
  2548. this._y = y;
  2549. this._z = z;
  2550. return this;
  2551. }
  2552. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2553. if (sqrSinHalfTheta <= Number.EPSILON) {
  2554. var s = 1 - t;
  2555. this._w = s * w + t * this._w;
  2556. this._x = s * x + t * this._x;
  2557. this._y = s * y + t * this._y;
  2558. this._z = s * z + t * this._z;
  2559. this.normalize();
  2560. this._onChangeCallback();
  2561. return this;
  2562. }
  2563. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2564. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2565. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2566. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2567. this._w = w * ratioA + this._w * ratioB;
  2568. this._x = x * ratioA + this._x * ratioB;
  2569. this._y = y * ratioA + this._y * ratioB;
  2570. this._z = z * ratioA + this._z * ratioB;
  2571. this._onChangeCallback();
  2572. return this;
  2573. },
  2574. equals: function (quaternion) {
  2575. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2576. },
  2577. fromArray: function (array, offset) {
  2578. if (offset === undefined) offset = 0;
  2579. this._x = array[offset];
  2580. this._y = array[offset + 1];
  2581. this._z = array[offset + 2];
  2582. this._w = array[offset + 3];
  2583. this._onChangeCallback();
  2584. return this;
  2585. },
  2586. toArray: function (array, offset) {
  2587. if (array === undefined) array = [];
  2588. if (offset === undefined) offset = 0;
  2589. array[offset] = this._x;
  2590. array[offset + 1] = this._y;
  2591. array[offset + 2] = this._z;
  2592. array[offset + 3] = this._w;
  2593. return array;
  2594. },
  2595. fromBufferAttribute: function (attribute, index) {
  2596. this._x = attribute.getX(index);
  2597. this._y = attribute.getY(index);
  2598. this._z = attribute.getZ(index);
  2599. this._w = attribute.getW(index);
  2600. return this;
  2601. },
  2602. _onChange: function (callback) {
  2603. this._onChangeCallback = callback;
  2604. return this;
  2605. },
  2606. _onChangeCallback: function () {}
  2607. });
  2608. /**
  2609. * @author mrdoob / http://mrdoob.com/
  2610. * @author kile / http://kile.stravaganza.org/
  2611. * @author philogb / http://blog.thejit.org/
  2612. * @author mikael emtinger / http://gomo.se/
  2613. * @author egraether / http://egraether.com/
  2614. * @author WestLangley / http://github.com/WestLangley
  2615. */
  2616. var _vector = new Vector3();
  2617. var _quaternion = new Quaternion();
  2618. function Vector3(x, y, z) {
  2619. this.x = x || 0;
  2620. this.y = y || 0;
  2621. this.z = z || 0;
  2622. }
  2623. Object.assign(Vector3.prototype, {
  2624. isVector3: true,
  2625. set: function (x, y, z) {
  2626. this.x = x;
  2627. this.y = y;
  2628. this.z = z;
  2629. return this;
  2630. },
  2631. setScalar: function (scalar) {
  2632. this.x = scalar;
  2633. this.y = scalar;
  2634. this.z = scalar;
  2635. return this;
  2636. },
  2637. setX: function (x) {
  2638. this.x = x;
  2639. return this;
  2640. },
  2641. setY: function (y) {
  2642. this.y = y;
  2643. return this;
  2644. },
  2645. setZ: function (z) {
  2646. this.z = z;
  2647. return this;
  2648. },
  2649. setComponent: function (index, value) {
  2650. switch (index) {
  2651. case 0:
  2652. this.x = value;
  2653. break;
  2654. case 1:
  2655. this.y = value;
  2656. break;
  2657. case 2:
  2658. this.z = value;
  2659. break;
  2660. default:
  2661. throw new Error('index is out of range: ' + index);
  2662. }
  2663. return this;
  2664. },
  2665. getComponent: function (index) {
  2666. switch (index) {
  2667. case 0:
  2668. return this.x;
  2669. case 1:
  2670. return this.y;
  2671. case 2:
  2672. return this.z;
  2673. default:
  2674. throw new Error('index is out of range: ' + index);
  2675. }
  2676. },
  2677. clone: function () {
  2678. return new this.constructor(this.x, this.y, this.z);
  2679. },
  2680. copy: function (v) {
  2681. this.x = v.x;
  2682. this.y = v.y;
  2683. this.z = v.z;
  2684. return this;
  2685. },
  2686. add: function (v, w) {
  2687. if (w !== undefined) {
  2688. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2689. return this.addVectors(v, w);
  2690. }
  2691. this.x += v.x;
  2692. this.y += v.y;
  2693. this.z += v.z;
  2694. return this;
  2695. },
  2696. addScalar: function (s) {
  2697. this.x += s;
  2698. this.y += s;
  2699. this.z += s;
  2700. return this;
  2701. },
  2702. addVectors: function (a, b) {
  2703. this.x = a.x + b.x;
  2704. this.y = a.y + b.y;
  2705. this.z = a.z + b.z;
  2706. return this;
  2707. },
  2708. addScaledVector: function (v, s) {
  2709. this.x += v.x * s;
  2710. this.y += v.y * s;
  2711. this.z += v.z * s;
  2712. return this;
  2713. },
  2714. sub: function (v, w) {
  2715. if (w !== undefined) {
  2716. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2717. return this.subVectors(v, w);
  2718. }
  2719. this.x -= v.x;
  2720. this.y -= v.y;
  2721. this.z -= v.z;
  2722. return this;
  2723. },
  2724. subScalar: function (s) {
  2725. this.x -= s;
  2726. this.y -= s;
  2727. this.z -= s;
  2728. return this;
  2729. },
  2730. subVectors: function (a, b) {
  2731. this.x = a.x - b.x;
  2732. this.y = a.y - b.y;
  2733. this.z = a.z - b.z;
  2734. return this;
  2735. },
  2736. multiply: function (v, w) {
  2737. if (w !== undefined) {
  2738. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2739. return this.multiplyVectors(v, w);
  2740. }
  2741. this.x *= v.x;
  2742. this.y *= v.y;
  2743. this.z *= v.z;
  2744. return this;
  2745. },
  2746. multiplyScalar: function (scalar) {
  2747. this.x *= scalar;
  2748. this.y *= scalar;
  2749. this.z *= scalar;
  2750. return this;
  2751. },
  2752. multiplyVectors: function (a, b) {
  2753. this.x = a.x * b.x;
  2754. this.y = a.y * b.y;
  2755. this.z = a.z * b.z;
  2756. return this;
  2757. },
  2758. applyEuler: function (euler) {
  2759. if (!(euler && euler.isEuler)) {
  2760. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2761. }
  2762. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2763. },
  2764. applyAxisAngle: function (axis, angle) {
  2765. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2766. },
  2767. applyMatrix3: function (m) {
  2768. var x = this.x,
  2769. y = this.y,
  2770. z = this.z;
  2771. var e = m.elements;
  2772. this.x = e[0] * x + e[3] * y + e[6] * z;
  2773. this.y = e[1] * x + e[4] * y + e[7] * z;
  2774. this.z = e[2] * x + e[5] * y + e[8] * z;
  2775. return this;
  2776. },
  2777. applyNormalMatrix: function (m) {
  2778. return this.applyMatrix3(m).normalize();
  2779. },
  2780. applyMatrix4: function (m) {
  2781. var x = this.x,
  2782. y = this.y,
  2783. z = this.z;
  2784. var e = m.elements;
  2785. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2786. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2787. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2788. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2789. return this;
  2790. },
  2791. applyQuaternion: function (q) {
  2792. var x = this.x,
  2793. y = this.y,
  2794. z = this.z;
  2795. var qx = q.x,
  2796. qy = q.y,
  2797. qz = q.z,
  2798. qw = q.w; // calculate quat * vector
  2799. var ix = qw * x + qy * z - qz * y;
  2800. var iy = qw * y + qz * x - qx * z;
  2801. var iz = qw * z + qx * y - qy * x;
  2802. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2803. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2804. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2805. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2806. return this;
  2807. },
  2808. project: function (camera) {
  2809. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2810. },
  2811. unproject: function (camera) {
  2812. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2813. },
  2814. transformDirection: function (m) {
  2815. // input: THREE.Matrix4 affine matrix
  2816. // vector interpreted as a direction
  2817. var x = this.x,
  2818. y = this.y,
  2819. z = this.z;
  2820. var e = m.elements;
  2821. this.x = e[0] * x + e[4] * y + e[8] * z;
  2822. this.y = e[1] * x + e[5] * y + e[9] * z;
  2823. this.z = e[2] * x + e[6] * y + e[10] * z;
  2824. return this.normalize();
  2825. },
  2826. divide: function (v) {
  2827. this.x /= v.x;
  2828. this.y /= v.y;
  2829. this.z /= v.z;
  2830. return this;
  2831. },
  2832. divideScalar: function (scalar) {
  2833. return this.multiplyScalar(1 / scalar);
  2834. },
  2835. min: function (v) {
  2836. this.x = Math.min(this.x, v.x);
  2837. this.y = Math.min(this.y, v.y);
  2838. this.z = Math.min(this.z, v.z);
  2839. return this;
  2840. },
  2841. max: function (v) {
  2842. this.x = Math.max(this.x, v.x);
  2843. this.y = Math.max(this.y, v.y);
  2844. this.z = Math.max(this.z, v.z);
  2845. return this;
  2846. },
  2847. clamp: function (min, max) {
  2848. // assumes min < max, componentwise
  2849. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2850. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2851. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2852. return this;
  2853. },
  2854. clampScalar: function (minVal, maxVal) {
  2855. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2856. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2857. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2858. return this;
  2859. },
  2860. clampLength: function (min, max) {
  2861. var length = this.length();
  2862. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2863. },
  2864. floor: function () {
  2865. this.x = Math.floor(this.x);
  2866. this.y = Math.floor(this.y);
  2867. this.z = Math.floor(this.z);
  2868. return this;
  2869. },
  2870. ceil: function () {
  2871. this.x = Math.ceil(this.x);
  2872. this.y = Math.ceil(this.y);
  2873. this.z = Math.ceil(this.z);
  2874. return this;
  2875. },
  2876. round: function () {
  2877. this.x = Math.round(this.x);
  2878. this.y = Math.round(this.y);
  2879. this.z = Math.round(this.z);
  2880. return this;
  2881. },
  2882. roundToZero: function () {
  2883. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2884. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2885. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2886. return this;
  2887. },
  2888. negate: function () {
  2889. this.x = -this.x;
  2890. this.y = -this.y;
  2891. this.z = -this.z;
  2892. return this;
  2893. },
  2894. dot: function (v) {
  2895. return this.x * v.x + this.y * v.y + this.z * v.z;
  2896. },
  2897. // TODO lengthSquared?
  2898. lengthSq: function () {
  2899. return this.x * this.x + this.y * this.y + this.z * this.z;
  2900. },
  2901. length: function () {
  2902. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2903. },
  2904. manhattanLength: function () {
  2905. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2906. },
  2907. normalize: function () {
  2908. return this.divideScalar(this.length() || 1);
  2909. },
  2910. setLength: function (length) {
  2911. return this.normalize().multiplyScalar(length);
  2912. },
  2913. lerp: function (v, alpha) {
  2914. this.x += (v.x - this.x) * alpha;
  2915. this.y += (v.y - this.y) * alpha;
  2916. this.z += (v.z - this.z) * alpha;
  2917. return this;
  2918. },
  2919. lerpVectors: function (v1, v2, alpha) {
  2920. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2921. },
  2922. cross: function (v, w) {
  2923. if (w !== undefined) {
  2924. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2925. return this.crossVectors(v, w);
  2926. }
  2927. return this.crossVectors(this, v);
  2928. },
  2929. crossVectors: function (a, b) {
  2930. var ax = a.x,
  2931. ay = a.y,
  2932. az = a.z;
  2933. var bx = b.x,
  2934. by = b.y,
  2935. bz = b.z;
  2936. this.x = ay * bz - az * by;
  2937. this.y = az * bx - ax * bz;
  2938. this.z = ax * by - ay * bx;
  2939. return this;
  2940. },
  2941. projectOnVector: function (v) {
  2942. var denominator = v.lengthSq();
  2943. if (denominator === 0) return this.set(0, 0, 0);
  2944. var scalar = v.dot(this) / denominator;
  2945. return this.copy(v).multiplyScalar(scalar);
  2946. },
  2947. projectOnPlane: function (planeNormal) {
  2948. _vector.copy(this).projectOnVector(planeNormal);
  2949. return this.sub(_vector);
  2950. },
  2951. reflect: function (normal) {
  2952. // reflect incident vector off plane orthogonal to normal
  2953. // normal is assumed to have unit length
  2954. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2955. },
  2956. angleTo: function (v) {
  2957. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2958. if (denominator === 0) return Math.PI / 2;
  2959. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2960. return Math.acos(MathUtils.clamp(theta, -1, 1));
  2961. },
  2962. distanceTo: function (v) {
  2963. return Math.sqrt(this.distanceToSquared(v));
  2964. },
  2965. distanceToSquared: function (v) {
  2966. var dx = this.x - v.x,
  2967. dy = this.y - v.y,
  2968. dz = this.z - v.z;
  2969. return dx * dx + dy * dy + dz * dz;
  2970. },
  2971. manhattanDistanceTo: function (v) {
  2972. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2973. },
  2974. setFromSpherical: function (s) {
  2975. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2976. },
  2977. setFromSphericalCoords: function (radius, phi, theta) {
  2978. var sinPhiRadius = Math.sin(phi) * radius;
  2979. this.x = sinPhiRadius * Math.sin(theta);
  2980. this.y = Math.cos(phi) * radius;
  2981. this.z = sinPhiRadius * Math.cos(theta);
  2982. return this;
  2983. },
  2984. setFromCylindrical: function (c) {
  2985. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2986. },
  2987. setFromCylindricalCoords: function (radius, theta, y) {
  2988. this.x = radius * Math.sin(theta);
  2989. this.y = y;
  2990. this.z = radius * Math.cos(theta);
  2991. return this;
  2992. },
  2993. setFromMatrixPosition: function (m) {
  2994. var e = m.elements;
  2995. this.x = e[12];
  2996. this.y = e[13];
  2997. this.z = e[14];
  2998. return this;
  2999. },
  3000. setFromMatrixScale: function (m) {
  3001. var sx = this.setFromMatrixColumn(m, 0).length();
  3002. var sy = this.setFromMatrixColumn(m, 1).length();
  3003. var sz = this.setFromMatrixColumn(m, 2).length();
  3004. this.x = sx;
  3005. this.y = sy;
  3006. this.z = sz;
  3007. return this;
  3008. },
  3009. setFromMatrixColumn: function (m, index) {
  3010. return this.fromArray(m.elements, index * 4);
  3011. },
  3012. setFromMatrix3Column: function (m, index) {
  3013. return this.fromArray(m.elements, index * 3);
  3014. },
  3015. equals: function (v) {
  3016. return v.x === this.x && v.y === this.y && v.z === this.z;
  3017. },
  3018. fromArray: function (array, offset) {
  3019. if (offset === undefined) offset = 0;
  3020. this.x = array[offset];
  3021. this.y = array[offset + 1];
  3022. this.z = array[offset + 2];
  3023. return this;
  3024. },
  3025. toArray: function (array, offset) {
  3026. if (array === undefined) array = [];
  3027. if (offset === undefined) offset = 0;
  3028. array[offset] = this.x;
  3029. array[offset + 1] = this.y;
  3030. array[offset + 2] = this.z;
  3031. return array;
  3032. },
  3033. fromBufferAttribute: function (attribute, index, offset) {
  3034. if (offset !== undefined) {
  3035. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  3036. }
  3037. this.x = attribute.getX(index);
  3038. this.y = attribute.getY(index);
  3039. this.z = attribute.getZ(index);
  3040. return this;
  3041. }
  3042. });
  3043. var _v1 = new Vector3();
  3044. var _m1 = new Matrix4();
  3045. var _zero = new Vector3(0, 0, 0);
  3046. var _one = new Vector3(1, 1, 1);
  3047. var _x = new Vector3();
  3048. var _y = new Vector3();
  3049. var _z = new Vector3();
  3050. /**
  3051. * @author mrdoob / http://mrdoob.com/
  3052. * @author supereggbert / http://www.paulbrunt.co.uk/
  3053. * @author philogb / http://blog.thejit.org/
  3054. * @author jordi_ros / http://plattsoft.com
  3055. * @author D1plo1d / http://github.com/D1plo1d
  3056. * @author alteredq / http://alteredqualia.com/
  3057. * @author mikael emtinger / http://gomo.se/
  3058. * @author timknip / http://www.floorplanner.com/
  3059. * @author bhouston / http://clara.io
  3060. * @author WestLangley / http://github.com/WestLangley
  3061. */
  3062. function Matrix4() {
  3063. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3064. if (arguments.length > 0) {
  3065. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3066. }
  3067. }
  3068. Object.assign(Matrix4.prototype, {
  3069. isMatrix4: true,
  3070. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3071. var te = this.elements;
  3072. te[0] = n11;
  3073. te[4] = n12;
  3074. te[8] = n13;
  3075. te[12] = n14;
  3076. te[1] = n21;
  3077. te[5] = n22;
  3078. te[9] = n23;
  3079. te[13] = n24;
  3080. te[2] = n31;
  3081. te[6] = n32;
  3082. te[10] = n33;
  3083. te[14] = n34;
  3084. te[3] = n41;
  3085. te[7] = n42;
  3086. te[11] = n43;
  3087. te[15] = n44;
  3088. return this;
  3089. },
  3090. identity: function () {
  3091. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3092. return this;
  3093. },
  3094. clone: function () {
  3095. return new Matrix4().fromArray(this.elements);
  3096. },
  3097. copy: function (m) {
  3098. var te = this.elements;
  3099. var me = m.elements;
  3100. te[0] = me[0];
  3101. te[1] = me[1];
  3102. te[2] = me[2];
  3103. te[3] = me[3];
  3104. te[4] = me[4];
  3105. te[5] = me[5];
  3106. te[6] = me[6];
  3107. te[7] = me[7];
  3108. te[8] = me[8];
  3109. te[9] = me[9];
  3110. te[10] = me[10];
  3111. te[11] = me[11];
  3112. te[12] = me[12];
  3113. te[13] = me[13];
  3114. te[14] = me[14];
  3115. te[15] = me[15];
  3116. return this;
  3117. },
  3118. copyPosition: function (m) {
  3119. var te = this.elements,
  3120. me = m.elements;
  3121. te[12] = me[12];
  3122. te[13] = me[13];
  3123. te[14] = me[14];
  3124. return this;
  3125. },
  3126. extractBasis: function (xAxis, yAxis, zAxis) {
  3127. xAxis.setFromMatrixColumn(this, 0);
  3128. yAxis.setFromMatrixColumn(this, 1);
  3129. zAxis.setFromMatrixColumn(this, 2);
  3130. return this;
  3131. },
  3132. makeBasis: function (xAxis, yAxis, zAxis) {
  3133. 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);
  3134. return this;
  3135. },
  3136. extractRotation: function (m) {
  3137. // this method does not support reflection matrices
  3138. var te = this.elements;
  3139. var me = m.elements;
  3140. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  3141. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  3142. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  3143. te[0] = me[0] * scaleX;
  3144. te[1] = me[1] * scaleX;
  3145. te[2] = me[2] * scaleX;
  3146. te[3] = 0;
  3147. te[4] = me[4] * scaleY;
  3148. te[5] = me[5] * scaleY;
  3149. te[6] = me[6] * scaleY;
  3150. te[7] = 0;
  3151. te[8] = me[8] * scaleZ;
  3152. te[9] = me[9] * scaleZ;
  3153. te[10] = me[10] * scaleZ;
  3154. te[11] = 0;
  3155. te[12] = 0;
  3156. te[13] = 0;
  3157. te[14] = 0;
  3158. te[15] = 1;
  3159. return this;
  3160. },
  3161. makeRotationFromEuler: function (euler) {
  3162. if (!(euler && euler.isEuler)) {
  3163. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3164. }
  3165. var te = this.elements;
  3166. var x = euler.x,
  3167. y = euler.y,
  3168. z = euler.z;
  3169. var a = Math.cos(x),
  3170. b = Math.sin(x);
  3171. var c = Math.cos(y),
  3172. d = Math.sin(y);
  3173. var e = Math.cos(z),
  3174. f = Math.sin(z);
  3175. if (euler.order === 'XYZ') {
  3176. var ae = a * e,
  3177. af = a * f,
  3178. be = b * e,
  3179. bf = b * f;
  3180. te[0] = c * e;
  3181. te[4] = -c * f;
  3182. te[8] = d;
  3183. te[1] = af + be * d;
  3184. te[5] = ae - bf * d;
  3185. te[9] = -b * c;
  3186. te[2] = bf - ae * d;
  3187. te[6] = be + af * d;
  3188. te[10] = a * c;
  3189. } else if (euler.order === 'YXZ') {
  3190. var ce = c * e,
  3191. cf = c * f,
  3192. de = d * e,
  3193. df = d * f;
  3194. te[0] = ce + df * b;
  3195. te[4] = de * b - cf;
  3196. te[8] = a * d;
  3197. te[1] = a * f;
  3198. te[5] = a * e;
  3199. te[9] = -b;
  3200. te[2] = cf * b - de;
  3201. te[6] = df + ce * b;
  3202. te[10] = a * c;
  3203. } else if (euler.order === 'ZXY') {
  3204. var ce = c * e,
  3205. cf = c * f,
  3206. de = d * e,
  3207. df = d * f;
  3208. te[0] = ce - df * b;
  3209. te[4] = -a * f;
  3210. te[8] = de + cf * b;
  3211. te[1] = cf + de * b;
  3212. te[5] = a * e;
  3213. te[9] = df - ce * b;
  3214. te[2] = -a * d;
  3215. te[6] = b;
  3216. te[10] = a * c;
  3217. } else if (euler.order === 'ZYX') {
  3218. var ae = a * e,
  3219. af = a * f,
  3220. be = b * e,
  3221. bf = b * f;
  3222. te[0] = c * e;
  3223. te[4] = be * d - af;
  3224. te[8] = ae * d + bf;
  3225. te[1] = c * f;
  3226. te[5] = bf * d + ae;
  3227. te[9] = af * d - be;
  3228. te[2] = -d;
  3229. te[6] = b * c;
  3230. te[10] = a * c;
  3231. } else if (euler.order === 'YZX') {
  3232. var ac = a * c,
  3233. ad = a * d,
  3234. bc = b * c,
  3235. bd = b * d;
  3236. te[0] = c * e;
  3237. te[4] = bd - ac * f;
  3238. te[8] = bc * f + ad;
  3239. te[1] = f;
  3240. te[5] = a * e;
  3241. te[9] = -b * e;
  3242. te[2] = -d * e;
  3243. te[6] = ad * f + bc;
  3244. te[10] = ac - bd * f;
  3245. } else if (euler.order === 'XZY') {
  3246. var ac = a * c,
  3247. ad = a * d,
  3248. bc = b * c,
  3249. bd = b * d;
  3250. te[0] = c * e;
  3251. te[4] = -f;
  3252. te[8] = d * e;
  3253. te[1] = ac * f + bd;
  3254. te[5] = a * e;
  3255. te[9] = ad * f - bc;
  3256. te[2] = bc * f - ad;
  3257. te[6] = b * e;
  3258. te[10] = bd * f + ac;
  3259. } // bottom row
  3260. te[3] = 0;
  3261. te[7] = 0;
  3262. te[11] = 0; // last column
  3263. te[12] = 0;
  3264. te[13] = 0;
  3265. te[14] = 0;
  3266. te[15] = 1;
  3267. return this;
  3268. },
  3269. makeRotationFromQuaternion: function (q) {
  3270. return this.compose(_zero, q, _one);
  3271. },
  3272. lookAt: function (eye, target, up) {
  3273. var te = this.elements;
  3274. _z.subVectors(eye, target);
  3275. if (_z.lengthSq() === 0) {
  3276. // eye and target are in the same position
  3277. _z.z = 1;
  3278. }
  3279. _z.normalize();
  3280. _x.crossVectors(up, _z);
  3281. if (_x.lengthSq() === 0) {
  3282. // up and z are parallel
  3283. if (Math.abs(up.z) === 1) {
  3284. _z.x += 0.0001;
  3285. } else {
  3286. _z.z += 0.0001;
  3287. }
  3288. _z.normalize();
  3289. _x.crossVectors(up, _z);
  3290. }
  3291. _x.normalize();
  3292. _y.crossVectors(_z, _x);
  3293. te[0] = _x.x;
  3294. te[4] = _y.x;
  3295. te[8] = _z.x;
  3296. te[1] = _x.y;
  3297. te[5] = _y.y;
  3298. te[9] = _z.y;
  3299. te[2] = _x.z;
  3300. te[6] = _y.z;
  3301. te[10] = _z.z;
  3302. return this;
  3303. },
  3304. multiply: function (m, n) {
  3305. if (n !== undefined) {
  3306. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3307. return this.multiplyMatrices(m, n);
  3308. }
  3309. return this.multiplyMatrices(this, m);
  3310. },
  3311. premultiply: function (m) {
  3312. return this.multiplyMatrices(m, this);
  3313. },
  3314. multiplyMatrices: function (a, b) {
  3315. var ae = a.elements;
  3316. var be = b.elements;
  3317. var te = this.elements;
  3318. var a11 = ae[0],
  3319. a12 = ae[4],
  3320. a13 = ae[8],
  3321. a14 = ae[12];
  3322. var a21 = ae[1],
  3323. a22 = ae[5],
  3324. a23 = ae[9],
  3325. a24 = ae[13];
  3326. var a31 = ae[2],
  3327. a32 = ae[6],
  3328. a33 = ae[10],
  3329. a34 = ae[14];
  3330. var a41 = ae[3],
  3331. a42 = ae[7],
  3332. a43 = ae[11],
  3333. a44 = ae[15];
  3334. var b11 = be[0],
  3335. b12 = be[4],
  3336. b13 = be[8],
  3337. b14 = be[12];
  3338. var b21 = be[1],
  3339. b22 = be[5],
  3340. b23 = be[9],
  3341. b24 = be[13];
  3342. var b31 = be[2],
  3343. b32 = be[6],
  3344. b33 = be[10],
  3345. b34 = be[14];
  3346. var b41 = be[3],
  3347. b42 = be[7],
  3348. b43 = be[11],
  3349. b44 = be[15];
  3350. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3351. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3352. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3353. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3354. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3355. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3356. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3357. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3358. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3359. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3360. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3361. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3362. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3363. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3364. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3365. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3366. return this;
  3367. },
  3368. multiplyScalar: function (s) {
  3369. var te = this.elements;
  3370. te[0] *= s;
  3371. te[4] *= s;
  3372. te[8] *= s;
  3373. te[12] *= s;
  3374. te[1] *= s;
  3375. te[5] *= s;
  3376. te[9] *= s;
  3377. te[13] *= s;
  3378. te[2] *= s;
  3379. te[6] *= s;
  3380. te[10] *= s;
  3381. te[14] *= s;
  3382. te[3] *= s;
  3383. te[7] *= s;
  3384. te[11] *= s;
  3385. te[15] *= s;
  3386. return this;
  3387. },
  3388. determinant: function () {
  3389. var te = this.elements;
  3390. var n11 = te[0],
  3391. n12 = te[4],
  3392. n13 = te[8],
  3393. n14 = te[12];
  3394. var n21 = te[1],
  3395. n22 = te[5],
  3396. n23 = te[9],
  3397. n24 = te[13];
  3398. var n31 = te[2],
  3399. n32 = te[6],
  3400. n33 = te[10],
  3401. n34 = te[14];
  3402. var n41 = te[3],
  3403. n42 = te[7],
  3404. n43 = te[11],
  3405. n44 = te[15]; //TODO: make this more efficient
  3406. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3407. 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);
  3408. },
  3409. transpose: function () {
  3410. var te = this.elements;
  3411. var tmp;
  3412. tmp = te[1];
  3413. te[1] = te[4];
  3414. te[4] = tmp;
  3415. tmp = te[2];
  3416. te[2] = te[8];
  3417. te[8] = tmp;
  3418. tmp = te[6];
  3419. te[6] = te[9];
  3420. te[9] = tmp;
  3421. tmp = te[3];
  3422. te[3] = te[12];
  3423. te[12] = tmp;
  3424. tmp = te[7];
  3425. te[7] = te[13];
  3426. te[13] = tmp;
  3427. tmp = te[11];
  3428. te[11] = te[14];
  3429. te[14] = tmp;
  3430. return this;
  3431. },
  3432. setPosition: function (x, y, z) {
  3433. var te = this.elements;
  3434. if (x.isVector3) {
  3435. te[12] = x.x;
  3436. te[13] = x.y;
  3437. te[14] = x.z;
  3438. } else {
  3439. te[12] = x;
  3440. te[13] = y;
  3441. te[14] = z;
  3442. }
  3443. return this;
  3444. },
  3445. getInverse: function (m, throwOnDegenerate) {
  3446. if (throwOnDegenerate !== undefined) {
  3447. console.warn("THREE.Matrix4: .getInverse() can no longer be configured to throw on degenerate.");
  3448. } // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3449. var te = this.elements,
  3450. me = m.elements,
  3451. n11 = me[0],
  3452. n21 = me[1],
  3453. n31 = me[2],
  3454. n41 = me[3],
  3455. n12 = me[4],
  3456. n22 = me[5],
  3457. n32 = me[6],
  3458. n42 = me[7],
  3459. n13 = me[8],
  3460. n23 = me[9],
  3461. n33 = me[10],
  3462. n43 = me[11],
  3463. n14 = me[12],
  3464. n24 = me[13],
  3465. n34 = me[14],
  3466. n44 = me[15],
  3467. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3468. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3469. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3470. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3471. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3472. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3473. var detInv = 1 / det;
  3474. te[0] = t11 * detInv;
  3475. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3476. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3477. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3478. te[4] = t12 * detInv;
  3479. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3480. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3481. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3482. te[8] = t13 * detInv;
  3483. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3484. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3485. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3486. te[12] = t14 * detInv;
  3487. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3488. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3489. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3490. return this;
  3491. },
  3492. scale: function (v) {
  3493. var te = this.elements;
  3494. var x = v.x,
  3495. y = v.y,
  3496. z = v.z;
  3497. te[0] *= x;
  3498. te[4] *= y;
  3499. te[8] *= z;
  3500. te[1] *= x;
  3501. te[5] *= y;
  3502. te[9] *= z;
  3503. te[2] *= x;
  3504. te[6] *= y;
  3505. te[10] *= z;
  3506. te[3] *= x;
  3507. te[7] *= y;
  3508. te[11] *= z;
  3509. return this;
  3510. },
  3511. getMaxScaleOnAxis: function () {
  3512. var te = this.elements;
  3513. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3514. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3515. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3516. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3517. },
  3518. makeTranslation: function (x, y, z) {
  3519. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3520. return this;
  3521. },
  3522. makeRotationX: function (theta) {
  3523. var c = Math.cos(theta),
  3524. s = Math.sin(theta);
  3525. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3526. return this;
  3527. },
  3528. makeRotationY: function (theta) {
  3529. var c = Math.cos(theta),
  3530. s = Math.sin(theta);
  3531. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3532. return this;
  3533. },
  3534. makeRotationZ: function (theta) {
  3535. var c = Math.cos(theta),
  3536. s = Math.sin(theta);
  3537. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3538. return this;
  3539. },
  3540. makeRotationAxis: function (axis, angle) {
  3541. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3542. var c = Math.cos(angle);
  3543. var s = Math.sin(angle);
  3544. var t = 1 - c;
  3545. var x = axis.x,
  3546. y = axis.y,
  3547. z = axis.z;
  3548. var tx = t * x,
  3549. ty = t * y;
  3550. 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);
  3551. return this;
  3552. },
  3553. makeScale: function (x, y, z) {
  3554. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3555. return this;
  3556. },
  3557. makeShear: function (x, y, z) {
  3558. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  3559. return this;
  3560. },
  3561. compose: function (position, quaternion, scale) {
  3562. var te = this.elements;
  3563. var x = quaternion._x,
  3564. y = quaternion._y,
  3565. z = quaternion._z,
  3566. w = quaternion._w;
  3567. var x2 = x + x,
  3568. y2 = y + y,
  3569. z2 = z + z;
  3570. var xx = x * x2,
  3571. xy = x * y2,
  3572. xz = x * z2;
  3573. var yy = y * y2,
  3574. yz = y * z2,
  3575. zz = z * z2;
  3576. var wx = w * x2,
  3577. wy = w * y2,
  3578. wz = w * z2;
  3579. var sx = scale.x,
  3580. sy = scale.y,
  3581. sz = scale.z;
  3582. te[0] = (1 - (yy + zz)) * sx;
  3583. te[1] = (xy + wz) * sx;
  3584. te[2] = (xz - wy) * sx;
  3585. te[3] = 0;
  3586. te[4] = (xy - wz) * sy;
  3587. te[5] = (1 - (xx + zz)) * sy;
  3588. te[6] = (yz + wx) * sy;
  3589. te[7] = 0;
  3590. te[8] = (xz + wy) * sz;
  3591. te[9] = (yz - wx) * sz;
  3592. te[10] = (1 - (xx + yy)) * sz;
  3593. te[11] = 0;
  3594. te[12] = position.x;
  3595. te[13] = position.y;
  3596. te[14] = position.z;
  3597. te[15] = 1;
  3598. return this;
  3599. },
  3600. decompose: function (position, quaternion, scale) {
  3601. var te = this.elements;
  3602. var sx = _v1.set(te[0], te[1], te[2]).length();
  3603. var sy = _v1.set(te[4], te[5], te[6]).length();
  3604. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3605. var det = this.determinant();
  3606. if (det < 0) sx = -sx;
  3607. position.x = te[12];
  3608. position.y = te[13];
  3609. position.z = te[14]; // scale the rotation part
  3610. _m1.copy(this);
  3611. var invSX = 1 / sx;
  3612. var invSY = 1 / sy;
  3613. var invSZ = 1 / sz;
  3614. _m1.elements[0] *= invSX;
  3615. _m1.elements[1] *= invSX;
  3616. _m1.elements[2] *= invSX;
  3617. _m1.elements[4] *= invSY;
  3618. _m1.elements[5] *= invSY;
  3619. _m1.elements[6] *= invSY;
  3620. _m1.elements[8] *= invSZ;
  3621. _m1.elements[9] *= invSZ;
  3622. _m1.elements[10] *= invSZ;
  3623. quaternion.setFromRotationMatrix(_m1);
  3624. scale.x = sx;
  3625. scale.y = sy;
  3626. scale.z = sz;
  3627. return this;
  3628. },
  3629. makePerspective: function (left, right, top, bottom, near, far) {
  3630. if (far === undefined) {
  3631. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3632. }
  3633. var te = this.elements;
  3634. var x = 2 * near / (right - left);
  3635. var y = 2 * near / (top - bottom);
  3636. var a = (right + left) / (right - left);
  3637. var b = (top + bottom) / (top - bottom);
  3638. var c = -(far + near) / (far - near);
  3639. var d = -2 * far * near / (far - near);
  3640. te[0] = x;
  3641. te[4] = 0;
  3642. te[8] = a;
  3643. te[12] = 0;
  3644. te[1] = 0;
  3645. te[5] = y;
  3646. te[9] = b;
  3647. te[13] = 0;
  3648. te[2] = 0;
  3649. te[6] = 0;
  3650. te[10] = c;
  3651. te[14] = d;
  3652. te[3] = 0;
  3653. te[7] = 0;
  3654. te[11] = -1;
  3655. te[15] = 0;
  3656. return this;
  3657. },
  3658. makeOrthographic: function (left, right, top, bottom, near, far) {
  3659. var te = this.elements;
  3660. var w = 1.0 / (right - left);
  3661. var h = 1.0 / (top - bottom);
  3662. var p = 1.0 / (far - near);
  3663. var x = (right + left) * w;
  3664. var y = (top + bottom) * h;
  3665. var z = (far + near) * p;
  3666. te[0] = 2 * w;
  3667. te[4] = 0;
  3668. te[8] = 0;
  3669. te[12] = -x;
  3670. te[1] = 0;
  3671. te[5] = 2 * h;
  3672. te[9] = 0;
  3673. te[13] = -y;
  3674. te[2] = 0;
  3675. te[6] = 0;
  3676. te[10] = -2 * p;
  3677. te[14] = -z;
  3678. te[3] = 0;
  3679. te[7] = 0;
  3680. te[11] = 0;
  3681. te[15] = 1;
  3682. return this;
  3683. },
  3684. equals: function (matrix) {
  3685. var te = this.elements;
  3686. var me = matrix.elements;
  3687. for (var i = 0; i < 16; i++) {
  3688. if (te[i] !== me[i]) return false;
  3689. }
  3690. return true;
  3691. },
  3692. fromArray: function (array, offset) {
  3693. if (offset === undefined) offset = 0;
  3694. for (var i = 0; i < 16; i++) {
  3695. this.elements[i] = array[i + offset];
  3696. }
  3697. return this;
  3698. },
  3699. toArray: function (array, offset) {
  3700. if (array === undefined) array = [];
  3701. if (offset === undefined) offset = 0;
  3702. var te = this.elements;
  3703. array[offset] = te[0];
  3704. array[offset + 1] = te[1];
  3705. array[offset + 2] = te[2];
  3706. array[offset + 3] = te[3];
  3707. array[offset + 4] = te[4];
  3708. array[offset + 5] = te[5];
  3709. array[offset + 6] = te[6];
  3710. array[offset + 7] = te[7];
  3711. array[offset + 8] = te[8];
  3712. array[offset + 9] = te[9];
  3713. array[offset + 10] = te[10];
  3714. array[offset + 11] = te[11];
  3715. array[offset + 12] = te[12];
  3716. array[offset + 13] = te[13];
  3717. array[offset + 14] = te[14];
  3718. array[offset + 15] = te[15];
  3719. return array;
  3720. }
  3721. });
  3722. /**
  3723. * @author mrdoob / http://mrdoob.com/
  3724. * @author WestLangley / http://github.com/WestLangley
  3725. * @author bhouston / http://clara.io
  3726. */
  3727. var _matrix = new Matrix4();
  3728. var _quaternion$1 = new Quaternion();
  3729. function Euler(x, y, z, order) {
  3730. this._x = x || 0;
  3731. this._y = y || 0;
  3732. this._z = z || 0;
  3733. this._order = order || Euler.DefaultOrder;
  3734. }
  3735. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  3736. Euler.DefaultOrder = 'XYZ';
  3737. Object.defineProperties(Euler.prototype, {
  3738. x: {
  3739. get: function () {
  3740. return this._x;
  3741. },
  3742. set: function (value) {
  3743. this._x = value;
  3744. this._onChangeCallback();
  3745. }
  3746. },
  3747. y: {
  3748. get: function () {
  3749. return this._y;
  3750. },
  3751. set: function (value) {
  3752. this._y = value;
  3753. this._onChangeCallback();
  3754. }
  3755. },
  3756. z: {
  3757. get: function () {
  3758. return this._z;
  3759. },
  3760. set: function (value) {
  3761. this._z = value;
  3762. this._onChangeCallback();
  3763. }
  3764. },
  3765. order: {
  3766. get: function () {
  3767. return this._order;
  3768. },
  3769. set: function (value) {
  3770. this._order = value;
  3771. this._onChangeCallback();
  3772. }
  3773. }
  3774. });
  3775. Object.assign(Euler.prototype, {
  3776. isEuler: true,
  3777. set: function (x, y, z, order) {
  3778. this._x = x;
  3779. this._y = y;
  3780. this._z = z;
  3781. this._order = order || this._order;
  3782. this._onChangeCallback();
  3783. return this;
  3784. },
  3785. clone: function () {
  3786. return new this.constructor(this._x, this._y, this._z, this._order);
  3787. },
  3788. copy: function (euler) {
  3789. this._x = euler._x;
  3790. this._y = euler._y;
  3791. this._z = euler._z;
  3792. this._order = euler._order;
  3793. this._onChangeCallback();
  3794. return this;
  3795. },
  3796. setFromRotationMatrix: function (m, order, update) {
  3797. var clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3798. var te = m.elements;
  3799. var m11 = te[0],
  3800. m12 = te[4],
  3801. m13 = te[8];
  3802. var m21 = te[1],
  3803. m22 = te[5],
  3804. m23 = te[9];
  3805. var m31 = te[2],
  3806. m32 = te[6],
  3807. m33 = te[10];
  3808. order = order || this._order;
  3809. if (order === 'XYZ') {
  3810. this._y = Math.asin(clamp(m13, -1, 1));
  3811. if (Math.abs(m13) < 0.9999999) {
  3812. this._x = Math.atan2(-m23, m33);
  3813. this._z = Math.atan2(-m12, m11);
  3814. } else {
  3815. this._x = Math.atan2(m32, m22);
  3816. this._z = 0;
  3817. }
  3818. } else if (order === 'YXZ') {
  3819. this._x = Math.asin(-clamp(m23, -1, 1));
  3820. if (Math.abs(m23) < 0.9999999) {
  3821. this._y = Math.atan2(m13, m33);
  3822. this._z = Math.atan2(m21, m22);
  3823. } else {
  3824. this._y = Math.atan2(-m31, m11);
  3825. this._z = 0;
  3826. }
  3827. } else if (order === 'ZXY') {
  3828. this._x = Math.asin(clamp(m32, -1, 1));
  3829. if (Math.abs(m32) < 0.9999999) {
  3830. this._y = Math.atan2(-m31, m33);
  3831. this._z = Math.atan2(-m12, m22);
  3832. } else {
  3833. this._y = 0;
  3834. this._z = Math.atan2(m21, m11);
  3835. }
  3836. } else if (order === 'ZYX') {
  3837. this._y = Math.asin(-clamp(m31, -1, 1));
  3838. if (Math.abs(m31) < 0.9999999) {
  3839. this._x = Math.atan2(m32, m33);
  3840. this._z = Math.atan2(m21, m11);
  3841. } else {
  3842. this._x = 0;
  3843. this._z = Math.atan2(-m12, m22);
  3844. }
  3845. } else if (order === 'YZX') {
  3846. this._z = Math.asin(clamp(m21, -1, 1));
  3847. if (Math.abs(m21) < 0.9999999) {
  3848. this._x = Math.atan2(-m23, m22);
  3849. this._y = Math.atan2(-m31, m11);
  3850. } else {
  3851. this._x = 0;
  3852. this._y = Math.atan2(m13, m33);
  3853. }
  3854. } else if (order === 'XZY') {
  3855. this._z = Math.asin(-clamp(m12, -1, 1));
  3856. if (Math.abs(m12) < 0.9999999) {
  3857. this._x = Math.atan2(m32, m22);
  3858. this._y = Math.atan2(m13, m11);
  3859. } else {
  3860. this._x = Math.atan2(-m23, m33);
  3861. this._y = 0;
  3862. }
  3863. } else {
  3864. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  3865. }
  3866. this._order = order;
  3867. if (update !== false) this._onChangeCallback();
  3868. return this;
  3869. },
  3870. setFromQuaternion: function (q, order, update) {
  3871. _matrix.makeRotationFromQuaternion(q);
  3872. return this.setFromRotationMatrix(_matrix, order, update);
  3873. },
  3874. setFromVector3: function (v, order) {
  3875. return this.set(v.x, v.y, v.z, order || this._order);
  3876. },
  3877. reorder: function (newOrder) {
  3878. // WARNING: this discards revolution information -bhouston
  3879. _quaternion$1.setFromEuler(this);
  3880. return this.setFromQuaternion(_quaternion$1, newOrder);
  3881. },
  3882. equals: function (euler) {
  3883. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  3884. },
  3885. fromArray: function (array) {
  3886. this._x = array[0];
  3887. this._y = array[1];
  3888. this._z = array[2];
  3889. if (array[3] !== undefined) this._order = array[3];
  3890. this._onChangeCallback();
  3891. return this;
  3892. },
  3893. toArray: function (array, offset) {
  3894. if (array === undefined) array = [];
  3895. if (offset === undefined) offset = 0;
  3896. array[offset] = this._x;
  3897. array[offset + 1] = this._y;
  3898. array[offset + 2] = this._z;
  3899. array[offset + 3] = this._order;
  3900. return array;
  3901. },
  3902. toVector3: function (optionalResult) {
  3903. if (optionalResult) {
  3904. return optionalResult.set(this._x, this._y, this._z);
  3905. } else {
  3906. return new Vector3(this._x, this._y, this._z);
  3907. }
  3908. },
  3909. _onChange: function (callback) {
  3910. this._onChangeCallback = callback;
  3911. return this;
  3912. },
  3913. _onChangeCallback: function () {}
  3914. });
  3915. /**
  3916. * @author mrdoob / http://mrdoob.com/
  3917. */
  3918. function Layers() {
  3919. this.mask = 1 | 0;
  3920. }
  3921. Object.assign(Layers.prototype, {
  3922. set: function (channel) {
  3923. this.mask = 1 << channel | 0;
  3924. },
  3925. enable: function (channel) {
  3926. this.mask |= 1 << channel | 0;
  3927. },
  3928. enableAll: function () {
  3929. this.mask = 0xffffffff | 0;
  3930. },
  3931. toggle: function (channel) {
  3932. this.mask ^= 1 << channel | 0;
  3933. },
  3934. disable: function (channel) {
  3935. this.mask &= ~(1 << channel | 0);
  3936. },
  3937. disableAll: function () {
  3938. this.mask = 0;
  3939. },
  3940. test: function (layers) {
  3941. return (this.mask & layers.mask) !== 0;
  3942. }
  3943. });
  3944. var _object3DId = 0;
  3945. var _v1$1 = new Vector3();
  3946. var _q1 = new Quaternion();
  3947. var _m1$1 = new Matrix4();
  3948. var _target = new Vector3();
  3949. var _position = new Vector3();
  3950. var _scale = new Vector3();
  3951. var _quaternion$2 = new Quaternion();
  3952. var _xAxis = new Vector3(1, 0, 0);
  3953. var _yAxis = new Vector3(0, 1, 0);
  3954. var _zAxis = new Vector3(0, 0, 1);
  3955. var _addedEvent = {
  3956. type: 'added'
  3957. };
  3958. var _removedEvent = {
  3959. type: 'removed'
  3960. };
  3961. /**
  3962. * @author mrdoob / http://mrdoob.com/
  3963. * @author mikael emtinger / http://gomo.se/
  3964. * @author alteredq / http://alteredqualia.com/
  3965. * @author WestLangley / http://github.com/WestLangley
  3966. * @author elephantatwork / www.elephantatwork.ch
  3967. */
  3968. function Object3D() {
  3969. Object.defineProperty(this, 'id', {
  3970. value: _object3DId++
  3971. });
  3972. this.uuid = MathUtils.generateUUID();
  3973. this.name = '';
  3974. this.type = 'Object3D';
  3975. this.parent = null;
  3976. this.children = [];
  3977. this.up = Object3D.DefaultUp.clone();
  3978. var position = new Vector3();
  3979. var rotation = new Euler();
  3980. var quaternion = new Quaternion();
  3981. var scale = new Vector3(1, 1, 1);
  3982. function onRotationChange() {
  3983. quaternion.setFromEuler(rotation, false);
  3984. }
  3985. function onQuaternionChange() {
  3986. rotation.setFromQuaternion(quaternion, undefined, false);
  3987. }
  3988. rotation._onChange(onRotationChange);
  3989. quaternion._onChange(onQuaternionChange);
  3990. Object.defineProperties(this, {
  3991. position: {
  3992. configurable: true,
  3993. enumerable: true,
  3994. value: position
  3995. },
  3996. rotation: {
  3997. configurable: true,
  3998. enumerable: true,
  3999. value: rotation
  4000. },
  4001. quaternion: {
  4002. configurable: true,
  4003. enumerable: true,
  4004. value: quaternion
  4005. },
  4006. scale: {
  4007. configurable: true,
  4008. enumerable: true,
  4009. value: scale
  4010. },
  4011. modelViewMatrix: {
  4012. value: new Matrix4()
  4013. },
  4014. normalMatrix: {
  4015. value: new Matrix3()
  4016. }
  4017. });
  4018. this.matrix = new Matrix4();
  4019. this.matrixWorld = new Matrix4();
  4020. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4021. this.matrixWorldNeedsUpdate = false;
  4022. this.layers = new Layers();
  4023. this.visible = true;
  4024. this.castShadow = false;
  4025. this.receiveShadow = false;
  4026. this.frustumCulled = true;
  4027. this.renderOrder = 0;
  4028. this.userData = {};
  4029. }
  4030. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4031. Object3D.DefaultMatrixAutoUpdate = true;
  4032. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4033. constructor: Object3D,
  4034. isObject3D: true,
  4035. onBeforeRender: function () {},
  4036. onAfterRender: function () {},
  4037. applyMatrix4: function (matrix) {
  4038. if (this.matrixAutoUpdate) this.updateMatrix();
  4039. this.matrix.premultiply(matrix);
  4040. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4041. },
  4042. applyQuaternion: function (q) {
  4043. this.quaternion.premultiply(q);
  4044. return this;
  4045. },
  4046. setRotationFromAxisAngle: function (axis, angle) {
  4047. // assumes axis is normalized
  4048. this.quaternion.setFromAxisAngle(axis, angle);
  4049. },
  4050. setRotationFromEuler: function (euler) {
  4051. this.quaternion.setFromEuler(euler, true);
  4052. },
  4053. setRotationFromMatrix: function (m) {
  4054. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4055. this.quaternion.setFromRotationMatrix(m);
  4056. },
  4057. setRotationFromQuaternion: function (q) {
  4058. // assumes q is normalized
  4059. this.quaternion.copy(q);
  4060. },
  4061. rotateOnAxis: function (axis, angle) {
  4062. // rotate object on axis in object space
  4063. // axis is assumed to be normalized
  4064. _q1.setFromAxisAngle(axis, angle);
  4065. this.quaternion.multiply(_q1);
  4066. return this;
  4067. },
  4068. rotateOnWorldAxis: function (axis, angle) {
  4069. // rotate object on axis in world space
  4070. // axis is assumed to be normalized
  4071. // method assumes no rotated parent
  4072. _q1.setFromAxisAngle(axis, angle);
  4073. this.quaternion.premultiply(_q1);
  4074. return this;
  4075. },
  4076. rotateX: function (angle) {
  4077. return this.rotateOnAxis(_xAxis, angle);
  4078. },
  4079. rotateY: function (angle) {
  4080. return this.rotateOnAxis(_yAxis, angle);
  4081. },
  4082. rotateZ: function (angle) {
  4083. return this.rotateOnAxis(_zAxis, angle);
  4084. },
  4085. translateOnAxis: function (axis, distance) {
  4086. // translate object by distance along axis in object space
  4087. // axis is assumed to be normalized
  4088. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  4089. this.position.add(_v1$1.multiplyScalar(distance));
  4090. return this;
  4091. },
  4092. translateX: function (distance) {
  4093. return this.translateOnAxis(_xAxis, distance);
  4094. },
  4095. translateY: function (distance) {
  4096. return this.translateOnAxis(_yAxis, distance);
  4097. },
  4098. translateZ: function (distance) {
  4099. return this.translateOnAxis(_zAxis, distance);
  4100. },
  4101. localToWorld: function (vector) {
  4102. return vector.applyMatrix4(this.matrixWorld);
  4103. },
  4104. worldToLocal: function (vector) {
  4105. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  4106. },
  4107. lookAt: function (x, y, z) {
  4108. // This method does not support objects having non-uniformly-scaled parent(s)
  4109. if (x.isVector3) {
  4110. _target.copy(x);
  4111. } else {
  4112. _target.set(x, y, z);
  4113. }
  4114. var parent = this.parent;
  4115. this.updateWorldMatrix(true, false);
  4116. _position.setFromMatrixPosition(this.matrixWorld);
  4117. if (this.isCamera || this.isLight) {
  4118. _m1$1.lookAt(_position, _target, this.up);
  4119. } else {
  4120. _m1$1.lookAt(_target, _position, this.up);
  4121. }
  4122. this.quaternion.setFromRotationMatrix(_m1$1);
  4123. if (parent) {
  4124. _m1$1.extractRotation(parent.matrixWorld);
  4125. _q1.setFromRotationMatrix(_m1$1);
  4126. this.quaternion.premultiply(_q1.inverse());
  4127. }
  4128. },
  4129. add: function (object) {
  4130. if (arguments.length > 1) {
  4131. for (var i = 0; i < arguments.length; i++) {
  4132. this.add(arguments[i]);
  4133. }
  4134. return this;
  4135. }
  4136. if (object === this) {
  4137. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  4138. return this;
  4139. }
  4140. if (object && object.isObject3D) {
  4141. if (object.parent !== null) {
  4142. object.parent.remove(object);
  4143. }
  4144. object.parent = this;
  4145. this.children.push(object);
  4146. object.dispatchEvent(_addedEvent);
  4147. } else {
  4148. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  4149. }
  4150. return this;
  4151. },
  4152. remove: function (object) {
  4153. if (arguments.length > 1) {
  4154. for (var i = 0; i < arguments.length; i++) {
  4155. this.remove(arguments[i]);
  4156. }
  4157. return this;
  4158. }
  4159. var index = this.children.indexOf(object);
  4160. if (index !== -1) {
  4161. object.parent = null;
  4162. this.children.splice(index, 1);
  4163. object.dispatchEvent(_removedEvent);
  4164. }
  4165. return this;
  4166. },
  4167. attach: function (object) {
  4168. // adds object as a child of this, while maintaining the object's world transform
  4169. this.updateWorldMatrix(true, false);
  4170. _m1$1.getInverse(this.matrixWorld);
  4171. if (object.parent !== null) {
  4172. object.parent.updateWorldMatrix(true, false);
  4173. _m1$1.multiply(object.parent.matrixWorld);
  4174. }
  4175. object.applyMatrix4(_m1$1);
  4176. object.updateWorldMatrix(false, false);
  4177. this.add(object);
  4178. return this;
  4179. },
  4180. getObjectById: function (id) {
  4181. return this.getObjectByProperty('id', id);
  4182. },
  4183. getObjectByName: function (name) {
  4184. return this.getObjectByProperty('name', name);
  4185. },
  4186. getObjectByProperty: function (name, value) {
  4187. if (this[name] === value) return this;
  4188. for (var i = 0, l = this.children.length; i < l; i++) {
  4189. var child = this.children[i];
  4190. var object = child.getObjectByProperty(name, value);
  4191. if (object !== undefined) {
  4192. return object;
  4193. }
  4194. }
  4195. return undefined;
  4196. },
  4197. getWorldPosition: function (target) {
  4198. if (target === undefined) {
  4199. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4200. target = new Vector3();
  4201. }
  4202. this.updateMatrixWorld(true);
  4203. return target.setFromMatrixPosition(this.matrixWorld);
  4204. },
  4205. getWorldQuaternion: function (target) {
  4206. if (target === undefined) {
  4207. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4208. target = new Quaternion();
  4209. }
  4210. this.updateMatrixWorld(true);
  4211. this.matrixWorld.decompose(_position, target, _scale);
  4212. return target;
  4213. },
  4214. getWorldScale: function (target) {
  4215. if (target === undefined) {
  4216. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4217. target = new Vector3();
  4218. }
  4219. this.updateMatrixWorld(true);
  4220. this.matrixWorld.decompose(_position, _quaternion$2, target);
  4221. return target;
  4222. },
  4223. getWorldDirection: function (target) {
  4224. if (target === undefined) {
  4225. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4226. target = new Vector3();
  4227. }
  4228. this.updateMatrixWorld(true);
  4229. var e = this.matrixWorld.elements;
  4230. return target.set(e[8], e[9], e[10]).normalize();
  4231. },
  4232. raycast: function () {},
  4233. traverse: function (callback) {
  4234. callback(this);
  4235. var children = this.children;
  4236. for (var i = 0, l = children.length; i < l; i++) {
  4237. children[i].traverse(callback);
  4238. }
  4239. },
  4240. traverseVisible: function (callback) {
  4241. if (this.visible === false) return;
  4242. callback(this);
  4243. var children = this.children;
  4244. for (var i = 0, l = children.length; i < l; i++) {
  4245. children[i].traverseVisible(callback);
  4246. }
  4247. },
  4248. traverseAncestors: function (callback) {
  4249. var parent = this.parent;
  4250. if (parent !== null) {
  4251. callback(parent);
  4252. parent.traverseAncestors(callback);
  4253. }
  4254. },
  4255. updateMatrix: function () {
  4256. this.matrix.compose(this.position, this.quaternion, this.scale);
  4257. this.matrixWorldNeedsUpdate = true;
  4258. },
  4259. updateMatrixWorld: function (force) {
  4260. if (this.matrixAutoUpdate) this.updateMatrix();
  4261. if (this.matrixWorldNeedsUpdate || force) {
  4262. if (this.parent === null) {
  4263. this.matrixWorld.copy(this.matrix);
  4264. } else {
  4265. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4266. }
  4267. this.matrixWorldNeedsUpdate = false;
  4268. force = true;
  4269. } // update children
  4270. var children = this.children;
  4271. for (var i = 0, l = children.length; i < l; i++) {
  4272. children[i].updateMatrixWorld(force);
  4273. }
  4274. },
  4275. updateWorldMatrix: function (updateParents, updateChildren) {
  4276. var parent = this.parent;
  4277. if (updateParents === true && parent !== null) {
  4278. parent.updateWorldMatrix(true, false);
  4279. }
  4280. if (this.matrixAutoUpdate) this.updateMatrix();
  4281. if (this.parent === null) {
  4282. this.matrixWorld.copy(this.matrix);
  4283. } else {
  4284. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4285. } // update children
  4286. if (updateChildren === true) {
  4287. var children = this.children;
  4288. for (var i = 0, l = children.length; i < l; i++) {
  4289. children[i].updateWorldMatrix(false, true);
  4290. }
  4291. }
  4292. },
  4293. toJSON: function (meta) {
  4294. // meta is a string when called from JSON.stringify
  4295. var isRootObject = meta === undefined || typeof meta === 'string';
  4296. var output = {}; // meta is a hash used to collect geometries, materials.
  4297. // not providing it implies that this is the root object
  4298. // being serialized.
  4299. if (isRootObject) {
  4300. // initialize meta obj
  4301. meta = {
  4302. geometries: {},
  4303. materials: {},
  4304. textures: {},
  4305. images: {},
  4306. shapes: {}
  4307. };
  4308. output.metadata = {
  4309. version: 4.5,
  4310. type: 'Object',
  4311. generator: 'Object3D.toJSON'
  4312. };
  4313. } // standard Object3D serialization
  4314. var object = {};
  4315. object.uuid = this.uuid;
  4316. object.type = this.type;
  4317. if (this.name !== '') object.name = this.name;
  4318. if (this.castShadow === true) object.castShadow = true;
  4319. if (this.receiveShadow === true) object.receiveShadow = true;
  4320. if (this.visible === false) object.visible = false;
  4321. if (this.frustumCulled === false) object.frustumCulled = false;
  4322. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4323. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4324. object.layers = this.layers.mask;
  4325. object.matrix = this.matrix.toArray();
  4326. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4327. if (this.isInstancedMesh) {
  4328. object.type = 'InstancedMesh';
  4329. object.count = this.count;
  4330. object.instanceMatrix = this.instanceMatrix.toJSON();
  4331. } //
  4332. function serialize(library, element) {
  4333. if (library[element.uuid] === undefined) {
  4334. library[element.uuid] = element.toJSON(meta);
  4335. }
  4336. return element.uuid;
  4337. }
  4338. if (this.isMesh || this.isLine || this.isPoints) {
  4339. object.geometry = serialize(meta.geometries, this.geometry);
  4340. var parameters = this.geometry.parameters;
  4341. if (parameters !== undefined && parameters.shapes !== undefined) {
  4342. var shapes = parameters.shapes;
  4343. if (Array.isArray(shapes)) {
  4344. for (var i = 0, l = shapes.length; i < l; i++) {
  4345. var shape = shapes[i];
  4346. serialize(meta.shapes, shape);
  4347. }
  4348. } else {
  4349. serialize(meta.shapes, shapes);
  4350. }
  4351. }
  4352. }
  4353. if (this.material !== undefined) {
  4354. if (Array.isArray(this.material)) {
  4355. var uuids = [];
  4356. for (var i = 0, l = this.material.length; i < l; i++) {
  4357. uuids.push(serialize(meta.materials, this.material[i]));
  4358. }
  4359. object.material = uuids;
  4360. } else {
  4361. object.material = serialize(meta.materials, this.material);
  4362. }
  4363. } //
  4364. if (this.children.length > 0) {
  4365. object.children = [];
  4366. for (var i = 0; i < this.children.length; i++) {
  4367. object.children.push(this.children[i].toJSON(meta).object);
  4368. }
  4369. }
  4370. if (isRootObject) {
  4371. var geometries = extractFromCache(meta.geometries);
  4372. var materials = extractFromCache(meta.materials);
  4373. var textures = extractFromCache(meta.textures);
  4374. var images = extractFromCache(meta.images);
  4375. var shapes = extractFromCache(meta.shapes);
  4376. if (geometries.length > 0) output.geometries = geometries;
  4377. if (materials.length > 0) output.materials = materials;
  4378. if (textures.length > 0) output.textures = textures;
  4379. if (images.length > 0) output.images = images;
  4380. if (shapes.length > 0) output.shapes = shapes;
  4381. }
  4382. output.object = object;
  4383. return output; // extract data from the cache hash
  4384. // remove metadata on each item
  4385. // and return as array
  4386. function extractFromCache(cache) {
  4387. var values = [];
  4388. for (var key in cache) {
  4389. var data = cache[key];
  4390. delete data.metadata;
  4391. values.push(data);
  4392. }
  4393. return values;
  4394. }
  4395. },
  4396. clone: function (recursive) {
  4397. return new this.constructor().copy(this, recursive);
  4398. },
  4399. copy: function (source, recursive) {
  4400. if (recursive === undefined) recursive = true;
  4401. this.name = source.name;
  4402. this.up.copy(source.up);
  4403. this.position.copy(source.position);
  4404. this.quaternion.copy(source.quaternion);
  4405. this.scale.copy(source.scale);
  4406. this.matrix.copy(source.matrix);
  4407. this.matrixWorld.copy(source.matrixWorld);
  4408. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4409. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4410. this.layers.mask = source.layers.mask;
  4411. this.visible = source.visible;
  4412. this.castShadow = source.castShadow;
  4413. this.receiveShadow = source.receiveShadow;
  4414. this.frustumCulled = source.frustumCulled;
  4415. this.renderOrder = source.renderOrder;
  4416. this.userData = JSON.parse(JSON.stringify(source.userData));
  4417. if (recursive === true) {
  4418. for (var i = 0; i < source.children.length; i++) {
  4419. var child = source.children[i];
  4420. this.add(child.clone());
  4421. }
  4422. }
  4423. return this;
  4424. }
  4425. });
  4426. /**
  4427. * @author mrdoob / http://mrdoob.com/
  4428. */
  4429. function Scene() {
  4430. Object3D.call(this);
  4431. this.type = 'Scene';
  4432. this.background = null;
  4433. this.environment = null;
  4434. this.fog = null;
  4435. this.overrideMaterial = null;
  4436. this.autoUpdate = true; // checked by the renderer
  4437. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  4438. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  4439. detail: this
  4440. })); // eslint-disable-line no-undef
  4441. }
  4442. }
  4443. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  4444. constructor: Scene,
  4445. isScene: true,
  4446. copy: function (source, recursive) {
  4447. Object3D.prototype.copy.call(this, source, recursive);
  4448. if (source.background !== null) this.background = source.background.clone();
  4449. if (source.environment !== null) this.environment = source.environment.clone();
  4450. if (source.fog !== null) this.fog = source.fog.clone();
  4451. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  4452. this.autoUpdate = source.autoUpdate;
  4453. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4454. return this;
  4455. },
  4456. toJSON: function (meta) {
  4457. var data = Object3D.prototype.toJSON.call(this, meta);
  4458. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  4459. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  4460. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  4461. return data;
  4462. },
  4463. dispose: function () {
  4464. this.dispatchEvent({
  4465. type: 'dispose'
  4466. });
  4467. }
  4468. });
  4469. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  4470. var _vector$1 = new Vector3();
  4471. var _box = new Box3(); // triangle centered vertices
  4472. var _v0 = new Vector3();
  4473. var _v1$2 = new Vector3();
  4474. var _v2 = new Vector3(); // triangle edge vectors
  4475. var _f0 = new Vector3();
  4476. var _f1 = new Vector3();
  4477. var _f2 = new Vector3();
  4478. var _center = new Vector3();
  4479. var _extents = new Vector3();
  4480. var _triangleNormal = new Vector3();
  4481. var _testAxis = new Vector3();
  4482. /**
  4483. * @author bhouston / http://clara.io
  4484. * @author WestLangley / http://github.com/WestLangley
  4485. */
  4486. function Box3(min, max) {
  4487. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  4488. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  4489. }
  4490. Object.assign(Box3.prototype, {
  4491. isBox3: true,
  4492. set: function (min, max) {
  4493. this.min.copy(min);
  4494. this.max.copy(max);
  4495. return this;
  4496. },
  4497. setFromArray: function (array) {
  4498. var minX = +Infinity;
  4499. var minY = +Infinity;
  4500. var minZ = +Infinity;
  4501. var maxX = -Infinity;
  4502. var maxY = -Infinity;
  4503. var maxZ = -Infinity;
  4504. for (var i = 0, l = array.length; i < l; i += 3) {
  4505. var x = array[i];
  4506. var y = array[i + 1];
  4507. var z = array[i + 2];
  4508. if (x < minX) minX = x;
  4509. if (y < minY) minY = y;
  4510. if (z < minZ) minZ = z;
  4511. if (x > maxX) maxX = x;
  4512. if (y > maxY) maxY = y;
  4513. if (z > maxZ) maxZ = z;
  4514. }
  4515. this.min.set(minX, minY, minZ);
  4516. this.max.set(maxX, maxY, maxZ);
  4517. return this;
  4518. },
  4519. setFromBufferAttribute: function (attribute) {
  4520. var minX = +Infinity;
  4521. var minY = +Infinity;
  4522. var minZ = +Infinity;
  4523. var maxX = -Infinity;
  4524. var maxY = -Infinity;
  4525. var maxZ = -Infinity;
  4526. for (var i = 0, l = attribute.count; i < l; i++) {
  4527. var x = attribute.getX(i);
  4528. var y = attribute.getY(i);
  4529. var z = attribute.getZ(i);
  4530. if (x < minX) minX = x;
  4531. if (y < minY) minY = y;
  4532. if (z < minZ) minZ = z;
  4533. if (x > maxX) maxX = x;
  4534. if (y > maxY) maxY = y;
  4535. if (z > maxZ) maxZ = z;
  4536. }
  4537. this.min.set(minX, minY, minZ);
  4538. this.max.set(maxX, maxY, maxZ);
  4539. return this;
  4540. },
  4541. setFromPoints: function (points) {
  4542. this.makeEmpty();
  4543. for (var i = 0, il = points.length; i < il; i++) {
  4544. this.expandByPoint(points[i]);
  4545. }
  4546. return this;
  4547. },
  4548. setFromCenterAndSize: function (center, size) {
  4549. var halfSize = _vector$1.copy(size).multiplyScalar(0.5);
  4550. this.min.copy(center).sub(halfSize);
  4551. this.max.copy(center).add(halfSize);
  4552. return this;
  4553. },
  4554. setFromObject: function (object) {
  4555. this.makeEmpty();
  4556. return this.expandByObject(object);
  4557. },
  4558. clone: function () {
  4559. return new this.constructor().copy(this);
  4560. },
  4561. copy: function (box) {
  4562. this.min.copy(box.min);
  4563. this.max.copy(box.max);
  4564. return this;
  4565. },
  4566. makeEmpty: function () {
  4567. this.min.x = this.min.y = this.min.z = +Infinity;
  4568. this.max.x = this.max.y = this.max.z = -Infinity;
  4569. return this;
  4570. },
  4571. isEmpty: function () {
  4572. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4573. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  4574. },
  4575. getCenter: function (target) {
  4576. if (target === undefined) {
  4577. console.warn('THREE.Box3: .getCenter() target is now required');
  4578. target = new Vector3();
  4579. }
  4580. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  4581. },
  4582. getSize: function (target) {
  4583. if (target === undefined) {
  4584. console.warn('THREE.Box3: .getSize() target is now required');
  4585. target = new Vector3();
  4586. }
  4587. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  4588. },
  4589. expandByPoint: function (point) {
  4590. this.min.min(point);
  4591. this.max.max(point);
  4592. return this;
  4593. },
  4594. expandByVector: function (vector) {
  4595. this.min.sub(vector);
  4596. this.max.add(vector);
  4597. return this;
  4598. },
  4599. expandByScalar: function (scalar) {
  4600. this.min.addScalar(-scalar);
  4601. this.max.addScalar(scalar);
  4602. return this;
  4603. },
  4604. expandByObject: function (object) {
  4605. // Computes the world-axis-aligned bounding box of an object (including its children),
  4606. // accounting for both the object's, and children's, world transforms
  4607. object.updateWorldMatrix(false, false);
  4608. var geometry = object.geometry;
  4609. if (geometry !== undefined) {
  4610. if (geometry.boundingBox === null) {
  4611. geometry.computeBoundingBox();
  4612. }
  4613. _box.copy(geometry.boundingBox);
  4614. _box.applyMatrix4(object.matrixWorld);
  4615. this.union(_box);
  4616. }
  4617. var children = object.children;
  4618. for (var i = 0, l = children.length; i < l; i++) {
  4619. this.expandByObject(children[i]);
  4620. }
  4621. return this;
  4622. },
  4623. containsPoint: function (point) {
  4624. 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;
  4625. },
  4626. containsBox: function (box) {
  4627. 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;
  4628. },
  4629. getParameter: function (point, target) {
  4630. // This can potentially have a divide by zero if the box
  4631. // has a size dimension of 0.
  4632. if (target === undefined) {
  4633. console.warn('THREE.Box3: .getParameter() target is now required');
  4634. target = new Vector3();
  4635. }
  4636. 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));
  4637. },
  4638. intersectsBox: function (box) {
  4639. // using 6 splitting planes to rule out intersections.
  4640. 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;
  4641. },
  4642. intersectsSphere: function (sphere) {
  4643. // Find the point on the AABB closest to the sphere center.
  4644. this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
  4645. return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  4646. },
  4647. intersectsPlane: function (plane) {
  4648. // We compute the minimum and maximum dot product values. If those values
  4649. // are on the same side (back or front) of the plane, then there is no intersection.
  4650. var min, max;
  4651. if (plane.normal.x > 0) {
  4652. min = plane.normal.x * this.min.x;
  4653. max = plane.normal.x * this.max.x;
  4654. } else {
  4655. min = plane.normal.x * this.max.x;
  4656. max = plane.normal.x * this.min.x;
  4657. }
  4658. if (plane.normal.y > 0) {
  4659. min += plane.normal.y * this.min.y;
  4660. max += plane.normal.y * this.max.y;
  4661. } else {
  4662. min += plane.normal.y * this.max.y;
  4663. max += plane.normal.y * this.min.y;
  4664. }
  4665. if (plane.normal.z > 0) {
  4666. min += plane.normal.z * this.min.z;
  4667. max += plane.normal.z * this.max.z;
  4668. } else {
  4669. min += plane.normal.z * this.max.z;
  4670. max += plane.normal.z * this.min.z;
  4671. }
  4672. return min <= -plane.constant && max >= -plane.constant;
  4673. },
  4674. intersectsTriangle: function (triangle) {
  4675. if (this.isEmpty()) {
  4676. return false;
  4677. } // compute box center and extents
  4678. this.getCenter(_center);
  4679. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  4680. _v0.subVectors(triangle.a, _center);
  4681. _v1$2.subVectors(triangle.b, _center);
  4682. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  4683. _f0.subVectors(_v1$2, _v0);
  4684. _f1.subVectors(_v2, _v1$2);
  4685. _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
  4686. // 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
  4687. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  4688. 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];
  4689. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  4690. return false;
  4691. } // test 3 face normals from the aabb
  4692. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  4693. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  4694. return false;
  4695. } // finally testing the face normal of the triangle
  4696. // use already existing triangle edge vectors here
  4697. _triangleNormal.crossVectors(_f0, _f1);
  4698. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  4699. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  4700. },
  4701. clampPoint: function (point, target) {
  4702. if (target === undefined) {
  4703. console.warn('THREE.Box3: .clampPoint() target is now required');
  4704. target = new Vector3();
  4705. }
  4706. return target.copy(point).clamp(this.min, this.max);
  4707. },
  4708. distanceToPoint: function (point) {
  4709. var clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
  4710. return clampedPoint.sub(point).length();
  4711. },
  4712. getBoundingSphere: function (target) {
  4713. if (target === undefined) {
  4714. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  4715. }
  4716. this.getCenter(target.center);
  4717. target.radius = this.getSize(_vector$1).length() * 0.5;
  4718. return target;
  4719. },
  4720. intersect: function (box) {
  4721. this.min.max(box.min);
  4722. 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.
  4723. if (this.isEmpty()) this.makeEmpty();
  4724. return this;
  4725. },
  4726. union: function (box) {
  4727. this.min.min(box.min);
  4728. this.max.max(box.max);
  4729. return this;
  4730. },
  4731. applyMatrix4: function (matrix) {
  4732. // transform of empty box is an empty box.
  4733. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4734. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  4735. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  4736. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  4737. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  4738. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  4739. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  4740. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  4741. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  4742. this.setFromPoints(_points);
  4743. return this;
  4744. },
  4745. translate: function (offset) {
  4746. this.min.add(offset);
  4747. this.max.add(offset);
  4748. return this;
  4749. },
  4750. equals: function (box) {
  4751. return box.min.equals(this.min) && box.max.equals(this.max);
  4752. }
  4753. });
  4754. function satForAxes(axes, v0, v1, v2, extents) {
  4755. var i, j;
  4756. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  4757. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  4758. 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
  4759. var p0 = v0.dot(_testAxis);
  4760. var p1 = v1.dot(_testAxis);
  4761. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  4762. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  4763. // points of the projected triangle are outside the projected half-length of the aabb
  4764. // the axis is seperating and we can exit
  4765. return false;
  4766. }
  4767. }
  4768. return true;
  4769. }
  4770. var _box$1 = new Box3();
  4771. /**
  4772. * @author bhouston / http://clara.io
  4773. * @author mrdoob / http://mrdoob.com/
  4774. */
  4775. function Sphere(center, radius) {
  4776. this.center = center !== undefined ? center : new Vector3();
  4777. this.radius = radius !== undefined ? radius : 0;
  4778. }
  4779. Object.assign(Sphere.prototype, {
  4780. set: function (center, radius) {
  4781. this.center.copy(center);
  4782. this.radius = radius;
  4783. return this;
  4784. },
  4785. setFromPoints: function (points, optionalCenter) {
  4786. var center = this.center;
  4787. if (optionalCenter !== undefined) {
  4788. center.copy(optionalCenter);
  4789. } else {
  4790. _box$1.setFromPoints(points).getCenter(center);
  4791. }
  4792. var maxRadiusSq = 0;
  4793. for (var i = 0, il = points.length; i < il; i++) {
  4794. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  4795. }
  4796. this.radius = Math.sqrt(maxRadiusSq);
  4797. return this;
  4798. },
  4799. clone: function () {
  4800. return new this.constructor().copy(this);
  4801. },
  4802. copy: function (sphere) {
  4803. this.center.copy(sphere.center);
  4804. this.radius = sphere.radius;
  4805. return this;
  4806. },
  4807. empty: function () {
  4808. return this.radius <= 0;
  4809. },
  4810. containsPoint: function (point) {
  4811. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  4812. },
  4813. distanceToPoint: function (point) {
  4814. return point.distanceTo(this.center) - this.radius;
  4815. },
  4816. intersectsSphere: function (sphere) {
  4817. var radiusSum = this.radius + sphere.radius;
  4818. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  4819. },
  4820. intersectsBox: function (box) {
  4821. return box.intersectsSphere(this);
  4822. },
  4823. intersectsPlane: function (plane) {
  4824. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  4825. },
  4826. clampPoint: function (point, target) {
  4827. var deltaLengthSq = this.center.distanceToSquared(point);
  4828. if (target === undefined) {
  4829. console.warn('THREE.Sphere: .clampPoint() target is now required');
  4830. target = new Vector3();
  4831. }
  4832. target.copy(point);
  4833. if (deltaLengthSq > this.radius * this.radius) {
  4834. target.sub(this.center).normalize();
  4835. target.multiplyScalar(this.radius).add(this.center);
  4836. }
  4837. return target;
  4838. },
  4839. getBoundingBox: function (target) {
  4840. if (target === undefined) {
  4841. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  4842. target = new Box3();
  4843. }
  4844. target.set(this.center, this.center);
  4845. target.expandByScalar(this.radius);
  4846. return target;
  4847. },
  4848. applyMatrix4: function (matrix) {
  4849. this.center.applyMatrix4(matrix);
  4850. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  4851. return this;
  4852. },
  4853. translate: function (offset) {
  4854. this.center.add(offset);
  4855. return this;
  4856. },
  4857. equals: function (sphere) {
  4858. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  4859. }
  4860. });
  4861. var _vector$2 = new Vector3();
  4862. var _segCenter = new Vector3();
  4863. var _segDir = new Vector3();
  4864. var _diff = new Vector3();
  4865. var _edge1 = new Vector3();
  4866. var _edge2 = new Vector3();
  4867. var _normal = new Vector3();
  4868. /**
  4869. * @author bhouston / http://clara.io
  4870. */
  4871. function Ray(origin, direction) {
  4872. this.origin = origin !== undefined ? origin : new Vector3();
  4873. this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
  4874. }
  4875. Object.assign(Ray.prototype, {
  4876. set: function (origin, direction) {
  4877. this.origin.copy(origin);
  4878. this.direction.copy(direction);
  4879. return this;
  4880. },
  4881. clone: function () {
  4882. return new this.constructor().copy(this);
  4883. },
  4884. copy: function (ray) {
  4885. this.origin.copy(ray.origin);
  4886. this.direction.copy(ray.direction);
  4887. return this;
  4888. },
  4889. at: function (t, target) {
  4890. if (target === undefined) {
  4891. console.warn('THREE.Ray: .at() target is now required');
  4892. target = new Vector3();
  4893. }
  4894. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  4895. },
  4896. lookAt: function (v) {
  4897. this.direction.copy(v).sub(this.origin).normalize();
  4898. return this;
  4899. },
  4900. recast: function (t) {
  4901. this.origin.copy(this.at(t, _vector$2));
  4902. return this;
  4903. },
  4904. closestPointToPoint: function (point, target) {
  4905. if (target === undefined) {
  4906. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  4907. target = new Vector3();
  4908. }
  4909. target.subVectors(point, this.origin);
  4910. var directionDistance = target.dot(this.direction);
  4911. if (directionDistance < 0) {
  4912. return target.copy(this.origin);
  4913. }
  4914. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  4915. },
  4916. distanceToPoint: function (point) {
  4917. return Math.sqrt(this.distanceSqToPoint(point));
  4918. },
  4919. distanceSqToPoint: function (point) {
  4920. var directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  4921. if (directionDistance < 0) {
  4922. return this.origin.distanceToSquared(point);
  4923. }
  4924. _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  4925. return _vector$2.distanceToSquared(point);
  4926. },
  4927. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  4928. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  4929. // It returns the min distance between the ray and the segment
  4930. // defined by v0 and v1
  4931. // It can also set two optional targets :
  4932. // - The closest point on the ray
  4933. // - The closest point on the segment
  4934. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  4935. _segDir.copy(v1).sub(v0).normalize();
  4936. _diff.copy(this.origin).sub(_segCenter);
  4937. var segExtent = v0.distanceTo(v1) * 0.5;
  4938. var a01 = -this.direction.dot(_segDir);
  4939. var b0 = _diff.dot(this.direction);
  4940. var b1 = -_diff.dot(_segDir);
  4941. var c = _diff.lengthSq();
  4942. var det = Math.abs(1 - a01 * a01);
  4943. var s0, s1, sqrDist, extDet;
  4944. if (det > 0) {
  4945. // The ray and segment are not parallel.
  4946. s0 = a01 * b1 - b0;
  4947. s1 = a01 * b0 - b1;
  4948. extDet = segExtent * det;
  4949. if (s0 >= 0) {
  4950. if (s1 >= -extDet) {
  4951. if (s1 <= extDet) {
  4952. // region 0
  4953. // Minimum at interior points of ray and segment.
  4954. var invDet = 1 / det;
  4955. s0 *= invDet;
  4956. s1 *= invDet;
  4957. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  4958. } else {
  4959. // region 1
  4960. s1 = segExtent;
  4961. s0 = Math.max(0, -(a01 * s1 + b0));
  4962. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4963. }
  4964. } else {
  4965. // region 5
  4966. s1 = -segExtent;
  4967. s0 = Math.max(0, -(a01 * s1 + b0));
  4968. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4969. }
  4970. } else {
  4971. if (s1 <= -extDet) {
  4972. // region 4
  4973. s0 = Math.max(0, -(-a01 * segExtent + b0));
  4974. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  4975. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4976. } else if (s1 <= extDet) {
  4977. // region 3
  4978. s0 = 0;
  4979. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  4980. sqrDist = s1 * (s1 + 2 * b1) + c;
  4981. } else {
  4982. // region 2
  4983. s0 = Math.max(0, -(a01 * segExtent + b0));
  4984. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  4985. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4986. }
  4987. }
  4988. } else {
  4989. // Ray and segment are parallel.
  4990. s1 = a01 > 0 ? -segExtent : segExtent;
  4991. s0 = Math.max(0, -(a01 * s1 + b0));
  4992. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4993. }
  4994. if (optionalPointOnRay) {
  4995. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  4996. }
  4997. if (optionalPointOnSegment) {
  4998. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  4999. }
  5000. return sqrDist;
  5001. },
  5002. intersectSphere: function (sphere, target) {
  5003. _vector$2.subVectors(sphere.center, this.origin);
  5004. var tca = _vector$2.dot(this.direction);
  5005. var d2 = _vector$2.dot(_vector$2) - tca * tca;
  5006. var radius2 = sphere.radius * sphere.radius;
  5007. if (d2 > radius2) return null;
  5008. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  5009. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  5010. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  5011. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  5012. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  5013. // in order to always return an intersect point that is in front of the ray.
  5014. 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
  5015. return this.at(t0, target);
  5016. },
  5017. intersectsSphere: function (sphere) {
  5018. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  5019. },
  5020. distanceToPlane: function (plane) {
  5021. var denominator = plane.normal.dot(this.direction);
  5022. if (denominator === 0) {
  5023. // line is coplanar, return origin
  5024. if (plane.distanceToPoint(this.origin) === 0) {
  5025. return 0;
  5026. } // Null is preferable to undefined since undefined means.... it is undefined
  5027. return null;
  5028. }
  5029. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  5030. return t >= 0 ? t : null;
  5031. },
  5032. intersectPlane: function (plane, target) {
  5033. var t = this.distanceToPlane(plane);
  5034. if (t === null) {
  5035. return null;
  5036. }
  5037. return this.at(t, target);
  5038. },
  5039. intersectsPlane: function (plane) {
  5040. // check if the ray lies on the plane first
  5041. var distToPoint = plane.distanceToPoint(this.origin);
  5042. if (distToPoint === 0) {
  5043. return true;
  5044. }
  5045. var denominator = plane.normal.dot(this.direction);
  5046. if (denominator * distToPoint < 0) {
  5047. return true;
  5048. } // ray origin is behind the plane (and is pointing behind it)
  5049. return false;
  5050. },
  5051. intersectBox: function (box, target) {
  5052. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  5053. var invdirx = 1 / this.direction.x,
  5054. invdiry = 1 / this.direction.y,
  5055. invdirz = 1 / this.direction.z;
  5056. var origin = this.origin;
  5057. if (invdirx >= 0) {
  5058. tmin = (box.min.x - origin.x) * invdirx;
  5059. tmax = (box.max.x - origin.x) * invdirx;
  5060. } else {
  5061. tmin = (box.max.x - origin.x) * invdirx;
  5062. tmax = (box.min.x - origin.x) * invdirx;
  5063. }
  5064. if (invdiry >= 0) {
  5065. tymin = (box.min.y - origin.y) * invdiry;
  5066. tymax = (box.max.y - origin.y) * invdiry;
  5067. } else {
  5068. tymin = (box.max.y - origin.y) * invdiry;
  5069. tymax = (box.min.y - origin.y) * invdiry;
  5070. }
  5071. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  5072. // (result of 0 * Infinity). x !== x returns true if x is NaN
  5073. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  5074. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  5075. if (invdirz >= 0) {
  5076. tzmin = (box.min.z - origin.z) * invdirz;
  5077. tzmax = (box.max.z - origin.z) * invdirz;
  5078. } else {
  5079. tzmin = (box.max.z - origin.z) * invdirz;
  5080. tzmax = (box.min.z - origin.z) * invdirz;
  5081. }
  5082. if (tmin > tzmax || tzmin > tmax) return null;
  5083. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  5084. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  5085. if (tmax < 0) return null;
  5086. return this.at(tmin >= 0 ? tmin : tmax, target);
  5087. },
  5088. intersectsBox: function (box) {
  5089. return this.intersectBox(box, _vector$2) !== null;
  5090. },
  5091. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  5092. // Compute the offset origin, edges, and normal.
  5093. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  5094. _edge1.subVectors(b, a);
  5095. _edge2.subVectors(c, a);
  5096. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  5097. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  5098. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  5099. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  5100. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  5101. var DdN = this.direction.dot(_normal);
  5102. var sign;
  5103. if (DdN > 0) {
  5104. if (backfaceCulling) return null;
  5105. sign = 1;
  5106. } else if (DdN < 0) {
  5107. sign = -1;
  5108. DdN = -DdN;
  5109. } else {
  5110. return null;
  5111. }
  5112. _diff.subVectors(this.origin, a);
  5113. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  5114. if (DdQxE2 < 0) {
  5115. return null;
  5116. }
  5117. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  5118. if (DdE1xQ < 0) {
  5119. return null;
  5120. } // b1+b2 > 1, no intersection
  5121. if (DdQxE2 + DdE1xQ > DdN) {
  5122. return null;
  5123. } // Line intersects triangle, check if ray does.
  5124. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  5125. if (QdN < 0) {
  5126. return null;
  5127. } // Ray intersects triangle.
  5128. return this.at(QdN / DdN, target);
  5129. },
  5130. applyMatrix4: function (matrix4) {
  5131. this.origin.applyMatrix4(matrix4);
  5132. this.direction.transformDirection(matrix4);
  5133. return this;
  5134. },
  5135. equals: function (ray) {
  5136. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  5137. }
  5138. });
  5139. /**
  5140. * @author bhouston / http://clara.io
  5141. */
  5142. var _vector1 = new Vector3();
  5143. var _vector2 = new Vector3();
  5144. var _normalMatrix = new Matrix3();
  5145. function Plane(normal, constant) {
  5146. // normal is assumed to be normalized
  5147. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  5148. this.constant = constant !== undefined ? constant : 0;
  5149. }
  5150. Object.assign(Plane.prototype, {
  5151. isPlane: true,
  5152. set: function (normal, constant) {
  5153. this.normal.copy(normal);
  5154. this.constant = constant;
  5155. return this;
  5156. },
  5157. setComponents: function (x, y, z, w) {
  5158. this.normal.set(x, y, z);
  5159. this.constant = w;
  5160. return this;
  5161. },
  5162. setFromNormalAndCoplanarPoint: function (normal, point) {
  5163. this.normal.copy(normal);
  5164. this.constant = -point.dot(this.normal);
  5165. return this;
  5166. },
  5167. setFromCoplanarPoints: function (a, b, c) {
  5168. 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)?
  5169. this.setFromNormalAndCoplanarPoint(normal, a);
  5170. return this;
  5171. },
  5172. clone: function () {
  5173. return new this.constructor().copy(this);
  5174. },
  5175. copy: function (plane) {
  5176. this.normal.copy(plane.normal);
  5177. this.constant = plane.constant;
  5178. return this;
  5179. },
  5180. normalize: function () {
  5181. // Note: will lead to a divide by zero if the plane is invalid.
  5182. var inverseNormalLength = 1.0 / this.normal.length();
  5183. this.normal.multiplyScalar(inverseNormalLength);
  5184. this.constant *= inverseNormalLength;
  5185. return this;
  5186. },
  5187. negate: function () {
  5188. this.constant *= -1;
  5189. this.normal.negate();
  5190. return this;
  5191. },
  5192. distanceToPoint: function (point) {
  5193. return this.normal.dot(point) + this.constant;
  5194. },
  5195. distanceToSphere: function (sphere) {
  5196. return this.distanceToPoint(sphere.center) - sphere.radius;
  5197. },
  5198. projectPoint: function (point, target) {
  5199. if (target === undefined) {
  5200. console.warn('THREE.Plane: .projectPoint() target is now required');
  5201. target = new Vector3();
  5202. }
  5203. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  5204. },
  5205. intersectLine: function (line, target) {
  5206. if (target === undefined) {
  5207. console.warn('THREE.Plane: .intersectLine() target is now required');
  5208. target = new Vector3();
  5209. }
  5210. var direction = line.delta(_vector1);
  5211. var denominator = this.normal.dot(direction);
  5212. if (denominator === 0) {
  5213. // line is coplanar, return origin
  5214. if (this.distanceToPoint(line.start) === 0) {
  5215. return target.copy(line.start);
  5216. } // Unsure if this is the correct method to handle this case.
  5217. return undefined;
  5218. }
  5219. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  5220. if (t < 0 || t > 1) {
  5221. return undefined;
  5222. }
  5223. return target.copy(direction).multiplyScalar(t).add(line.start);
  5224. },
  5225. intersectsLine: function (line) {
  5226. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5227. var startSign = this.distanceToPoint(line.start);
  5228. var endSign = this.distanceToPoint(line.end);
  5229. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  5230. },
  5231. intersectsBox: function (box) {
  5232. return box.intersectsPlane(this);
  5233. },
  5234. intersectsSphere: function (sphere) {
  5235. return sphere.intersectsPlane(this);
  5236. },
  5237. coplanarPoint: function (target) {
  5238. if (target === undefined) {
  5239. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  5240. target = new Vector3();
  5241. }
  5242. return target.copy(this.normal).multiplyScalar(-this.constant);
  5243. },
  5244. applyMatrix4: function (matrix, optionalNormalMatrix) {
  5245. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  5246. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  5247. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  5248. this.constant = -referencePoint.dot(normal);
  5249. return this;
  5250. },
  5251. translate: function (offset) {
  5252. this.constant -= offset.dot(this.normal);
  5253. return this;
  5254. },
  5255. equals: function (plane) {
  5256. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  5257. }
  5258. });
  5259. /**
  5260. * @author bhouston / http://clara.io
  5261. * @author mrdoob / http://mrdoob.com/
  5262. */
  5263. var _v0$1 = new Vector3();
  5264. var _v1$3 = new Vector3();
  5265. var _v2$1 = new Vector3();
  5266. var _v3 = new Vector3();
  5267. var _vab = new Vector3();
  5268. var _vac = new Vector3();
  5269. var _vbc = new Vector3();
  5270. var _vap = new Vector3();
  5271. var _vbp = new Vector3();
  5272. var _vcp = new Vector3();
  5273. function Triangle(a, b, c) {
  5274. this.a = a !== undefined ? a : new Vector3();
  5275. this.b = b !== undefined ? b : new Vector3();
  5276. this.c = c !== undefined ? c : new Vector3();
  5277. }
  5278. Object.assign(Triangle, {
  5279. getNormal: function (a, b, c, target) {
  5280. if (target === undefined) {
  5281. console.warn('THREE.Triangle: .getNormal() target is now required');
  5282. target = new Vector3();
  5283. }
  5284. target.subVectors(c, b);
  5285. _v0$1.subVectors(a, b);
  5286. target.cross(_v0$1);
  5287. var targetLengthSq = target.lengthSq();
  5288. if (targetLengthSq > 0) {
  5289. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5290. }
  5291. return target.set(0, 0, 0);
  5292. },
  5293. // static/instance method to calculate barycentric coordinates
  5294. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5295. getBarycoord: function (point, a, b, c, target) {
  5296. _v0$1.subVectors(c, a);
  5297. _v1$3.subVectors(b, a);
  5298. _v2$1.subVectors(point, a);
  5299. var dot00 = _v0$1.dot(_v0$1);
  5300. var dot01 = _v0$1.dot(_v1$3);
  5301. var dot02 = _v0$1.dot(_v2$1);
  5302. var dot11 = _v1$3.dot(_v1$3);
  5303. var dot12 = _v1$3.dot(_v2$1);
  5304. var denom = dot00 * dot11 - dot01 * dot01;
  5305. if (target === undefined) {
  5306. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  5307. target = new Vector3();
  5308. } // collinear or singular triangle
  5309. if (denom === 0) {
  5310. // arbitrary location outside of triangle?
  5311. // not sure if this is the best idea, maybe should be returning undefined
  5312. return target.set(-2, -1, -1);
  5313. }
  5314. var invDenom = 1 / denom;
  5315. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5316. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5317. return target.set(1 - u - v, v, u);
  5318. },
  5319. containsPoint: function (point, a, b, c) {
  5320. Triangle.getBarycoord(point, a, b, c, _v3);
  5321. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  5322. },
  5323. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  5324. this.getBarycoord(point, p1, p2, p3, _v3);
  5325. target.set(0, 0);
  5326. target.addScaledVector(uv1, _v3.x);
  5327. target.addScaledVector(uv2, _v3.y);
  5328. target.addScaledVector(uv3, _v3.z);
  5329. return target;
  5330. },
  5331. isFrontFacing: function (a, b, c, direction) {
  5332. _v0$1.subVectors(c, b);
  5333. _v1$3.subVectors(a, b); // strictly front facing
  5334. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5335. }
  5336. });
  5337. Object.assign(Triangle.prototype, {
  5338. set: function (a, b, c) {
  5339. this.a.copy(a);
  5340. this.b.copy(b);
  5341. this.c.copy(c);
  5342. return this;
  5343. },
  5344. setFromPointsAndIndices: function (points, i0, i1, i2) {
  5345. this.a.copy(points[i0]);
  5346. this.b.copy(points[i1]);
  5347. this.c.copy(points[i2]);
  5348. return this;
  5349. },
  5350. clone: function () {
  5351. return new this.constructor().copy(this);
  5352. },
  5353. copy: function (triangle) {
  5354. this.a.copy(triangle.a);
  5355. this.b.copy(triangle.b);
  5356. this.c.copy(triangle.c);
  5357. return this;
  5358. },
  5359. getArea: function () {
  5360. _v0$1.subVectors(this.c, this.b);
  5361. _v1$3.subVectors(this.a, this.b);
  5362. return _v0$1.cross(_v1$3).length() * 0.5;
  5363. },
  5364. getMidpoint: function (target) {
  5365. if (target === undefined) {
  5366. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  5367. target = new Vector3();
  5368. }
  5369. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5370. },
  5371. getNormal: function (target) {
  5372. return Triangle.getNormal(this.a, this.b, this.c, target);
  5373. },
  5374. getPlane: function (target) {
  5375. if (target === undefined) {
  5376. console.warn('THREE.Triangle: .getPlane() target is now required');
  5377. target = new Plane();
  5378. }
  5379. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5380. },
  5381. getBarycoord: function (point, target) {
  5382. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5383. },
  5384. getUV: function (point, uv1, uv2, uv3, target) {
  5385. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5386. },
  5387. containsPoint: function (point) {
  5388. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5389. },
  5390. isFrontFacing: function (direction) {
  5391. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5392. },
  5393. intersectsBox: function (box) {
  5394. return box.intersectsTriangle(this);
  5395. },
  5396. closestPointToPoint: function (p, target) {
  5397. if (target === undefined) {
  5398. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  5399. target = new Vector3();
  5400. }
  5401. var a = this.a,
  5402. b = this.b,
  5403. c = this.c;
  5404. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5405. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5406. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5407. // basically, we're distinguishing which of the voronoi regions of the triangle
  5408. // the point lies in with the minimum amount of redundant computation.
  5409. _vab.subVectors(b, a);
  5410. _vac.subVectors(c, a);
  5411. _vap.subVectors(p, a);
  5412. var d1 = _vab.dot(_vap);
  5413. var d2 = _vac.dot(_vap);
  5414. if (d1 <= 0 && d2 <= 0) {
  5415. // vertex region of A; barycentric coords (1, 0, 0)
  5416. return target.copy(a);
  5417. }
  5418. _vbp.subVectors(p, b);
  5419. var d3 = _vab.dot(_vbp);
  5420. var d4 = _vac.dot(_vbp);
  5421. if (d3 >= 0 && d4 <= d3) {
  5422. // vertex region of B; barycentric coords (0, 1, 0)
  5423. return target.copy(b);
  5424. }
  5425. var vc = d1 * d4 - d3 * d2;
  5426. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5427. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5428. return target.copy(a).addScaledVector(_vab, v);
  5429. }
  5430. _vcp.subVectors(p, c);
  5431. var d5 = _vab.dot(_vcp);
  5432. var d6 = _vac.dot(_vcp);
  5433. if (d6 >= 0 && d5 <= d6) {
  5434. // vertex region of C; barycentric coords (0, 0, 1)
  5435. return target.copy(c);
  5436. }
  5437. var vb = d5 * d2 - d1 * d6;
  5438. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5439. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5440. return target.copy(a).addScaledVector(_vac, w);
  5441. }
  5442. var va = d3 * d6 - d5 * d4;
  5443. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5444. _vbc.subVectors(c, b);
  5445. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5446. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5447. } // face region
  5448. var denom = 1 / (va + vb + vc); // u = va * denom
  5449. v = vb * denom;
  5450. w = vc * denom;
  5451. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5452. },
  5453. equals: function (triangle) {
  5454. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5455. }
  5456. });
  5457. /**
  5458. * @author mrdoob / http://mrdoob.com/
  5459. */
  5460. var _colorKeywords = {
  5461. 'aliceblue': 0xF0F8FF,
  5462. 'antiquewhite': 0xFAEBD7,
  5463. 'aqua': 0x00FFFF,
  5464. 'aquamarine': 0x7FFFD4,
  5465. 'azure': 0xF0FFFF,
  5466. 'beige': 0xF5F5DC,
  5467. 'bisque': 0xFFE4C4,
  5468. 'black': 0x000000,
  5469. 'blanchedalmond': 0xFFEBCD,
  5470. 'blue': 0x0000FF,
  5471. 'blueviolet': 0x8A2BE2,
  5472. 'brown': 0xA52A2A,
  5473. 'burlywood': 0xDEB887,
  5474. 'cadetblue': 0x5F9EA0,
  5475. 'chartreuse': 0x7FFF00,
  5476. 'chocolate': 0xD2691E,
  5477. 'coral': 0xFF7F50,
  5478. 'cornflowerblue': 0x6495ED,
  5479. 'cornsilk': 0xFFF8DC,
  5480. 'crimson': 0xDC143C,
  5481. 'cyan': 0x00FFFF,
  5482. 'darkblue': 0x00008B,
  5483. 'darkcyan': 0x008B8B,
  5484. 'darkgoldenrod': 0xB8860B,
  5485. 'darkgray': 0xA9A9A9,
  5486. 'darkgreen': 0x006400,
  5487. 'darkgrey': 0xA9A9A9,
  5488. 'darkkhaki': 0xBDB76B,
  5489. 'darkmagenta': 0x8B008B,
  5490. 'darkolivegreen': 0x556B2F,
  5491. 'darkorange': 0xFF8C00,
  5492. 'darkorchid': 0x9932CC,
  5493. 'darkred': 0x8B0000,
  5494. 'darksalmon': 0xE9967A,
  5495. 'darkseagreen': 0x8FBC8F,
  5496. 'darkslateblue': 0x483D8B,
  5497. 'darkslategray': 0x2F4F4F,
  5498. 'darkslategrey': 0x2F4F4F,
  5499. 'darkturquoise': 0x00CED1,
  5500. 'darkviolet': 0x9400D3,
  5501. 'deeppink': 0xFF1493,
  5502. 'deepskyblue': 0x00BFFF,
  5503. 'dimgray': 0x696969,
  5504. 'dimgrey': 0x696969,
  5505. 'dodgerblue': 0x1E90FF,
  5506. 'firebrick': 0xB22222,
  5507. 'floralwhite': 0xFFFAF0,
  5508. 'forestgreen': 0x228B22,
  5509. 'fuchsia': 0xFF00FF,
  5510. 'gainsboro': 0xDCDCDC,
  5511. 'ghostwhite': 0xF8F8FF,
  5512. 'gold': 0xFFD700,
  5513. 'goldenrod': 0xDAA520,
  5514. 'gray': 0x808080,
  5515. 'green': 0x008000,
  5516. 'greenyellow': 0xADFF2F,
  5517. 'grey': 0x808080,
  5518. 'honeydew': 0xF0FFF0,
  5519. 'hotpink': 0xFF69B4,
  5520. 'indianred': 0xCD5C5C,
  5521. 'indigo': 0x4B0082,
  5522. 'ivory': 0xFFFFF0,
  5523. 'khaki': 0xF0E68C,
  5524. 'lavender': 0xE6E6FA,
  5525. 'lavenderblush': 0xFFF0F5,
  5526. 'lawngreen': 0x7CFC00,
  5527. 'lemonchiffon': 0xFFFACD,
  5528. 'lightblue': 0xADD8E6,
  5529. 'lightcoral': 0xF08080,
  5530. 'lightcyan': 0xE0FFFF,
  5531. 'lightgoldenrodyellow': 0xFAFAD2,
  5532. 'lightgray': 0xD3D3D3,
  5533. 'lightgreen': 0x90EE90,
  5534. 'lightgrey': 0xD3D3D3,
  5535. 'lightpink': 0xFFB6C1,
  5536. 'lightsalmon': 0xFFA07A,
  5537. 'lightseagreen': 0x20B2AA,
  5538. 'lightskyblue': 0x87CEFA,
  5539. 'lightslategray': 0x778899,
  5540. 'lightslategrey': 0x778899,
  5541. 'lightsteelblue': 0xB0C4DE,
  5542. 'lightyellow': 0xFFFFE0,
  5543. 'lime': 0x00FF00,
  5544. 'limegreen': 0x32CD32,
  5545. 'linen': 0xFAF0E6,
  5546. 'magenta': 0xFF00FF,
  5547. 'maroon': 0x800000,
  5548. 'mediumaquamarine': 0x66CDAA,
  5549. 'mediumblue': 0x0000CD,
  5550. 'mediumorchid': 0xBA55D3,
  5551. 'mediumpurple': 0x9370DB,
  5552. 'mediumseagreen': 0x3CB371,
  5553. 'mediumslateblue': 0x7B68EE,
  5554. 'mediumspringgreen': 0x00FA9A,
  5555. 'mediumturquoise': 0x48D1CC,
  5556. 'mediumvioletred': 0xC71585,
  5557. 'midnightblue': 0x191970,
  5558. 'mintcream': 0xF5FFFA,
  5559. 'mistyrose': 0xFFE4E1,
  5560. 'moccasin': 0xFFE4B5,
  5561. 'navajowhite': 0xFFDEAD,
  5562. 'navy': 0x000080,
  5563. 'oldlace': 0xFDF5E6,
  5564. 'olive': 0x808000,
  5565. 'olivedrab': 0x6B8E23,
  5566. 'orange': 0xFFA500,
  5567. 'orangered': 0xFF4500,
  5568. 'orchid': 0xDA70D6,
  5569. 'palegoldenrod': 0xEEE8AA,
  5570. 'palegreen': 0x98FB98,
  5571. 'paleturquoise': 0xAFEEEE,
  5572. 'palevioletred': 0xDB7093,
  5573. 'papayawhip': 0xFFEFD5,
  5574. 'peachpuff': 0xFFDAB9,
  5575. 'peru': 0xCD853F,
  5576. 'pink': 0xFFC0CB,
  5577. 'plum': 0xDDA0DD,
  5578. 'powderblue': 0xB0E0E6,
  5579. 'purple': 0x800080,
  5580. 'rebeccapurple': 0x663399,
  5581. 'red': 0xFF0000,
  5582. 'rosybrown': 0xBC8F8F,
  5583. 'royalblue': 0x4169E1,
  5584. 'saddlebrown': 0x8B4513,
  5585. 'salmon': 0xFA8072,
  5586. 'sandybrown': 0xF4A460,
  5587. 'seagreen': 0x2E8B57,
  5588. 'seashell': 0xFFF5EE,
  5589. 'sienna': 0xA0522D,
  5590. 'silver': 0xC0C0C0,
  5591. 'skyblue': 0x87CEEB,
  5592. 'slateblue': 0x6A5ACD,
  5593. 'slategray': 0x708090,
  5594. 'slategrey': 0x708090,
  5595. 'snow': 0xFFFAFA,
  5596. 'springgreen': 0x00FF7F,
  5597. 'steelblue': 0x4682B4,
  5598. 'tan': 0xD2B48C,
  5599. 'teal': 0x008080,
  5600. 'thistle': 0xD8BFD8,
  5601. 'tomato': 0xFF6347,
  5602. 'turquoise': 0x40E0D0,
  5603. 'violet': 0xEE82EE,
  5604. 'wheat': 0xF5DEB3,
  5605. 'white': 0xFFFFFF,
  5606. 'whitesmoke': 0xF5F5F5,
  5607. 'yellow': 0xFFFF00,
  5608. 'yellowgreen': 0x9ACD32
  5609. };
  5610. var _hslA = {
  5611. h: 0,
  5612. s: 0,
  5613. l: 0
  5614. };
  5615. var _hslB = {
  5616. h: 0,
  5617. s: 0,
  5618. l: 0
  5619. };
  5620. function Color(r, g, b) {
  5621. if (g === undefined && b === undefined) {
  5622. // r is THREE.Color, hex or string
  5623. return this.set(r);
  5624. }
  5625. return this.setRGB(r, g, b);
  5626. }
  5627. function hue2rgb(p, q, t) {
  5628. if (t < 0) t += 1;
  5629. if (t > 1) t -= 1;
  5630. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5631. if (t < 1 / 2) return q;
  5632. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5633. return p;
  5634. }
  5635. function SRGBToLinear(c) {
  5636. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5637. }
  5638. function LinearToSRGB(c) {
  5639. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5640. }
  5641. Object.assign(Color.prototype, {
  5642. isColor: true,
  5643. r: 1,
  5644. g: 1,
  5645. b: 1,
  5646. set: function (value) {
  5647. if (value && value.isColor) {
  5648. this.copy(value);
  5649. } else if (typeof value === 'number') {
  5650. this.setHex(value);
  5651. } else if (typeof value === 'string') {
  5652. this.setStyle(value);
  5653. }
  5654. return this;
  5655. },
  5656. setScalar: function (scalar) {
  5657. this.r = scalar;
  5658. this.g = scalar;
  5659. this.b = scalar;
  5660. return this;
  5661. },
  5662. setHex: function (hex) {
  5663. hex = Math.floor(hex);
  5664. this.r = (hex >> 16 & 255) / 255;
  5665. this.g = (hex >> 8 & 255) / 255;
  5666. this.b = (hex & 255) / 255;
  5667. return this;
  5668. },
  5669. setRGB: function (r, g, b) {
  5670. this.r = r;
  5671. this.g = g;
  5672. this.b = b;
  5673. return this;
  5674. },
  5675. setHSL: function (h, s, l) {
  5676. // h,s,l ranges are in 0.0 - 1.0
  5677. h = MathUtils.euclideanModulo(h, 1);
  5678. s = MathUtils.clamp(s, 0, 1);
  5679. l = MathUtils.clamp(l, 0, 1);
  5680. if (s === 0) {
  5681. this.r = this.g = this.b = l;
  5682. } else {
  5683. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5684. var q = 2 * l - p;
  5685. this.r = hue2rgb(q, p, h + 1 / 3);
  5686. this.g = hue2rgb(q, p, h);
  5687. this.b = hue2rgb(q, p, h - 1 / 3);
  5688. }
  5689. return this;
  5690. },
  5691. setStyle: function (style) {
  5692. function handleAlpha(string) {
  5693. if (string === undefined) return;
  5694. if (parseFloat(string) < 1) {
  5695. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5696. }
  5697. }
  5698. var m;
  5699. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  5700. // rgb / hsl
  5701. var color;
  5702. var name = m[1];
  5703. var components = m[2];
  5704. switch (name) {
  5705. case 'rgb':
  5706. case 'rgba':
  5707. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5708. // rgb(255,0,0) rgba(255,0,0,0.5)
  5709. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5710. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5711. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5712. handleAlpha(color[5]);
  5713. return this;
  5714. }
  5715. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5716. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5717. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5718. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5719. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5720. handleAlpha(color[5]);
  5721. return this;
  5722. }
  5723. break;
  5724. case 'hsl':
  5725. case 'hsla':
  5726. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5727. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5728. var h = parseFloat(color[1]) / 360;
  5729. var s = parseInt(color[2], 10) / 100;
  5730. var l = parseInt(color[3], 10) / 100;
  5731. handleAlpha(color[5]);
  5732. return this.setHSL(h, s, l);
  5733. }
  5734. break;
  5735. }
  5736. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  5737. // hex color
  5738. var hex = m[1];
  5739. var size = hex.length;
  5740. if (size === 3) {
  5741. // #ff0
  5742. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5743. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5744. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5745. return this;
  5746. } else if (size === 6) {
  5747. // #ff0000
  5748. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5749. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5750. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5751. return this;
  5752. }
  5753. }
  5754. if (style && style.length > 0) {
  5755. return this.setColorName(style);
  5756. }
  5757. return this;
  5758. },
  5759. setColorName: function (style) {
  5760. // color keywords
  5761. var hex = _colorKeywords[style];
  5762. if (hex !== undefined) {
  5763. // red
  5764. this.setHex(hex);
  5765. } else {
  5766. // unknown color
  5767. console.warn('THREE.Color: Unknown color ' + style);
  5768. }
  5769. return this;
  5770. },
  5771. clone: function () {
  5772. return new this.constructor(this.r, this.g, this.b);
  5773. },
  5774. copy: function (color) {
  5775. this.r = color.r;
  5776. this.g = color.g;
  5777. this.b = color.b;
  5778. return this;
  5779. },
  5780. copyGammaToLinear: function (color, gammaFactor) {
  5781. if (gammaFactor === undefined) gammaFactor = 2.0;
  5782. this.r = Math.pow(color.r, gammaFactor);
  5783. this.g = Math.pow(color.g, gammaFactor);
  5784. this.b = Math.pow(color.b, gammaFactor);
  5785. return this;
  5786. },
  5787. copyLinearToGamma: function (color, gammaFactor) {
  5788. if (gammaFactor === undefined) gammaFactor = 2.0;
  5789. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5790. this.r = Math.pow(color.r, safeInverse);
  5791. this.g = Math.pow(color.g, safeInverse);
  5792. this.b = Math.pow(color.b, safeInverse);
  5793. return this;
  5794. },
  5795. convertGammaToLinear: function (gammaFactor) {
  5796. this.copyGammaToLinear(this, gammaFactor);
  5797. return this;
  5798. },
  5799. convertLinearToGamma: function (gammaFactor) {
  5800. this.copyLinearToGamma(this, gammaFactor);
  5801. return this;
  5802. },
  5803. copySRGBToLinear: function (color) {
  5804. this.r = SRGBToLinear(color.r);
  5805. this.g = SRGBToLinear(color.g);
  5806. this.b = SRGBToLinear(color.b);
  5807. return this;
  5808. },
  5809. copyLinearToSRGB: function (color) {
  5810. this.r = LinearToSRGB(color.r);
  5811. this.g = LinearToSRGB(color.g);
  5812. this.b = LinearToSRGB(color.b);
  5813. return this;
  5814. },
  5815. convertSRGBToLinear: function () {
  5816. this.copySRGBToLinear(this);
  5817. return this;
  5818. },
  5819. convertLinearToSRGB: function () {
  5820. this.copyLinearToSRGB(this);
  5821. return this;
  5822. },
  5823. getHex: function () {
  5824. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5825. },
  5826. getHexString: function () {
  5827. return ('000000' + this.getHex().toString(16)).slice(-6);
  5828. },
  5829. getHSL: function (target) {
  5830. // h,s,l ranges are in 0.0 - 1.0
  5831. if (target === undefined) {
  5832. console.warn('THREE.Color: .getHSL() target is now required');
  5833. target = {
  5834. h: 0,
  5835. s: 0,
  5836. l: 0
  5837. };
  5838. }
  5839. var r = this.r,
  5840. g = this.g,
  5841. b = this.b;
  5842. var max = Math.max(r, g, b);
  5843. var min = Math.min(r, g, b);
  5844. var hue, saturation;
  5845. var lightness = (min + max) / 2.0;
  5846. if (min === max) {
  5847. hue = 0;
  5848. saturation = 0;
  5849. } else {
  5850. var delta = max - min;
  5851. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5852. switch (max) {
  5853. case r:
  5854. hue = (g - b) / delta + (g < b ? 6 : 0);
  5855. break;
  5856. case g:
  5857. hue = (b - r) / delta + 2;
  5858. break;
  5859. case b:
  5860. hue = (r - g) / delta + 4;
  5861. break;
  5862. }
  5863. hue /= 6;
  5864. }
  5865. target.h = hue;
  5866. target.s = saturation;
  5867. target.l = lightness;
  5868. return target;
  5869. },
  5870. getStyle: function () {
  5871. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5872. },
  5873. offsetHSL: function (h, s, l) {
  5874. this.getHSL(_hslA);
  5875. _hslA.h += h;
  5876. _hslA.s += s;
  5877. _hslA.l += l;
  5878. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5879. return this;
  5880. },
  5881. add: function (color) {
  5882. this.r += color.r;
  5883. this.g += color.g;
  5884. this.b += color.b;
  5885. return this;
  5886. },
  5887. addColors: function (color1, color2) {
  5888. this.r = color1.r + color2.r;
  5889. this.g = color1.g + color2.g;
  5890. this.b = color1.b + color2.b;
  5891. return this;
  5892. },
  5893. addScalar: function (s) {
  5894. this.r += s;
  5895. this.g += s;
  5896. this.b += s;
  5897. return this;
  5898. },
  5899. sub: function (color) {
  5900. this.r = Math.max(0, this.r - color.r);
  5901. this.g = Math.max(0, this.g - color.g);
  5902. this.b = Math.max(0, this.b - color.b);
  5903. return this;
  5904. },
  5905. multiply: function (color) {
  5906. this.r *= color.r;
  5907. this.g *= color.g;
  5908. this.b *= color.b;
  5909. return this;
  5910. },
  5911. multiplyScalar: function (s) {
  5912. this.r *= s;
  5913. this.g *= s;
  5914. this.b *= s;
  5915. return this;
  5916. },
  5917. lerp: function (color, alpha) {
  5918. this.r += (color.r - this.r) * alpha;
  5919. this.g += (color.g - this.g) * alpha;
  5920. this.b += (color.b - this.b) * alpha;
  5921. return this;
  5922. },
  5923. lerpHSL: function (color, alpha) {
  5924. this.getHSL(_hslA);
  5925. color.getHSL(_hslB);
  5926. var h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
  5927. var s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
  5928. var l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
  5929. this.setHSL(h, s, l);
  5930. return this;
  5931. },
  5932. equals: function (c) {
  5933. return c.r === this.r && c.g === this.g && c.b === this.b;
  5934. },
  5935. fromArray: function (array, offset) {
  5936. if (offset === undefined) offset = 0;
  5937. this.r = array[offset];
  5938. this.g = array[offset + 1];
  5939. this.b = array[offset + 2];
  5940. return this;
  5941. },
  5942. toArray: function (array, offset) {
  5943. if (array === undefined) array = [];
  5944. if (offset === undefined) offset = 0;
  5945. array[offset] = this.r;
  5946. array[offset + 1] = this.g;
  5947. array[offset + 2] = this.b;
  5948. return array;
  5949. },
  5950. toJSON: function () {
  5951. return this.getHex();
  5952. }
  5953. });
  5954. Color.NAMES = _colorKeywords;
  5955. /**
  5956. * @author mrdoob / http://mrdoob.com/
  5957. * @author alteredq / http://alteredqualia.com/
  5958. */
  5959. function Face3(a, b, c, normal, color, materialIndex) {
  5960. this.a = a;
  5961. this.b = b;
  5962. this.c = c;
  5963. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  5964. this.vertexNormals = Array.isArray(normal) ? normal : [];
  5965. this.color = color && color.isColor ? color : new Color();
  5966. this.vertexColors = Array.isArray(color) ? color : [];
  5967. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5968. }
  5969. Object.assign(Face3.prototype, {
  5970. clone: function () {
  5971. return new this.constructor().copy(this);
  5972. },
  5973. copy: function (source) {
  5974. this.a = source.a;
  5975. this.b = source.b;
  5976. this.c = source.c;
  5977. this.normal.copy(source.normal);
  5978. this.color.copy(source.color);
  5979. this.materialIndex = source.materialIndex;
  5980. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  5981. this.vertexNormals[i] = source.vertexNormals[i].clone();
  5982. }
  5983. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  5984. this.vertexColors[i] = source.vertexColors[i].clone();
  5985. }
  5986. return this;
  5987. }
  5988. });
  5989. /**
  5990. * @author mrdoob / http://mrdoob.com/
  5991. * @author alteredq / http://alteredqualia.com/
  5992. */
  5993. var materialId = 0;
  5994. function Material() {
  5995. Object.defineProperty(this, 'id', {
  5996. value: materialId++
  5997. });
  5998. this.uuid = MathUtils.generateUUID();
  5999. this.name = '';
  6000. this.type = 'Material';
  6001. this.fog = true;
  6002. this.blending = NormalBlending;
  6003. this.side = FrontSide;
  6004. this.flatShading = false;
  6005. this.vertexColors = false;
  6006. this.opacity = 1;
  6007. this.transparent = false;
  6008. this.blendSrc = SrcAlphaFactor;
  6009. this.blendDst = OneMinusSrcAlphaFactor;
  6010. this.blendEquation = AddEquation;
  6011. this.blendSrcAlpha = null;
  6012. this.blendDstAlpha = null;
  6013. this.blendEquationAlpha = null;
  6014. this.depthFunc = LessEqualDepth;
  6015. this.depthTest = true;
  6016. this.depthWrite = true;
  6017. this.stencilWriteMask = 0xff;
  6018. this.stencilFunc = AlwaysStencilFunc;
  6019. this.stencilRef = 0;
  6020. this.stencilFuncMask = 0xff;
  6021. this.stencilFail = KeepStencilOp;
  6022. this.stencilZFail = KeepStencilOp;
  6023. this.stencilZPass = KeepStencilOp;
  6024. this.stencilWrite = false;
  6025. this.clippingPlanes = null;
  6026. this.clipIntersection = false;
  6027. this.clipShadows = false;
  6028. this.shadowSide = null;
  6029. this.colorWrite = true;
  6030. this.precision = null; // override the renderer's default precision for this material
  6031. this.polygonOffset = false;
  6032. this.polygonOffsetFactor = 0;
  6033. this.polygonOffsetUnits = 0;
  6034. this.dithering = false;
  6035. this.alphaTest = 0;
  6036. this.premultipliedAlpha = false;
  6037. this.visible = true;
  6038. this.toneMapped = true;
  6039. this.userData = {};
  6040. this.version = 0;
  6041. }
  6042. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6043. constructor: Material,
  6044. isMaterial: true,
  6045. onBeforeCompile: function () {},
  6046. setValues: function (values) {
  6047. if (values === undefined) return;
  6048. for (var key in values) {
  6049. var newValue = values[key];
  6050. if (newValue === undefined) {
  6051. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  6052. continue;
  6053. } // for backward compatability if shading is set in the constructor
  6054. if (key === 'shading') {
  6055. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  6056. this.flatShading = newValue === FlatShading ? true : false;
  6057. continue;
  6058. }
  6059. var currentValue = this[key];
  6060. if (currentValue === undefined) {
  6061. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6062. continue;
  6063. }
  6064. if (currentValue && currentValue.isColor) {
  6065. currentValue.set(newValue);
  6066. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6067. currentValue.copy(newValue);
  6068. } else {
  6069. this[key] = newValue;
  6070. }
  6071. }
  6072. },
  6073. toJSON: function (meta) {
  6074. var isRoot = meta === undefined || typeof meta === 'string';
  6075. if (isRoot) {
  6076. meta = {
  6077. textures: {},
  6078. images: {}
  6079. };
  6080. }
  6081. var data = {
  6082. metadata: {
  6083. version: 4.5,
  6084. type: 'Material',
  6085. generator: 'Material.toJSON'
  6086. }
  6087. }; // standard Material serialization
  6088. data.uuid = this.uuid;
  6089. data.type = this.type;
  6090. if (this.name !== '') data.name = this.name;
  6091. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6092. if (this.roughness !== undefined) data.roughness = this.roughness;
  6093. if (this.metalness !== undefined) data.metalness = this.metalness;
  6094. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6095. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6096. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6097. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6098. if (this.shininess !== undefined) data.shininess = this.shininess;
  6099. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  6100. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  6101. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  6102. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  6103. }
  6104. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  6105. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  6106. }
  6107. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  6108. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  6109. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  6110. }
  6111. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  6112. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  6113. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  6114. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  6115. if (this.aoMap && this.aoMap.isTexture) {
  6116. data.aoMap = this.aoMap.toJSON(meta).uuid;
  6117. data.aoMapIntensity = this.aoMapIntensity;
  6118. }
  6119. if (this.bumpMap && this.bumpMap.isTexture) {
  6120. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  6121. data.bumpScale = this.bumpScale;
  6122. }
  6123. if (this.normalMap && this.normalMap.isTexture) {
  6124. data.normalMap = this.normalMap.toJSON(meta).uuid;
  6125. data.normalMapType = this.normalMapType;
  6126. data.normalScale = this.normalScale.toArray();
  6127. }
  6128. if (this.displacementMap && this.displacementMap.isTexture) {
  6129. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  6130. data.displacementScale = this.displacementScale;
  6131. data.displacementBias = this.displacementBias;
  6132. }
  6133. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  6134. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  6135. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  6136. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  6137. if (this.envMap && this.envMap.isTexture) {
  6138. data.envMap = this.envMap.toJSON(meta).uuid;
  6139. data.reflectivity = this.reflectivity; // Scale behind envMap
  6140. data.refractionRatio = this.refractionRatio;
  6141. if (this.combine !== undefined) data.combine = this.combine;
  6142. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  6143. }
  6144. if (this.gradientMap && this.gradientMap.isTexture) {
  6145. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  6146. }
  6147. if (this.size !== undefined) data.size = this.size;
  6148. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  6149. if (this.blending !== NormalBlending) data.blending = this.blending;
  6150. if (this.flatShading === true) data.flatShading = this.flatShading;
  6151. if (this.side !== FrontSide) data.side = this.side;
  6152. if (this.vertexColors) data.vertexColors = true;
  6153. if (this.opacity < 1) data.opacity = this.opacity;
  6154. if (this.transparent === true) data.transparent = this.transparent;
  6155. data.depthFunc = this.depthFunc;
  6156. data.depthTest = this.depthTest;
  6157. data.depthWrite = this.depthWrite;
  6158. data.stencilWrite = this.stencilWrite;
  6159. data.stencilWriteMask = this.stencilWriteMask;
  6160. data.stencilFunc = this.stencilFunc;
  6161. data.stencilRef = this.stencilRef;
  6162. data.stencilFuncMask = this.stencilFuncMask;
  6163. data.stencilFail = this.stencilFail;
  6164. data.stencilZFail = this.stencilZFail;
  6165. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  6166. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  6167. if (this.polygonOffset === true) data.polygonOffset = true;
  6168. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  6169. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  6170. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  6171. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  6172. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  6173. if (this.scale !== undefined) data.scale = this.scale;
  6174. if (this.dithering === true) data.dithering = true;
  6175. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  6176. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  6177. if (this.wireframe === true) data.wireframe = this.wireframe;
  6178. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  6179. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  6180. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  6181. if (this.morphTargets === true) data.morphTargets = true;
  6182. if (this.morphNormals === true) data.morphNormals = true;
  6183. if (this.skinning === true) data.skinning = true;
  6184. if (this.visible === false) data.visible = false;
  6185. if (this.toneMapped === false) data.toneMapped = false;
  6186. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  6187. function extractFromCache(cache) {
  6188. var values = [];
  6189. for (var key in cache) {
  6190. var data = cache[key];
  6191. delete data.metadata;
  6192. values.push(data);
  6193. }
  6194. return values;
  6195. }
  6196. if (isRoot) {
  6197. var textures = extractFromCache(meta.textures);
  6198. var images = extractFromCache(meta.images);
  6199. if (textures.length > 0) data.textures = textures;
  6200. if (images.length > 0) data.images = images;
  6201. }
  6202. return data;
  6203. },
  6204. clone: function () {
  6205. return new this.constructor().copy(this);
  6206. },
  6207. copy: function (source) {
  6208. this.name = source.name;
  6209. this.fog = source.fog;
  6210. this.blending = source.blending;
  6211. this.side = source.side;
  6212. this.flatShading = source.flatShading;
  6213. this.vertexColors = source.vertexColors;
  6214. this.opacity = source.opacity;
  6215. this.transparent = source.transparent;
  6216. this.blendSrc = source.blendSrc;
  6217. this.blendDst = source.blendDst;
  6218. this.blendEquation = source.blendEquation;
  6219. this.blendSrcAlpha = source.blendSrcAlpha;
  6220. this.blendDstAlpha = source.blendDstAlpha;
  6221. this.blendEquationAlpha = source.blendEquationAlpha;
  6222. this.depthFunc = source.depthFunc;
  6223. this.depthTest = source.depthTest;
  6224. this.depthWrite = source.depthWrite;
  6225. this.stencilWriteMask = source.stencilWriteMask;
  6226. this.stencilFunc = source.stencilFunc;
  6227. this.stencilRef = source.stencilRef;
  6228. this.stencilFuncMask = source.stencilFuncMask;
  6229. this.stencilFail = source.stencilFail;
  6230. this.stencilZFail = source.stencilZFail;
  6231. this.stencilZPass = source.stencilZPass;
  6232. this.stencilWrite = source.stencilWrite;
  6233. var srcPlanes = source.clippingPlanes,
  6234. dstPlanes = null;
  6235. if (srcPlanes !== null) {
  6236. var n = srcPlanes.length;
  6237. dstPlanes = new Array(n);
  6238. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  6239. }
  6240. this.clippingPlanes = dstPlanes;
  6241. this.clipIntersection = source.clipIntersection;
  6242. this.clipShadows = source.clipShadows;
  6243. this.shadowSide = source.shadowSide;
  6244. this.colorWrite = source.colorWrite;
  6245. this.precision = source.precision;
  6246. this.polygonOffset = source.polygonOffset;
  6247. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6248. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6249. this.dithering = source.dithering;
  6250. this.alphaTest = source.alphaTest;
  6251. this.premultipliedAlpha = source.premultipliedAlpha;
  6252. this.visible = source.visible;
  6253. this.toneMapped = source.toneMapped;
  6254. this.userData = JSON.parse(JSON.stringify(source.userData));
  6255. return this;
  6256. },
  6257. dispose: function () {
  6258. this.dispatchEvent({
  6259. type: 'dispose'
  6260. });
  6261. }
  6262. });
  6263. Object.defineProperty(Material.prototype, 'needsUpdate', {
  6264. set: function (value) {
  6265. if (value === true) this.version++;
  6266. }
  6267. });
  6268. /**
  6269. * @author mrdoob / http://mrdoob.com/
  6270. * @author alteredq / http://alteredqualia.com/
  6271. *
  6272. * parameters = {
  6273. * color: <hex>,
  6274. * opacity: <float>,
  6275. * map: new THREE.Texture( <Image> ),
  6276. *
  6277. * lightMap: new THREE.Texture( <Image> ),
  6278. * lightMapIntensity: <float>
  6279. *
  6280. * aoMap: new THREE.Texture( <Image> ),
  6281. * aoMapIntensity: <float>
  6282. *
  6283. * specularMap: new THREE.Texture( <Image> ),
  6284. *
  6285. * alphaMap: new THREE.Texture( <Image> ),
  6286. *
  6287. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6288. * combine: THREE.Multiply,
  6289. * reflectivity: <float>,
  6290. * refractionRatio: <float>,
  6291. *
  6292. * depthTest: <bool>,
  6293. * depthWrite: <bool>,
  6294. *
  6295. * wireframe: <boolean>,
  6296. * wireframeLinewidth: <float>,
  6297. *
  6298. * skinning: <bool>,
  6299. * morphTargets: <bool>
  6300. * }
  6301. */
  6302. function MeshBasicMaterial(parameters) {
  6303. Material.call(this);
  6304. this.type = 'MeshBasicMaterial';
  6305. this.color = new Color(0xffffff); // emissive
  6306. this.map = null;
  6307. this.lightMap = null;
  6308. this.lightMapIntensity = 1.0;
  6309. this.aoMap = null;
  6310. this.aoMapIntensity = 1.0;
  6311. this.specularMap = null;
  6312. this.alphaMap = null;
  6313. this.envMap = null;
  6314. this.combine = MultiplyOperation;
  6315. this.reflectivity = 1;
  6316. this.refractionRatio = 0.98;
  6317. this.wireframe = false;
  6318. this.wireframeLinewidth = 1;
  6319. this.wireframeLinecap = 'round';
  6320. this.wireframeLinejoin = 'round';
  6321. this.skinning = false;
  6322. this.morphTargets = false;
  6323. this.setValues(parameters);
  6324. }
  6325. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  6326. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6327. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6328. MeshBasicMaterial.prototype.copy = function (source) {
  6329. Material.prototype.copy.call(this, source);
  6330. this.color.copy(source.color);
  6331. this.map = source.map;
  6332. this.lightMap = source.lightMap;
  6333. this.lightMapIntensity = source.lightMapIntensity;
  6334. this.aoMap = source.aoMap;
  6335. this.aoMapIntensity = source.aoMapIntensity;
  6336. this.specularMap = source.specularMap;
  6337. this.alphaMap = source.alphaMap;
  6338. this.envMap = source.envMap;
  6339. this.combine = source.combine;
  6340. this.reflectivity = source.reflectivity;
  6341. this.refractionRatio = source.refractionRatio;
  6342. this.wireframe = source.wireframe;
  6343. this.wireframeLinewidth = source.wireframeLinewidth;
  6344. this.wireframeLinecap = source.wireframeLinecap;
  6345. this.wireframeLinejoin = source.wireframeLinejoin;
  6346. this.skinning = source.skinning;
  6347. this.morphTargets = source.morphTargets;
  6348. return this;
  6349. };
  6350. /**
  6351. * @author mrdoob / http://mrdoob.com/
  6352. */
  6353. var _vector$3 = new Vector3();
  6354. function BufferAttribute(array, itemSize, normalized) {
  6355. if (Array.isArray(array)) {
  6356. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  6357. }
  6358. this.name = '';
  6359. this.array = array;
  6360. this.itemSize = itemSize;
  6361. this.count = array !== undefined ? array.length / itemSize : 0;
  6362. this.normalized = normalized === true;
  6363. this.usage = StaticDrawUsage;
  6364. this.updateRange = {
  6365. offset: 0,
  6366. count: -1
  6367. };
  6368. this.version = 0;
  6369. }
  6370. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  6371. set: function (value) {
  6372. if (value === true) this.version++;
  6373. }
  6374. });
  6375. Object.assign(BufferAttribute.prototype, {
  6376. isBufferAttribute: true,
  6377. onUploadCallback: function () {},
  6378. setUsage: function (value) {
  6379. this.usage = value;
  6380. return this;
  6381. },
  6382. copy: function (source) {
  6383. this.name = source.name;
  6384. this.array = new source.array.constructor(source.array);
  6385. this.itemSize = source.itemSize;
  6386. this.count = source.count;
  6387. this.normalized = source.normalized;
  6388. this.usage = source.usage;
  6389. return this;
  6390. },
  6391. copyAt: function (index1, attribute, index2) {
  6392. index1 *= this.itemSize;
  6393. index2 *= attribute.itemSize;
  6394. for (var i = 0, l = this.itemSize; i < l; i++) {
  6395. this.array[index1 + i] = attribute.array[index2 + i];
  6396. }
  6397. return this;
  6398. },
  6399. copyArray: function (array) {
  6400. this.array.set(array);
  6401. return this;
  6402. },
  6403. copyColorsArray: function (colors) {
  6404. var array = this.array,
  6405. offset = 0;
  6406. for (var i = 0, l = colors.length; i < l; i++) {
  6407. var color = colors[i];
  6408. if (color === undefined) {
  6409. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  6410. color = new Color();
  6411. }
  6412. array[offset++] = color.r;
  6413. array[offset++] = color.g;
  6414. array[offset++] = color.b;
  6415. }
  6416. return this;
  6417. },
  6418. copyVector2sArray: function (vectors) {
  6419. var array = this.array,
  6420. offset = 0;
  6421. for (var i = 0, l = vectors.length; i < l; i++) {
  6422. var vector = vectors[i];
  6423. if (vector === undefined) {
  6424. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  6425. vector = new Vector2();
  6426. }
  6427. array[offset++] = vector.x;
  6428. array[offset++] = vector.y;
  6429. }
  6430. return this;
  6431. },
  6432. copyVector3sArray: function (vectors) {
  6433. var array = this.array,
  6434. offset = 0;
  6435. for (var i = 0, l = vectors.length; i < l; i++) {
  6436. var vector = vectors[i];
  6437. if (vector === undefined) {
  6438. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  6439. vector = new Vector3();
  6440. }
  6441. array[offset++] = vector.x;
  6442. array[offset++] = vector.y;
  6443. array[offset++] = vector.z;
  6444. }
  6445. return this;
  6446. },
  6447. copyVector4sArray: function (vectors) {
  6448. var array = this.array,
  6449. offset = 0;
  6450. for (var i = 0, l = vectors.length; i < l; i++) {
  6451. var vector = vectors[i];
  6452. if (vector === undefined) {
  6453. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  6454. vector = new Vector4();
  6455. }
  6456. array[offset++] = vector.x;
  6457. array[offset++] = vector.y;
  6458. array[offset++] = vector.z;
  6459. array[offset++] = vector.w;
  6460. }
  6461. return this;
  6462. },
  6463. applyMatrix3: function (m) {
  6464. for (var i = 0, l = this.count; i < l; i++) {
  6465. _vector$3.x = this.getX(i);
  6466. _vector$3.y = this.getY(i);
  6467. _vector$3.z = this.getZ(i);
  6468. _vector$3.applyMatrix3(m);
  6469. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6470. }
  6471. return this;
  6472. },
  6473. applyMatrix4: function (m) {
  6474. for (var i = 0, l = this.count; i < l; i++) {
  6475. _vector$3.x = this.getX(i);
  6476. _vector$3.y = this.getY(i);
  6477. _vector$3.z = this.getZ(i);
  6478. _vector$3.applyMatrix4(m);
  6479. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6480. }
  6481. return this;
  6482. },
  6483. applyNormalMatrix: function (m) {
  6484. for (var i = 0, l = this.count; i < l; i++) {
  6485. _vector$3.x = this.getX(i);
  6486. _vector$3.y = this.getY(i);
  6487. _vector$3.z = this.getZ(i);
  6488. _vector$3.applyNormalMatrix(m);
  6489. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6490. }
  6491. return this;
  6492. },
  6493. transformDirection: function (m) {
  6494. for (var i = 0, l = this.count; i < l; i++) {
  6495. _vector$3.x = this.getX(i);
  6496. _vector$3.y = this.getY(i);
  6497. _vector$3.z = this.getZ(i);
  6498. _vector$3.transformDirection(m);
  6499. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6500. }
  6501. return this;
  6502. },
  6503. set: function (value, offset) {
  6504. if (offset === undefined) offset = 0;
  6505. this.array.set(value, offset);
  6506. return this;
  6507. },
  6508. getX: function (index) {
  6509. return this.array[index * this.itemSize];
  6510. },
  6511. setX: function (index, x) {
  6512. this.array[index * this.itemSize] = x;
  6513. return this;
  6514. },
  6515. getY: function (index) {
  6516. return this.array[index * this.itemSize + 1];
  6517. },
  6518. setY: function (index, y) {
  6519. this.array[index * this.itemSize + 1] = y;
  6520. return this;
  6521. },
  6522. getZ: function (index) {
  6523. return this.array[index * this.itemSize + 2];
  6524. },
  6525. setZ: function (index, z) {
  6526. this.array[index * this.itemSize + 2] = z;
  6527. return this;
  6528. },
  6529. getW: function (index) {
  6530. return this.array[index * this.itemSize + 3];
  6531. },
  6532. setW: function (index, w) {
  6533. this.array[index * this.itemSize + 3] = w;
  6534. return this;
  6535. },
  6536. setXY: function (index, x, y) {
  6537. index *= this.itemSize;
  6538. this.array[index + 0] = x;
  6539. this.array[index + 1] = y;
  6540. return this;
  6541. },
  6542. setXYZ: function (index, x, y, z) {
  6543. index *= this.itemSize;
  6544. this.array[index + 0] = x;
  6545. this.array[index + 1] = y;
  6546. this.array[index + 2] = z;
  6547. return this;
  6548. },
  6549. setXYZW: function (index, x, y, z, w) {
  6550. index *= this.itemSize;
  6551. this.array[index + 0] = x;
  6552. this.array[index + 1] = y;
  6553. this.array[index + 2] = z;
  6554. this.array[index + 3] = w;
  6555. return this;
  6556. },
  6557. onUpload: function (callback) {
  6558. this.onUploadCallback = callback;
  6559. return this;
  6560. },
  6561. clone: function () {
  6562. return new this.constructor(this.array, this.itemSize).copy(this);
  6563. },
  6564. toJSON: function () {
  6565. return {
  6566. itemSize: this.itemSize,
  6567. type: this.array.constructor.name,
  6568. array: Array.prototype.slice.call(this.array),
  6569. normalized: this.normalized
  6570. };
  6571. }
  6572. }); //
  6573. function Int8BufferAttribute(array, itemSize, normalized) {
  6574. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  6575. }
  6576. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6577. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6578. function Uint8BufferAttribute(array, itemSize, normalized) {
  6579. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  6580. }
  6581. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6582. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6583. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  6584. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  6585. }
  6586. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6587. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6588. function Int16BufferAttribute(array, itemSize, normalized) {
  6589. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  6590. }
  6591. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6592. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6593. function Uint16BufferAttribute(array, itemSize, normalized) {
  6594. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6595. }
  6596. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6597. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6598. function Int32BufferAttribute(array, itemSize, normalized) {
  6599. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  6600. }
  6601. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6602. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6603. function Uint32BufferAttribute(array, itemSize, normalized) {
  6604. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  6605. }
  6606. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6607. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6608. function Float32BufferAttribute(array, itemSize, normalized) {
  6609. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  6610. }
  6611. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6612. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6613. function Float64BufferAttribute(array, itemSize, normalized) {
  6614. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  6615. }
  6616. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6617. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6618. /**
  6619. * @author mrdoob / http://mrdoob.com/
  6620. */
  6621. function DirectGeometry() {
  6622. this.vertices = [];
  6623. this.normals = [];
  6624. this.colors = [];
  6625. this.uvs = [];
  6626. this.uvs2 = [];
  6627. this.groups = [];
  6628. this.morphTargets = {};
  6629. this.skinWeights = [];
  6630. this.skinIndices = []; // this.lineDistances = [];
  6631. this.boundingBox = null;
  6632. this.boundingSphere = null; // update flags
  6633. this.verticesNeedUpdate = false;
  6634. this.normalsNeedUpdate = false;
  6635. this.colorsNeedUpdate = false;
  6636. this.uvsNeedUpdate = false;
  6637. this.groupsNeedUpdate = false;
  6638. }
  6639. Object.assign(DirectGeometry.prototype, {
  6640. computeGroups: function (geometry) {
  6641. var group;
  6642. var groups = [];
  6643. var materialIndex = undefined;
  6644. var faces = geometry.faces;
  6645. for (var i = 0; i < faces.length; i++) {
  6646. var face = faces[i]; // materials
  6647. if (face.materialIndex !== materialIndex) {
  6648. materialIndex = face.materialIndex;
  6649. if (group !== undefined) {
  6650. group.count = i * 3 - group.start;
  6651. groups.push(group);
  6652. }
  6653. group = {
  6654. start: i * 3,
  6655. materialIndex: materialIndex
  6656. };
  6657. }
  6658. }
  6659. if (group !== undefined) {
  6660. group.count = i * 3 - group.start;
  6661. groups.push(group);
  6662. }
  6663. this.groups = groups;
  6664. },
  6665. fromGeometry: function (geometry) {
  6666. var faces = geometry.faces;
  6667. var vertices = geometry.vertices;
  6668. var faceVertexUvs = geometry.faceVertexUvs;
  6669. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  6670. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  6671. var morphTargets = geometry.morphTargets;
  6672. var morphTargetsLength = morphTargets.length;
  6673. var morphTargetsPosition;
  6674. if (morphTargetsLength > 0) {
  6675. morphTargetsPosition = [];
  6676. for (var i = 0; i < morphTargetsLength; i++) {
  6677. morphTargetsPosition[i] = {
  6678. name: morphTargets[i].name,
  6679. data: []
  6680. };
  6681. }
  6682. this.morphTargets.position = morphTargetsPosition;
  6683. }
  6684. var morphNormals = geometry.morphNormals;
  6685. var morphNormalsLength = morphNormals.length;
  6686. var morphTargetsNormal;
  6687. if (morphNormalsLength > 0) {
  6688. morphTargetsNormal = [];
  6689. for (var i = 0; i < morphNormalsLength; i++) {
  6690. morphTargetsNormal[i] = {
  6691. name: morphNormals[i].name,
  6692. data: []
  6693. };
  6694. }
  6695. this.morphTargets.normal = morphTargetsNormal;
  6696. } // skins
  6697. var skinIndices = geometry.skinIndices;
  6698. var skinWeights = geometry.skinWeights;
  6699. var hasSkinIndices = skinIndices.length === vertices.length;
  6700. var hasSkinWeights = skinWeights.length === vertices.length; //
  6701. if (vertices.length > 0 && faces.length === 0) {
  6702. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  6703. }
  6704. for (var i = 0; i < faces.length; i++) {
  6705. var face = faces[i];
  6706. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  6707. var vertexNormals = face.vertexNormals;
  6708. if (vertexNormals.length === 3) {
  6709. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  6710. } else {
  6711. var normal = face.normal;
  6712. this.normals.push(normal, normal, normal);
  6713. }
  6714. var vertexColors = face.vertexColors;
  6715. if (vertexColors.length === 3) {
  6716. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  6717. } else {
  6718. var color = face.color;
  6719. this.colors.push(color, color, color);
  6720. }
  6721. if (hasFaceVertexUv === true) {
  6722. var vertexUvs = faceVertexUvs[0][i];
  6723. if (vertexUvs !== undefined) {
  6724. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6725. } else {
  6726. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  6727. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  6728. }
  6729. }
  6730. if (hasFaceVertexUv2 === true) {
  6731. var vertexUvs = faceVertexUvs[1][i];
  6732. if (vertexUvs !== undefined) {
  6733. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6734. } else {
  6735. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  6736. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  6737. }
  6738. } // morphs
  6739. for (var j = 0; j < morphTargetsLength; j++) {
  6740. var morphTarget = morphTargets[j].vertices;
  6741. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  6742. }
  6743. for (var j = 0; j < morphNormalsLength; j++) {
  6744. var morphNormal = morphNormals[j].vertexNormals[i];
  6745. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  6746. } // skins
  6747. if (hasSkinIndices) {
  6748. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  6749. }
  6750. if (hasSkinWeights) {
  6751. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  6752. }
  6753. }
  6754. this.computeGroups(geometry);
  6755. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6756. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6757. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6758. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6759. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6760. if (geometry.boundingSphere !== null) {
  6761. this.boundingSphere = geometry.boundingSphere.clone();
  6762. }
  6763. if (geometry.boundingBox !== null) {
  6764. this.boundingBox = geometry.boundingBox.clone();
  6765. }
  6766. return this;
  6767. }
  6768. });
  6769. /**
  6770. * @author mrdoob / http://mrdoob.com/
  6771. */
  6772. function arrayMax(array) {
  6773. if (array.length === 0) return -Infinity;
  6774. var max = array[0];
  6775. for (var i = 1, l = array.length; i < l; ++i) {
  6776. if (array[i] > max) max = array[i];
  6777. }
  6778. return max;
  6779. }
  6780. /**
  6781. * @author alteredq / http://alteredqualia.com/
  6782. * @author mrdoob / http://mrdoob.com/
  6783. */
  6784. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6785. var _m1$2 = new Matrix4();
  6786. var _obj = new Object3D();
  6787. var _offset = new Vector3();
  6788. var _box$2 = new Box3();
  6789. var _boxMorphTargets = new Box3();
  6790. var _vector$4 = new Vector3();
  6791. function BufferGeometry() {
  6792. Object.defineProperty(this, 'id', {
  6793. value: _bufferGeometryId += 2
  6794. });
  6795. this.uuid = MathUtils.generateUUID();
  6796. this.name = '';
  6797. this.type = 'BufferGeometry';
  6798. this.index = null;
  6799. this.attributes = {};
  6800. this.morphAttributes = {};
  6801. this.morphTargetsRelative = false;
  6802. this.groups = [];
  6803. this.boundingBox = null;
  6804. this.boundingSphere = null;
  6805. this.drawRange = {
  6806. start: 0,
  6807. count: Infinity
  6808. };
  6809. this.userData = {};
  6810. }
  6811. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6812. constructor: BufferGeometry,
  6813. isBufferGeometry: true,
  6814. getIndex: function () {
  6815. return this.index;
  6816. },
  6817. setIndex: function (index) {
  6818. if (Array.isArray(index)) {
  6819. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6820. } else {
  6821. this.index = index;
  6822. }
  6823. },
  6824. getAttribute: function (name) {
  6825. return this.attributes[name];
  6826. },
  6827. setAttribute: function (name, attribute) {
  6828. this.attributes[name] = attribute;
  6829. return this;
  6830. },
  6831. deleteAttribute: function (name) {
  6832. delete this.attributes[name];
  6833. return this;
  6834. },
  6835. addGroup: function (start, count, materialIndex) {
  6836. this.groups.push({
  6837. start: start,
  6838. count: count,
  6839. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6840. });
  6841. },
  6842. clearGroups: function () {
  6843. this.groups = [];
  6844. },
  6845. setDrawRange: function (start, count) {
  6846. this.drawRange.start = start;
  6847. this.drawRange.count = count;
  6848. },
  6849. applyMatrix4: function (matrix) {
  6850. var position = this.attributes.position;
  6851. if (position !== undefined) {
  6852. position.applyMatrix4(matrix);
  6853. position.needsUpdate = true;
  6854. }
  6855. var normal = this.attributes.normal;
  6856. if (normal !== undefined) {
  6857. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6858. normal.applyNormalMatrix(normalMatrix);
  6859. normal.needsUpdate = true;
  6860. }
  6861. var tangent = this.attributes.tangent;
  6862. if (tangent !== undefined) {
  6863. tangent.transformDirection(matrix);
  6864. tangent.needsUpdate = true;
  6865. }
  6866. if (this.boundingBox !== null) {
  6867. this.computeBoundingBox();
  6868. }
  6869. if (this.boundingSphere !== null) {
  6870. this.computeBoundingSphere();
  6871. }
  6872. return this;
  6873. },
  6874. rotateX: function (angle) {
  6875. // rotate geometry around world x-axis
  6876. _m1$2.makeRotationX(angle);
  6877. this.applyMatrix4(_m1$2);
  6878. return this;
  6879. },
  6880. rotateY: function (angle) {
  6881. // rotate geometry around world y-axis
  6882. _m1$2.makeRotationY(angle);
  6883. this.applyMatrix4(_m1$2);
  6884. return this;
  6885. },
  6886. rotateZ: function (angle) {
  6887. // rotate geometry around world z-axis
  6888. _m1$2.makeRotationZ(angle);
  6889. this.applyMatrix4(_m1$2);
  6890. return this;
  6891. },
  6892. translate: function (x, y, z) {
  6893. // translate geometry
  6894. _m1$2.makeTranslation(x, y, z);
  6895. this.applyMatrix4(_m1$2);
  6896. return this;
  6897. },
  6898. scale: function (x, y, z) {
  6899. // scale geometry
  6900. _m1$2.makeScale(x, y, z);
  6901. this.applyMatrix4(_m1$2);
  6902. return this;
  6903. },
  6904. lookAt: function (vector) {
  6905. _obj.lookAt(vector);
  6906. _obj.updateMatrix();
  6907. this.applyMatrix4(_obj.matrix);
  6908. return this;
  6909. },
  6910. center: function () {
  6911. this.computeBoundingBox();
  6912. this.boundingBox.getCenter(_offset).negate();
  6913. this.translate(_offset.x, _offset.y, _offset.z);
  6914. return this;
  6915. },
  6916. setFromObject: function (object) {
  6917. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6918. var geometry = object.geometry;
  6919. if (object.isPoints || object.isLine) {
  6920. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  6921. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  6922. this.setAttribute('position', positions.copyVector3sArray(geometry.vertices));
  6923. this.setAttribute('color', colors.copyColorsArray(geometry.colors));
  6924. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  6925. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  6926. this.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  6927. }
  6928. if (geometry.boundingSphere !== null) {
  6929. this.boundingSphere = geometry.boundingSphere.clone();
  6930. }
  6931. if (geometry.boundingBox !== null) {
  6932. this.boundingBox = geometry.boundingBox.clone();
  6933. }
  6934. } else if (object.isMesh) {
  6935. if (geometry && geometry.isGeometry) {
  6936. this.fromGeometry(geometry);
  6937. }
  6938. }
  6939. return this;
  6940. },
  6941. setFromPoints: function (points) {
  6942. var position = [];
  6943. for (var i = 0, l = points.length; i < l; i++) {
  6944. var point = points[i];
  6945. position.push(point.x, point.y, point.z || 0);
  6946. }
  6947. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6948. return this;
  6949. },
  6950. updateFromObject: function (object) {
  6951. var geometry = object.geometry;
  6952. if (object.isMesh) {
  6953. var direct = geometry.__directGeometry;
  6954. if (geometry.elementsNeedUpdate === true) {
  6955. direct = undefined;
  6956. geometry.elementsNeedUpdate = false;
  6957. }
  6958. if (direct === undefined) {
  6959. return this.fromGeometry(geometry);
  6960. }
  6961. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6962. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6963. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6964. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6965. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6966. geometry.verticesNeedUpdate = false;
  6967. geometry.normalsNeedUpdate = false;
  6968. geometry.colorsNeedUpdate = false;
  6969. geometry.uvsNeedUpdate = false;
  6970. geometry.groupsNeedUpdate = false;
  6971. geometry = direct;
  6972. }
  6973. var attribute;
  6974. if (geometry.verticesNeedUpdate === true) {
  6975. attribute = this.attributes.position;
  6976. if (attribute !== undefined) {
  6977. attribute.copyVector3sArray(geometry.vertices);
  6978. attribute.needsUpdate = true;
  6979. }
  6980. geometry.verticesNeedUpdate = false;
  6981. }
  6982. if (geometry.normalsNeedUpdate === true) {
  6983. attribute = this.attributes.normal;
  6984. if (attribute !== undefined) {
  6985. attribute.copyVector3sArray(geometry.normals);
  6986. attribute.needsUpdate = true;
  6987. }
  6988. geometry.normalsNeedUpdate = false;
  6989. }
  6990. if (geometry.colorsNeedUpdate === true) {
  6991. attribute = this.attributes.color;
  6992. if (attribute !== undefined) {
  6993. attribute.copyColorsArray(geometry.colors);
  6994. attribute.needsUpdate = true;
  6995. }
  6996. geometry.colorsNeedUpdate = false;
  6997. }
  6998. if (geometry.uvsNeedUpdate) {
  6999. attribute = this.attributes.uv;
  7000. if (attribute !== undefined) {
  7001. attribute.copyVector2sArray(geometry.uvs);
  7002. attribute.needsUpdate = true;
  7003. }
  7004. geometry.uvsNeedUpdate = false;
  7005. }
  7006. if (geometry.lineDistancesNeedUpdate) {
  7007. attribute = this.attributes.lineDistance;
  7008. if (attribute !== undefined) {
  7009. attribute.copyArray(geometry.lineDistances);
  7010. attribute.needsUpdate = true;
  7011. }
  7012. geometry.lineDistancesNeedUpdate = false;
  7013. }
  7014. if (geometry.groupsNeedUpdate) {
  7015. geometry.computeGroups(object.geometry);
  7016. this.groups = geometry.groups;
  7017. geometry.groupsNeedUpdate = false;
  7018. }
  7019. return this;
  7020. },
  7021. fromGeometry: function (geometry) {
  7022. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  7023. return this.fromDirectGeometry(geometry.__directGeometry);
  7024. },
  7025. fromDirectGeometry: function (geometry) {
  7026. var positions = new Float32Array(geometry.vertices.length * 3);
  7027. this.setAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  7028. if (geometry.normals.length > 0) {
  7029. var normals = new Float32Array(geometry.normals.length * 3);
  7030. this.setAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  7031. }
  7032. if (geometry.colors.length > 0) {
  7033. var colors = new Float32Array(geometry.colors.length * 3);
  7034. this.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  7035. }
  7036. if (geometry.uvs.length > 0) {
  7037. var uvs = new Float32Array(geometry.uvs.length * 2);
  7038. this.setAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  7039. }
  7040. if (geometry.uvs2.length > 0) {
  7041. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  7042. this.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7043. } // groups
  7044. this.groups = geometry.groups; // morphs
  7045. for (var name in geometry.morphTargets) {
  7046. var array = [];
  7047. var morphTargets = geometry.morphTargets[name];
  7048. for (var i = 0, l = morphTargets.length; i < l; i++) {
  7049. var morphTarget = morphTargets[i];
  7050. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7051. attribute.name = morphTarget.name;
  7052. array.push(attribute.copyVector3sArray(morphTarget.data));
  7053. }
  7054. this.morphAttributes[name] = array;
  7055. } // skinning
  7056. if (geometry.skinIndices.length > 0) {
  7057. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7058. this.setAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7059. }
  7060. if (geometry.skinWeights.length > 0) {
  7061. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7062. this.setAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7063. } //
  7064. if (geometry.boundingSphere !== null) {
  7065. this.boundingSphere = geometry.boundingSphere.clone();
  7066. }
  7067. if (geometry.boundingBox !== null) {
  7068. this.boundingBox = geometry.boundingBox.clone();
  7069. }
  7070. return this;
  7071. },
  7072. computeBoundingBox: function () {
  7073. if (this.boundingBox === null) {
  7074. this.boundingBox = new Box3();
  7075. }
  7076. var position = this.attributes.position;
  7077. var morphAttributesPosition = this.morphAttributes.position;
  7078. if (position !== undefined) {
  7079. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7080. if (morphAttributesPosition) {
  7081. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7082. var morphAttribute = morphAttributesPosition[i];
  7083. _box$2.setFromBufferAttribute(morphAttribute);
  7084. if (this.morphTargetsRelative) {
  7085. _vector$4.addVectors(this.boundingBox.min, _box$2.min);
  7086. this.boundingBox.expandByPoint(_vector$4);
  7087. _vector$4.addVectors(this.boundingBox.max, _box$2.max);
  7088. this.boundingBox.expandByPoint(_vector$4);
  7089. } else {
  7090. this.boundingBox.expandByPoint(_box$2.min);
  7091. this.boundingBox.expandByPoint(_box$2.max);
  7092. }
  7093. }
  7094. }
  7095. } else {
  7096. this.boundingBox.makeEmpty();
  7097. }
  7098. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7099. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7100. }
  7101. },
  7102. computeBoundingSphere: function () {
  7103. if (this.boundingSphere === null) {
  7104. this.boundingSphere = new Sphere();
  7105. }
  7106. var position = this.attributes.position;
  7107. var morphAttributesPosition = this.morphAttributes.position;
  7108. if (position) {
  7109. // first, find the center of the bounding sphere
  7110. var center = this.boundingSphere.center;
  7111. _box$2.setFromBufferAttribute(position); // process morph attributes if present
  7112. if (morphAttributesPosition) {
  7113. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7114. var morphAttribute = morphAttributesPosition[i];
  7115. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7116. if (this.morphTargetsRelative) {
  7117. _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
  7118. _box$2.expandByPoint(_vector$4);
  7119. _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
  7120. _box$2.expandByPoint(_vector$4);
  7121. } else {
  7122. _box$2.expandByPoint(_boxMorphTargets.min);
  7123. _box$2.expandByPoint(_boxMorphTargets.max);
  7124. }
  7125. }
  7126. }
  7127. _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7128. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7129. var maxRadiusSq = 0;
  7130. for (var i = 0, il = position.count; i < il; i++) {
  7131. _vector$4.fromBufferAttribute(position, i);
  7132. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7133. } // process morph attributes if present
  7134. if (morphAttributesPosition) {
  7135. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7136. var morphAttribute = morphAttributesPosition[i];
  7137. var morphTargetsRelative = this.morphTargetsRelative;
  7138. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  7139. _vector$4.fromBufferAttribute(morphAttribute, j);
  7140. if (morphTargetsRelative) {
  7141. _offset.fromBufferAttribute(position, j);
  7142. _vector$4.add(_offset);
  7143. }
  7144. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7145. }
  7146. }
  7147. }
  7148. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7149. if (isNaN(this.boundingSphere.radius)) {
  7150. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7151. }
  7152. }
  7153. },
  7154. computeFaceNormals: function () {// backwards compatibility
  7155. },
  7156. computeVertexNormals: function () {
  7157. var index = this.index;
  7158. var attributes = this.attributes;
  7159. if (attributes.position) {
  7160. var positions = attributes.position.array;
  7161. if (attributes.normal === undefined) {
  7162. this.setAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  7163. } else {
  7164. // reset existing normals to zero
  7165. var array = attributes.normal.array;
  7166. for (var i = 0, il = array.length; i < il; i++) {
  7167. array[i] = 0;
  7168. }
  7169. }
  7170. var normals = attributes.normal.array;
  7171. var vA, vB, vC;
  7172. var pA = new Vector3(),
  7173. pB = new Vector3(),
  7174. pC = new Vector3();
  7175. var cb = new Vector3(),
  7176. ab = new Vector3(); // indexed elements
  7177. if (index) {
  7178. var indices = index.array;
  7179. for (var i = 0, il = index.count; i < il; i += 3) {
  7180. vA = indices[i + 0] * 3;
  7181. vB = indices[i + 1] * 3;
  7182. vC = indices[i + 2] * 3;
  7183. pA.fromArray(positions, vA);
  7184. pB.fromArray(positions, vB);
  7185. pC.fromArray(positions, vC);
  7186. cb.subVectors(pC, pB);
  7187. ab.subVectors(pA, pB);
  7188. cb.cross(ab);
  7189. normals[vA] += cb.x;
  7190. normals[vA + 1] += cb.y;
  7191. normals[vA + 2] += cb.z;
  7192. normals[vB] += cb.x;
  7193. normals[vB + 1] += cb.y;
  7194. normals[vB + 2] += cb.z;
  7195. normals[vC] += cb.x;
  7196. normals[vC + 1] += cb.y;
  7197. normals[vC + 2] += cb.z;
  7198. }
  7199. } else {
  7200. // non-indexed elements (unconnected triangle soup)
  7201. for (var i = 0, il = positions.length; i < il; i += 9) {
  7202. pA.fromArray(positions, i);
  7203. pB.fromArray(positions, i + 3);
  7204. pC.fromArray(positions, i + 6);
  7205. cb.subVectors(pC, pB);
  7206. ab.subVectors(pA, pB);
  7207. cb.cross(ab);
  7208. normals[i] = cb.x;
  7209. normals[i + 1] = cb.y;
  7210. normals[i + 2] = cb.z;
  7211. normals[i + 3] = cb.x;
  7212. normals[i + 4] = cb.y;
  7213. normals[i + 5] = cb.z;
  7214. normals[i + 6] = cb.x;
  7215. normals[i + 7] = cb.y;
  7216. normals[i + 8] = cb.z;
  7217. }
  7218. }
  7219. this.normalizeNormals();
  7220. attributes.normal.needsUpdate = true;
  7221. }
  7222. },
  7223. merge: function (geometry, offset) {
  7224. if (!(geometry && geometry.isBufferGeometry)) {
  7225. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  7226. return;
  7227. }
  7228. if (offset === undefined) {
  7229. offset = 0;
  7230. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  7231. }
  7232. var attributes = this.attributes;
  7233. for (var key in attributes) {
  7234. if (geometry.attributes[key] === undefined) continue;
  7235. var attribute1 = attributes[key];
  7236. var attributeArray1 = attribute1.array;
  7237. var attribute2 = geometry.attributes[key];
  7238. var attributeArray2 = attribute2.array;
  7239. var attributeOffset = attribute2.itemSize * offset;
  7240. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  7241. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  7242. attributeArray1[j] = attributeArray2[i];
  7243. }
  7244. }
  7245. return this;
  7246. },
  7247. normalizeNormals: function () {
  7248. var normals = this.attributes.normal;
  7249. for (var i = 0, il = normals.count; i < il; i++) {
  7250. _vector$4.x = normals.getX(i);
  7251. _vector$4.y = normals.getY(i);
  7252. _vector$4.z = normals.getZ(i);
  7253. _vector$4.normalize();
  7254. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  7255. }
  7256. },
  7257. toNonIndexed: function () {
  7258. function convertBufferAttribute(attribute, indices) {
  7259. var array = attribute.array;
  7260. var itemSize = attribute.itemSize;
  7261. var array2 = new array.constructor(indices.length * itemSize);
  7262. var index = 0,
  7263. index2 = 0;
  7264. for (var i = 0, l = indices.length; i < l; i++) {
  7265. index = indices[i] * itemSize;
  7266. for (var j = 0; j < itemSize; j++) {
  7267. array2[index2++] = array[index++];
  7268. }
  7269. }
  7270. return new BufferAttribute(array2, itemSize);
  7271. } //
  7272. if (this.index === null) {
  7273. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  7274. return this;
  7275. }
  7276. var geometry2 = new BufferGeometry();
  7277. var indices = this.index.array;
  7278. var attributes = this.attributes; // attributes
  7279. for (var name in attributes) {
  7280. var attribute = attributes[name];
  7281. var newAttribute = convertBufferAttribute(attribute, indices);
  7282. geometry2.setAttribute(name, newAttribute);
  7283. } // morph attributes
  7284. var morphAttributes = this.morphAttributes;
  7285. for (name in morphAttributes) {
  7286. var morphArray = [];
  7287. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7288. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  7289. var attribute = morphAttribute[i];
  7290. var newAttribute = convertBufferAttribute(attribute, indices);
  7291. morphArray.push(newAttribute);
  7292. }
  7293. geometry2.morphAttributes[name] = morphArray;
  7294. }
  7295. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  7296. var groups = this.groups;
  7297. for (var i = 0, l = groups.length; i < l; i++) {
  7298. var group = groups[i];
  7299. geometry2.addGroup(group.start, group.count, group.materialIndex);
  7300. }
  7301. return geometry2;
  7302. },
  7303. toJSON: function () {
  7304. var data = {
  7305. metadata: {
  7306. version: 4.5,
  7307. type: 'BufferGeometry',
  7308. generator: 'BufferGeometry.toJSON'
  7309. }
  7310. }; // standard BufferGeometry serialization
  7311. data.uuid = this.uuid;
  7312. data.type = this.type;
  7313. if (this.name !== '') data.name = this.name;
  7314. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  7315. if (this.parameters !== undefined) {
  7316. var parameters = this.parameters;
  7317. for (var key in parameters) {
  7318. if (parameters[key] !== undefined) data[key] = parameters[key];
  7319. }
  7320. return data;
  7321. }
  7322. data.data = {
  7323. attributes: {}
  7324. };
  7325. var index = this.index;
  7326. if (index !== null) {
  7327. data.data.index = {
  7328. type: index.array.constructor.name,
  7329. array: Array.prototype.slice.call(index.array)
  7330. };
  7331. }
  7332. var attributes = this.attributes;
  7333. for (var key in attributes) {
  7334. var attribute = attributes[key];
  7335. var attributeData = attribute.toJSON();
  7336. if (attribute.name !== '') attributeData.name = attribute.name;
  7337. data.data.attributes[key] = attributeData;
  7338. }
  7339. var morphAttributes = {};
  7340. var hasMorphAttributes = false;
  7341. for (var key in this.morphAttributes) {
  7342. var attributeArray = this.morphAttributes[key];
  7343. var array = [];
  7344. for (var i = 0, il = attributeArray.length; i < il; i++) {
  7345. var attribute = attributeArray[i];
  7346. var attributeData = attribute.toJSON();
  7347. if (attribute.name !== '') attributeData.name = attribute.name;
  7348. array.push(attributeData);
  7349. }
  7350. if (array.length > 0) {
  7351. morphAttributes[key] = array;
  7352. hasMorphAttributes = true;
  7353. }
  7354. }
  7355. if (hasMorphAttributes) {
  7356. data.data.morphAttributes = morphAttributes;
  7357. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7358. }
  7359. var groups = this.groups;
  7360. if (groups.length > 0) {
  7361. data.data.groups = JSON.parse(JSON.stringify(groups));
  7362. }
  7363. var boundingSphere = this.boundingSphere;
  7364. if (boundingSphere !== null) {
  7365. data.data.boundingSphere = {
  7366. center: boundingSphere.center.toArray(),
  7367. radius: boundingSphere.radius
  7368. };
  7369. }
  7370. return data;
  7371. },
  7372. clone: function () {
  7373. /*
  7374. // Handle primitives
  7375. var parameters = this.parameters;
  7376. if ( parameters !== undefined ) {
  7377. var values = [];
  7378. for ( var key in parameters ) {
  7379. values.push( parameters[ key ] );
  7380. }
  7381. var geometry = Object.create( this.constructor.prototype );
  7382. this.constructor.apply( geometry, values );
  7383. return geometry;
  7384. }
  7385. return new this.constructor().copy( this );
  7386. */
  7387. return new BufferGeometry().copy(this);
  7388. },
  7389. copy: function (source) {
  7390. var name, i, l; // reset
  7391. this.index = null;
  7392. this.attributes = {};
  7393. this.morphAttributes = {};
  7394. this.groups = [];
  7395. this.boundingBox = null;
  7396. this.boundingSphere = null; // name
  7397. this.name = source.name; // index
  7398. var index = source.index;
  7399. if (index !== null) {
  7400. this.setIndex(index.clone());
  7401. } // attributes
  7402. var attributes = source.attributes;
  7403. for (name in attributes) {
  7404. var attribute = attributes[name];
  7405. this.setAttribute(name, attribute.clone());
  7406. } // morph attributes
  7407. var morphAttributes = source.morphAttributes;
  7408. for (name in morphAttributes) {
  7409. var array = [];
  7410. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7411. for (i = 0, l = morphAttribute.length; i < l; i++) {
  7412. array.push(morphAttribute[i].clone());
  7413. }
  7414. this.morphAttributes[name] = array;
  7415. }
  7416. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  7417. var groups = source.groups;
  7418. for (i = 0, l = groups.length; i < l; i++) {
  7419. var group = groups[i];
  7420. this.addGroup(group.start, group.count, group.materialIndex);
  7421. } // bounding box
  7422. var boundingBox = source.boundingBox;
  7423. if (boundingBox !== null) {
  7424. this.boundingBox = boundingBox.clone();
  7425. } // bounding sphere
  7426. var boundingSphere = source.boundingSphere;
  7427. if (boundingSphere !== null) {
  7428. this.boundingSphere = boundingSphere.clone();
  7429. } // draw range
  7430. this.drawRange.start = source.drawRange.start;
  7431. this.drawRange.count = source.drawRange.count; // user data
  7432. this.userData = source.userData;
  7433. return this;
  7434. },
  7435. dispose: function () {
  7436. this.dispatchEvent({
  7437. type: 'dispose'
  7438. });
  7439. }
  7440. });
  7441. /**
  7442. * @author mrdoob / http://mrdoob.com/
  7443. * @author alteredq / http://alteredqualia.com/
  7444. * @author mikael emtinger / http://gomo.se/
  7445. * @author jonobr1 / http://jonobr1.com/
  7446. */
  7447. var _inverseMatrix = new Matrix4();
  7448. var _ray = new Ray();
  7449. var _sphere = new Sphere();
  7450. var _vA = new Vector3();
  7451. var _vB = new Vector3();
  7452. var _vC = new Vector3();
  7453. var _tempA = new Vector3();
  7454. var _tempB = new Vector3();
  7455. var _tempC = new Vector3();
  7456. var _morphA = new Vector3();
  7457. var _morphB = new Vector3();
  7458. var _morphC = new Vector3();
  7459. var _uvA = new Vector2();
  7460. var _uvB = new Vector2();
  7461. var _uvC = new Vector2();
  7462. var _intersectionPoint = new Vector3();
  7463. var _intersectionPointWorld = new Vector3();
  7464. function Mesh(geometry, material) {
  7465. Object3D.call(this);
  7466. this.type = 'Mesh';
  7467. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  7468. this.material = material !== undefined ? material : new MeshBasicMaterial();
  7469. this.updateMorphTargets();
  7470. }
  7471. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  7472. constructor: Mesh,
  7473. isMesh: true,
  7474. copy: function (source) {
  7475. Object3D.prototype.copy.call(this, source);
  7476. if (source.morphTargetInfluences !== undefined) {
  7477. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7478. }
  7479. if (source.morphTargetDictionary !== undefined) {
  7480. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  7481. }
  7482. return this;
  7483. },
  7484. updateMorphTargets: function () {
  7485. var geometry = this.geometry;
  7486. var m, ml, name;
  7487. if (geometry.isBufferGeometry) {
  7488. var morphAttributes = geometry.morphAttributes;
  7489. var keys = Object.keys(morphAttributes);
  7490. if (keys.length > 0) {
  7491. var morphAttribute = morphAttributes[keys[0]];
  7492. if (morphAttribute !== undefined) {
  7493. this.morphTargetInfluences = [];
  7494. this.morphTargetDictionary = {};
  7495. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  7496. name = morphAttribute[m].name || String(m);
  7497. this.morphTargetInfluences.push(0);
  7498. this.morphTargetDictionary[name] = m;
  7499. }
  7500. }
  7501. }
  7502. } else {
  7503. var morphTargets = geometry.morphTargets;
  7504. if (morphTargets !== undefined && morphTargets.length > 0) {
  7505. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  7506. }
  7507. }
  7508. },
  7509. raycast: function (raycaster, intersects) {
  7510. var geometry = this.geometry;
  7511. var material = this.material;
  7512. var matrixWorld = this.matrixWorld;
  7513. if (material === undefined) return; // Checking boundingSphere distance to ray
  7514. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7515. _sphere.copy(geometry.boundingSphere);
  7516. _sphere.applyMatrix4(matrixWorld);
  7517. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  7518. _inverseMatrix.getInverse(matrixWorld);
  7519. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  7520. if (geometry.boundingBox !== null) {
  7521. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  7522. }
  7523. var intersection;
  7524. if (geometry.isBufferGeometry) {
  7525. var a, b, c;
  7526. var index = geometry.index;
  7527. var position = geometry.attributes.position;
  7528. var morphPosition = geometry.morphAttributes.position;
  7529. var morphTargetsRelative = geometry.morphTargetsRelative;
  7530. var uv = geometry.attributes.uv;
  7531. var uv2 = geometry.attributes.uv2;
  7532. var groups = geometry.groups;
  7533. var drawRange = geometry.drawRange;
  7534. var i, j, il, jl;
  7535. var group, groupMaterial;
  7536. var start, end;
  7537. if (index !== null) {
  7538. // indexed buffer geometry
  7539. if (Array.isArray(material)) {
  7540. for (i = 0, il = groups.length; i < il; i++) {
  7541. group = groups[i];
  7542. groupMaterial = material[group.materialIndex];
  7543. start = Math.max(group.start, drawRange.start);
  7544. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7545. for (j = start, jl = end; j < jl; j += 3) {
  7546. a = index.getX(j);
  7547. b = index.getX(j + 1);
  7548. c = index.getX(j + 2);
  7549. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7550. if (intersection) {
  7551. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  7552. intersection.face.materialIndex = group.materialIndex;
  7553. intersects.push(intersection);
  7554. }
  7555. }
  7556. }
  7557. } else {
  7558. start = Math.max(0, drawRange.start);
  7559. end = Math.min(index.count, drawRange.start + drawRange.count);
  7560. for (i = start, il = end; i < il; i += 3) {
  7561. a = index.getX(i);
  7562. b = index.getX(i + 1);
  7563. c = index.getX(i + 2);
  7564. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7565. if (intersection) {
  7566. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  7567. intersects.push(intersection);
  7568. }
  7569. }
  7570. }
  7571. } else if (position !== undefined) {
  7572. // non-indexed buffer geometry
  7573. if (Array.isArray(material)) {
  7574. for (i = 0, il = groups.length; i < il; i++) {
  7575. group = groups[i];
  7576. groupMaterial = material[group.materialIndex];
  7577. start = Math.max(group.start, drawRange.start);
  7578. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7579. for (j = start, jl = end; j < jl; j += 3) {
  7580. a = j;
  7581. b = j + 1;
  7582. c = j + 2;
  7583. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7584. if (intersection) {
  7585. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  7586. intersection.face.materialIndex = group.materialIndex;
  7587. intersects.push(intersection);
  7588. }
  7589. }
  7590. }
  7591. } else {
  7592. start = Math.max(0, drawRange.start);
  7593. end = Math.min(position.count, drawRange.start + drawRange.count);
  7594. for (i = start, il = end; i < il; i += 3) {
  7595. a = i;
  7596. b = i + 1;
  7597. c = i + 2;
  7598. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7599. if (intersection) {
  7600. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  7601. intersects.push(intersection);
  7602. }
  7603. }
  7604. }
  7605. }
  7606. } else if (geometry.isGeometry) {
  7607. var fvA, fvB, fvC;
  7608. var isMultiMaterial = Array.isArray(material);
  7609. var vertices = geometry.vertices;
  7610. var faces = geometry.faces;
  7611. var uvs;
  7612. var faceVertexUvs = geometry.faceVertexUvs[0];
  7613. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  7614. for (var f = 0, fl = faces.length; f < fl; f++) {
  7615. var face = faces[f];
  7616. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  7617. if (faceMaterial === undefined) continue;
  7618. fvA = vertices[face.a];
  7619. fvB = vertices[face.b];
  7620. fvC = vertices[face.c];
  7621. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  7622. if (intersection) {
  7623. if (uvs && uvs[f]) {
  7624. var uvs_f = uvs[f];
  7625. _uvA.copy(uvs_f[0]);
  7626. _uvB.copy(uvs_f[1]);
  7627. _uvC.copy(uvs_f[2]);
  7628. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  7629. }
  7630. intersection.face = face;
  7631. intersection.faceIndex = f;
  7632. intersects.push(intersection);
  7633. }
  7634. }
  7635. }
  7636. },
  7637. clone: function () {
  7638. return new this.constructor(this.geometry, this.material).copy(this);
  7639. }
  7640. });
  7641. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  7642. var intersect;
  7643. if (material.side === BackSide) {
  7644. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  7645. } else {
  7646. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  7647. }
  7648. if (intersect === null) return null;
  7649. _intersectionPointWorld.copy(point);
  7650. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  7651. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  7652. if (distance < raycaster.near || distance > raycaster.far) return null;
  7653. return {
  7654. distance: distance,
  7655. point: _intersectionPointWorld.clone(),
  7656. object: object
  7657. };
  7658. }
  7659. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  7660. _vA.fromBufferAttribute(position, a);
  7661. _vB.fromBufferAttribute(position, b);
  7662. _vC.fromBufferAttribute(position, c);
  7663. var morphInfluences = object.morphTargetInfluences;
  7664. if (material.morphTargets && morphPosition && morphInfluences) {
  7665. _morphA.set(0, 0, 0);
  7666. _morphB.set(0, 0, 0);
  7667. _morphC.set(0, 0, 0);
  7668. for (var i = 0, il = morphPosition.length; i < il; i++) {
  7669. var influence = morphInfluences[i];
  7670. var morphAttribute = morphPosition[i];
  7671. if (influence === 0) continue;
  7672. _tempA.fromBufferAttribute(morphAttribute, a);
  7673. _tempB.fromBufferAttribute(morphAttribute, b);
  7674. _tempC.fromBufferAttribute(morphAttribute, c);
  7675. if (morphTargetsRelative) {
  7676. _morphA.addScaledVector(_tempA, influence);
  7677. _morphB.addScaledVector(_tempB, influence);
  7678. _morphC.addScaledVector(_tempC, influence);
  7679. } else {
  7680. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  7681. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  7682. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  7683. }
  7684. }
  7685. _vA.add(_morphA);
  7686. _vB.add(_morphB);
  7687. _vC.add(_morphC);
  7688. }
  7689. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  7690. if (intersection) {
  7691. if (uv) {
  7692. _uvA.fromBufferAttribute(uv, a);
  7693. _uvB.fromBufferAttribute(uv, b);
  7694. _uvC.fromBufferAttribute(uv, c);
  7695. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7696. }
  7697. if (uv2) {
  7698. _uvA.fromBufferAttribute(uv2, a);
  7699. _uvB.fromBufferAttribute(uv2, b);
  7700. _uvC.fromBufferAttribute(uv2, c);
  7701. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7702. }
  7703. var face = new Face3(a, b, c);
  7704. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  7705. intersection.face = face;
  7706. }
  7707. return intersection;
  7708. }
  7709. /**
  7710. * @author mrdoob / http://mrdoob.com/
  7711. * @author kile / http://kile.stravaganza.org/
  7712. * @author alteredq / http://alteredqualia.com/
  7713. * @author mikael emtinger / http://gomo.se/
  7714. * @author zz85 / http://www.lab4games.net/zz85/blog
  7715. * @author bhouston / http://clara.io
  7716. */
  7717. var _geometryId = 0; // Geometry uses even numbers as Id
  7718. var _m1$3 = new Matrix4();
  7719. var _obj$1 = new Object3D();
  7720. var _offset$1 = new Vector3();
  7721. function Geometry() {
  7722. Object.defineProperty(this, 'id', {
  7723. value: _geometryId += 2
  7724. });
  7725. this.uuid = MathUtils.generateUUID();
  7726. this.name = '';
  7727. this.type = 'Geometry';
  7728. this.vertices = [];
  7729. this.colors = [];
  7730. this.faces = [];
  7731. this.faceVertexUvs = [[]];
  7732. this.morphTargets = [];
  7733. this.morphNormals = [];
  7734. this.skinWeights = [];
  7735. this.skinIndices = [];
  7736. this.lineDistances = [];
  7737. this.boundingBox = null;
  7738. this.boundingSphere = null; // update flags
  7739. this.elementsNeedUpdate = false;
  7740. this.verticesNeedUpdate = false;
  7741. this.uvsNeedUpdate = false;
  7742. this.normalsNeedUpdate = false;
  7743. this.colorsNeedUpdate = false;
  7744. this.lineDistancesNeedUpdate = false;
  7745. this.groupsNeedUpdate = false;
  7746. }
  7747. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7748. constructor: Geometry,
  7749. isGeometry: true,
  7750. applyMatrix4: function (matrix) {
  7751. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7752. for (var i = 0, il = this.vertices.length; i < il; i++) {
  7753. var vertex = this.vertices[i];
  7754. vertex.applyMatrix4(matrix);
  7755. }
  7756. for (var i = 0, il = this.faces.length; i < il; i++) {
  7757. var face = this.faces[i];
  7758. face.normal.applyMatrix3(normalMatrix).normalize();
  7759. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  7760. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  7761. }
  7762. }
  7763. if (this.boundingBox !== null) {
  7764. this.computeBoundingBox();
  7765. }
  7766. if (this.boundingSphere !== null) {
  7767. this.computeBoundingSphere();
  7768. }
  7769. this.verticesNeedUpdate = true;
  7770. this.normalsNeedUpdate = true;
  7771. return this;
  7772. },
  7773. rotateX: function (angle) {
  7774. // rotate geometry around world x-axis
  7775. _m1$3.makeRotationX(angle);
  7776. this.applyMatrix4(_m1$3);
  7777. return this;
  7778. },
  7779. rotateY: function (angle) {
  7780. // rotate geometry around world y-axis
  7781. _m1$3.makeRotationY(angle);
  7782. this.applyMatrix4(_m1$3);
  7783. return this;
  7784. },
  7785. rotateZ: function (angle) {
  7786. // rotate geometry around world z-axis
  7787. _m1$3.makeRotationZ(angle);
  7788. this.applyMatrix4(_m1$3);
  7789. return this;
  7790. },
  7791. translate: function (x, y, z) {
  7792. // translate geometry
  7793. _m1$3.makeTranslation(x, y, z);
  7794. this.applyMatrix4(_m1$3);
  7795. return this;
  7796. },
  7797. scale: function (x, y, z) {
  7798. // scale geometry
  7799. _m1$3.makeScale(x, y, z);
  7800. this.applyMatrix4(_m1$3);
  7801. return this;
  7802. },
  7803. lookAt: function (vector) {
  7804. _obj$1.lookAt(vector);
  7805. _obj$1.updateMatrix();
  7806. this.applyMatrix4(_obj$1.matrix);
  7807. return this;
  7808. },
  7809. fromBufferGeometry: function (geometry) {
  7810. var scope = this;
  7811. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7812. var attributes = geometry.attributes;
  7813. if (attributes.position === undefined) {
  7814. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  7815. return this;
  7816. }
  7817. var positions = attributes.position.array;
  7818. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7819. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7820. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7821. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7822. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  7823. for (var i = 0; i < positions.length; i += 3) {
  7824. scope.vertices.push(new Vector3().fromArray(positions, i));
  7825. if (colors !== undefined) {
  7826. scope.colors.push(new Color().fromArray(colors, i));
  7827. }
  7828. }
  7829. function addFace(a, b, c, materialIndex) {
  7830. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  7831. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  7832. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  7833. scope.faces.push(face);
  7834. if (uvs !== undefined) {
  7835. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  7836. }
  7837. if (uvs2 !== undefined) {
  7838. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  7839. }
  7840. }
  7841. var groups = geometry.groups;
  7842. if (groups.length > 0) {
  7843. for (var i = 0; i < groups.length; i++) {
  7844. var group = groups[i];
  7845. var start = group.start;
  7846. var count = group.count;
  7847. for (var j = start, jl = start + count; j < jl; j += 3) {
  7848. if (indices !== undefined) {
  7849. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  7850. } else {
  7851. addFace(j, j + 1, j + 2, group.materialIndex);
  7852. }
  7853. }
  7854. }
  7855. } else {
  7856. if (indices !== undefined) {
  7857. for (var i = 0; i < indices.length; i += 3) {
  7858. addFace(indices[i], indices[i + 1], indices[i + 2]);
  7859. }
  7860. } else {
  7861. for (var i = 0; i < positions.length / 3; i += 3) {
  7862. addFace(i, i + 1, i + 2);
  7863. }
  7864. }
  7865. }
  7866. this.computeFaceNormals();
  7867. if (geometry.boundingBox !== null) {
  7868. this.boundingBox = geometry.boundingBox.clone();
  7869. }
  7870. if (geometry.boundingSphere !== null) {
  7871. this.boundingSphere = geometry.boundingSphere.clone();
  7872. }
  7873. return this;
  7874. },
  7875. center: function () {
  7876. this.computeBoundingBox();
  7877. this.boundingBox.getCenter(_offset$1).negate();
  7878. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  7879. return this;
  7880. },
  7881. normalize: function () {
  7882. this.computeBoundingSphere();
  7883. var center = this.boundingSphere.center;
  7884. var radius = this.boundingSphere.radius;
  7885. var s = radius === 0 ? 1 : 1.0 / radius;
  7886. var matrix = new Matrix4();
  7887. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  7888. this.applyMatrix4(matrix);
  7889. return this;
  7890. },
  7891. computeFaceNormals: function () {
  7892. var cb = new Vector3(),
  7893. ab = new Vector3();
  7894. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  7895. var face = this.faces[f];
  7896. var vA = this.vertices[face.a];
  7897. var vB = this.vertices[face.b];
  7898. var vC = this.vertices[face.c];
  7899. cb.subVectors(vC, vB);
  7900. ab.subVectors(vA, vB);
  7901. cb.cross(ab);
  7902. cb.normalize();
  7903. face.normal.copy(cb);
  7904. }
  7905. },
  7906. computeVertexNormals: function (areaWeighted) {
  7907. if (areaWeighted === undefined) areaWeighted = true;
  7908. var v, vl, f, fl, face, vertices;
  7909. vertices = new Array(this.vertices.length);
  7910. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  7911. vertices[v] = new Vector3();
  7912. }
  7913. if (areaWeighted) {
  7914. // vertex normals weighted by triangle areas
  7915. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7916. var vA, vB, vC;
  7917. var cb = new Vector3(),
  7918. ab = new Vector3();
  7919. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7920. face = this.faces[f];
  7921. vA = this.vertices[face.a];
  7922. vB = this.vertices[face.b];
  7923. vC = this.vertices[face.c];
  7924. cb.subVectors(vC, vB);
  7925. ab.subVectors(vA, vB);
  7926. cb.cross(ab);
  7927. vertices[face.a].add(cb);
  7928. vertices[face.b].add(cb);
  7929. vertices[face.c].add(cb);
  7930. }
  7931. } else {
  7932. this.computeFaceNormals();
  7933. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7934. face = this.faces[f];
  7935. vertices[face.a].add(face.normal);
  7936. vertices[face.b].add(face.normal);
  7937. vertices[face.c].add(face.normal);
  7938. }
  7939. }
  7940. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  7941. vertices[v].normalize();
  7942. }
  7943. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7944. face = this.faces[f];
  7945. var vertexNormals = face.vertexNormals;
  7946. if (vertexNormals.length === 3) {
  7947. vertexNormals[0].copy(vertices[face.a]);
  7948. vertexNormals[1].copy(vertices[face.b]);
  7949. vertexNormals[2].copy(vertices[face.c]);
  7950. } else {
  7951. vertexNormals[0] = vertices[face.a].clone();
  7952. vertexNormals[1] = vertices[face.b].clone();
  7953. vertexNormals[2] = vertices[face.c].clone();
  7954. }
  7955. }
  7956. if (this.faces.length > 0) {
  7957. this.normalsNeedUpdate = true;
  7958. }
  7959. },
  7960. computeFlatVertexNormals: function () {
  7961. var f, fl, face;
  7962. this.computeFaceNormals();
  7963. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7964. face = this.faces[f];
  7965. var vertexNormals = face.vertexNormals;
  7966. if (vertexNormals.length === 3) {
  7967. vertexNormals[0].copy(face.normal);
  7968. vertexNormals[1].copy(face.normal);
  7969. vertexNormals[2].copy(face.normal);
  7970. } else {
  7971. vertexNormals[0] = face.normal.clone();
  7972. vertexNormals[1] = face.normal.clone();
  7973. vertexNormals[2] = face.normal.clone();
  7974. }
  7975. }
  7976. if (this.faces.length > 0) {
  7977. this.normalsNeedUpdate = true;
  7978. }
  7979. },
  7980. computeMorphNormals: function () {
  7981. var i, il, f, fl, face; // save original normals
  7982. // - create temp variables on first access
  7983. // otherwise just copy (for faster repeated calls)
  7984. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7985. face = this.faces[f];
  7986. if (!face.__originalFaceNormal) {
  7987. face.__originalFaceNormal = face.normal.clone();
  7988. } else {
  7989. face.__originalFaceNormal.copy(face.normal);
  7990. }
  7991. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  7992. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  7993. if (!face.__originalVertexNormals[i]) {
  7994. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  7995. } else {
  7996. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  7997. }
  7998. }
  7999. } // use temp geometry to compute face and vertex normals for each morph
  8000. var tmpGeo = new Geometry();
  8001. tmpGeo.faces = this.faces;
  8002. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  8003. // create on first access
  8004. if (!this.morphNormals[i]) {
  8005. this.morphNormals[i] = {};
  8006. this.morphNormals[i].faceNormals = [];
  8007. this.morphNormals[i].vertexNormals = [];
  8008. var dstNormalsFace = this.morphNormals[i].faceNormals;
  8009. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  8010. var faceNormal, vertexNormals;
  8011. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8012. faceNormal = new Vector3();
  8013. vertexNormals = {
  8014. a: new Vector3(),
  8015. b: new Vector3(),
  8016. c: new Vector3()
  8017. };
  8018. dstNormalsFace.push(faceNormal);
  8019. dstNormalsVertex.push(vertexNormals);
  8020. }
  8021. }
  8022. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  8023. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  8024. tmpGeo.computeFaceNormals();
  8025. tmpGeo.computeVertexNormals(); // store morph normals
  8026. var faceNormal, vertexNormals;
  8027. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8028. face = this.faces[f];
  8029. faceNormal = morphNormals.faceNormals[f];
  8030. vertexNormals = morphNormals.vertexNormals[f];
  8031. faceNormal.copy(face.normal);
  8032. vertexNormals.a.copy(face.vertexNormals[0]);
  8033. vertexNormals.b.copy(face.vertexNormals[1]);
  8034. vertexNormals.c.copy(face.vertexNormals[2]);
  8035. }
  8036. } // restore original normals
  8037. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8038. face = this.faces[f];
  8039. face.normal = face.__originalFaceNormal;
  8040. face.vertexNormals = face.__originalVertexNormals;
  8041. }
  8042. },
  8043. computeBoundingBox: function () {
  8044. if (this.boundingBox === null) {
  8045. this.boundingBox = new Box3();
  8046. }
  8047. this.boundingBox.setFromPoints(this.vertices);
  8048. },
  8049. computeBoundingSphere: function () {
  8050. if (this.boundingSphere === null) {
  8051. this.boundingSphere = new Sphere();
  8052. }
  8053. this.boundingSphere.setFromPoints(this.vertices);
  8054. },
  8055. merge: function (geometry, matrix, materialIndexOffset) {
  8056. if (!(geometry && geometry.isGeometry)) {
  8057. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  8058. return;
  8059. }
  8060. var normalMatrix,
  8061. vertexOffset = this.vertices.length,
  8062. vertices1 = this.vertices,
  8063. vertices2 = geometry.vertices,
  8064. faces1 = this.faces,
  8065. faces2 = geometry.faces,
  8066. colors1 = this.colors,
  8067. colors2 = geometry.colors;
  8068. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  8069. if (matrix !== undefined) {
  8070. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8071. } // vertices
  8072. for (var i = 0, il = vertices2.length; i < il; i++) {
  8073. var vertex = vertices2[i];
  8074. var vertexCopy = vertex.clone();
  8075. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  8076. vertices1.push(vertexCopy);
  8077. } // colors
  8078. for (var i = 0, il = colors2.length; i < il; i++) {
  8079. colors1.push(colors2[i].clone());
  8080. } // faces
  8081. for (i = 0, il = faces2.length; i < il; i++) {
  8082. var face = faces2[i],
  8083. faceCopy,
  8084. normal,
  8085. color,
  8086. faceVertexNormals = face.vertexNormals,
  8087. faceVertexColors = face.vertexColors;
  8088. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  8089. faceCopy.normal.copy(face.normal);
  8090. if (normalMatrix !== undefined) {
  8091. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  8092. }
  8093. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  8094. normal = faceVertexNormals[j].clone();
  8095. if (normalMatrix !== undefined) {
  8096. normal.applyMatrix3(normalMatrix).normalize();
  8097. }
  8098. faceCopy.vertexNormals.push(normal);
  8099. }
  8100. faceCopy.color.copy(face.color);
  8101. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  8102. color = faceVertexColors[j];
  8103. faceCopy.vertexColors.push(color.clone());
  8104. }
  8105. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8106. faces1.push(faceCopy);
  8107. } // uvs
  8108. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  8109. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  8110. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  8111. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  8112. var uvs2 = faceVertexUvs2[j],
  8113. uvsCopy = [];
  8114. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  8115. uvsCopy.push(uvs2[k].clone());
  8116. }
  8117. this.faceVertexUvs[i].push(uvsCopy);
  8118. }
  8119. }
  8120. },
  8121. mergeMesh: function (mesh) {
  8122. if (!(mesh && mesh.isMesh)) {
  8123. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  8124. return;
  8125. }
  8126. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  8127. this.merge(mesh.geometry, mesh.matrix);
  8128. },
  8129. /*
  8130. * Checks for duplicate vertices with hashmap.
  8131. * Duplicated vertices are removed
  8132. * and faces' vertices are updated.
  8133. */
  8134. mergeVertices: function () {
  8135. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8136. var unique = [],
  8137. changes = [];
  8138. var v, key;
  8139. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  8140. var precision = Math.pow(10, precisionPoints);
  8141. var i, il, face;
  8142. var indices, j, jl;
  8143. for (i = 0, il = this.vertices.length; i < il; i++) {
  8144. v = this.vertices[i];
  8145. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  8146. if (verticesMap[key] === undefined) {
  8147. verticesMap[key] = i;
  8148. unique.push(this.vertices[i]);
  8149. changes[i] = unique.length - 1;
  8150. } else {
  8151. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  8152. changes[i] = changes[verticesMap[key]];
  8153. }
  8154. } // if faces are completely degenerate after merging vertices, we
  8155. // have to remove them from the geometry.
  8156. var faceIndicesToRemove = [];
  8157. for (i = 0, il = this.faces.length; i < il; i++) {
  8158. face = this.faces[i];
  8159. face.a = changes[face.a];
  8160. face.b = changes[face.b];
  8161. face.c = changes[face.c];
  8162. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  8163. // we have to remove the face as nothing can be saved
  8164. for (var n = 0; n < 3; n++) {
  8165. if (indices[n] === indices[(n + 1) % 3]) {
  8166. faceIndicesToRemove.push(i);
  8167. break;
  8168. }
  8169. }
  8170. }
  8171. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  8172. var idx = faceIndicesToRemove[i];
  8173. this.faces.splice(idx, 1);
  8174. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  8175. this.faceVertexUvs[j].splice(idx, 1);
  8176. }
  8177. } // Use unique set of vertices
  8178. var diff = this.vertices.length - unique.length;
  8179. this.vertices = unique;
  8180. return diff;
  8181. },
  8182. setFromPoints: function (points) {
  8183. this.vertices = [];
  8184. for (var i = 0, l = points.length; i < l; i++) {
  8185. var point = points[i];
  8186. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  8187. }
  8188. return this;
  8189. },
  8190. sortFacesByMaterialIndex: function () {
  8191. var faces = this.faces;
  8192. var length = faces.length; // tag faces
  8193. for (var i = 0; i < length; i++) {
  8194. faces[i]._id = i;
  8195. } // sort faces
  8196. function materialIndexSort(a, b) {
  8197. return a.materialIndex - b.materialIndex;
  8198. }
  8199. faces.sort(materialIndexSort); // sort uvs
  8200. var uvs1 = this.faceVertexUvs[0];
  8201. var uvs2 = this.faceVertexUvs[1];
  8202. var newUvs1, newUvs2;
  8203. if (uvs1 && uvs1.length === length) newUvs1 = [];
  8204. if (uvs2 && uvs2.length === length) newUvs2 = [];
  8205. for (var i = 0; i < length; i++) {
  8206. var id = faces[i]._id;
  8207. if (newUvs1) newUvs1.push(uvs1[id]);
  8208. if (newUvs2) newUvs2.push(uvs2[id]);
  8209. }
  8210. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  8211. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  8212. },
  8213. toJSON: function () {
  8214. var data = {
  8215. metadata: {
  8216. version: 4.5,
  8217. type: 'Geometry',
  8218. generator: 'Geometry.toJSON'
  8219. }
  8220. }; // standard Geometry serialization
  8221. data.uuid = this.uuid;
  8222. data.type = this.type;
  8223. if (this.name !== '') data.name = this.name;
  8224. if (this.parameters !== undefined) {
  8225. var parameters = this.parameters;
  8226. for (var key in parameters) {
  8227. if (parameters[key] !== undefined) data[key] = parameters[key];
  8228. }
  8229. return data;
  8230. }
  8231. var vertices = [];
  8232. for (var i = 0; i < this.vertices.length; i++) {
  8233. var vertex = this.vertices[i];
  8234. vertices.push(vertex.x, vertex.y, vertex.z);
  8235. }
  8236. var faces = [];
  8237. var normals = [];
  8238. var normalsHash = {};
  8239. var colors = [];
  8240. var colorsHash = {};
  8241. var uvs = [];
  8242. var uvsHash = {};
  8243. for (var i = 0; i < this.faces.length; i++) {
  8244. var face = this.faces[i];
  8245. var hasMaterial = true;
  8246. var hasFaceUv = false; // deprecated
  8247. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  8248. var hasFaceNormal = face.normal.length() > 0;
  8249. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8250. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8251. var hasFaceVertexColor = face.vertexColors.length > 0;
  8252. var faceType = 0;
  8253. faceType = setBit(faceType, 0, 0); // isQuad
  8254. faceType = setBit(faceType, 1, hasMaterial);
  8255. faceType = setBit(faceType, 2, hasFaceUv);
  8256. faceType = setBit(faceType, 3, hasFaceVertexUv);
  8257. faceType = setBit(faceType, 4, hasFaceNormal);
  8258. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  8259. faceType = setBit(faceType, 6, hasFaceColor);
  8260. faceType = setBit(faceType, 7, hasFaceVertexColor);
  8261. faces.push(faceType);
  8262. faces.push(face.a, face.b, face.c);
  8263. faces.push(face.materialIndex);
  8264. if (hasFaceVertexUv) {
  8265. var faceVertexUvs = this.faceVertexUvs[0][i];
  8266. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  8267. }
  8268. if (hasFaceNormal) {
  8269. faces.push(getNormalIndex(face.normal));
  8270. }
  8271. if (hasFaceVertexNormal) {
  8272. var vertexNormals = face.vertexNormals;
  8273. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  8274. }
  8275. if (hasFaceColor) {
  8276. faces.push(getColorIndex(face.color));
  8277. }
  8278. if (hasFaceVertexColor) {
  8279. var vertexColors = face.vertexColors;
  8280. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  8281. }
  8282. }
  8283. function setBit(value, position, enabled) {
  8284. return enabled ? value | 1 << position : value & ~(1 << position);
  8285. }
  8286. function getNormalIndex(normal) {
  8287. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8288. if (normalsHash[hash] !== undefined) {
  8289. return normalsHash[hash];
  8290. }
  8291. normalsHash[hash] = normals.length / 3;
  8292. normals.push(normal.x, normal.y, normal.z);
  8293. return normalsHash[hash];
  8294. }
  8295. function getColorIndex(color) {
  8296. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8297. if (colorsHash[hash] !== undefined) {
  8298. return colorsHash[hash];
  8299. }
  8300. colorsHash[hash] = colors.length;
  8301. colors.push(color.getHex());
  8302. return colorsHash[hash];
  8303. }
  8304. function getUvIndex(uv) {
  8305. var hash = uv.x.toString() + uv.y.toString();
  8306. if (uvsHash[hash] !== undefined) {
  8307. return uvsHash[hash];
  8308. }
  8309. uvsHash[hash] = uvs.length / 2;
  8310. uvs.push(uv.x, uv.y);
  8311. return uvsHash[hash];
  8312. }
  8313. data.data = {};
  8314. data.data.vertices = vertices;
  8315. data.data.normals = normals;
  8316. if (colors.length > 0) data.data.colors = colors;
  8317. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  8318. data.data.faces = faces;
  8319. return data;
  8320. },
  8321. clone: function () {
  8322. /*
  8323. // Handle primitives
  8324. var parameters = this.parameters;
  8325. if ( parameters !== undefined ) {
  8326. var values = [];
  8327. for ( var key in parameters ) {
  8328. values.push( parameters[ key ] );
  8329. }
  8330. var geometry = Object.create( this.constructor.prototype );
  8331. this.constructor.apply( geometry, values );
  8332. return geometry;
  8333. }
  8334. return new this.constructor().copy( this );
  8335. */
  8336. return new Geometry().copy(this);
  8337. },
  8338. copy: function (source) {
  8339. var i, il, j, jl, k, kl; // reset
  8340. this.vertices = [];
  8341. this.colors = [];
  8342. this.faces = [];
  8343. this.faceVertexUvs = [[]];
  8344. this.morphTargets = [];
  8345. this.morphNormals = [];
  8346. this.skinWeights = [];
  8347. this.skinIndices = [];
  8348. this.lineDistances = [];
  8349. this.boundingBox = null;
  8350. this.boundingSphere = null; // name
  8351. this.name = source.name; // vertices
  8352. var vertices = source.vertices;
  8353. for (i = 0, il = vertices.length; i < il; i++) {
  8354. this.vertices.push(vertices[i].clone());
  8355. } // colors
  8356. var colors = source.colors;
  8357. for (i = 0, il = colors.length; i < il; i++) {
  8358. this.colors.push(colors[i].clone());
  8359. } // faces
  8360. var faces = source.faces;
  8361. for (i = 0, il = faces.length; i < il; i++) {
  8362. this.faces.push(faces[i].clone());
  8363. } // face vertex uvs
  8364. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  8365. var faceVertexUvs = source.faceVertexUvs[i];
  8366. if (this.faceVertexUvs[i] === undefined) {
  8367. this.faceVertexUvs[i] = [];
  8368. }
  8369. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  8370. var uvs = faceVertexUvs[j],
  8371. uvsCopy = [];
  8372. for (k = 0, kl = uvs.length; k < kl; k++) {
  8373. var uv = uvs[k];
  8374. uvsCopy.push(uv.clone());
  8375. }
  8376. this.faceVertexUvs[i].push(uvsCopy);
  8377. }
  8378. } // morph targets
  8379. var morphTargets = source.morphTargets;
  8380. for (i = 0, il = morphTargets.length; i < il; i++) {
  8381. var morphTarget = {};
  8382. morphTarget.name = morphTargets[i].name; // vertices
  8383. if (morphTargets[i].vertices !== undefined) {
  8384. morphTarget.vertices = [];
  8385. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  8386. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  8387. }
  8388. } // normals
  8389. if (morphTargets[i].normals !== undefined) {
  8390. morphTarget.normals = [];
  8391. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  8392. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  8393. }
  8394. }
  8395. this.morphTargets.push(morphTarget);
  8396. } // morph normals
  8397. var morphNormals = source.morphNormals;
  8398. for (i = 0, il = morphNormals.length; i < il; i++) {
  8399. var morphNormal = {}; // vertex normals
  8400. if (morphNormals[i].vertexNormals !== undefined) {
  8401. morphNormal.vertexNormals = [];
  8402. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  8403. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  8404. var destVertexNormal = {};
  8405. destVertexNormal.a = srcVertexNormal.a.clone();
  8406. destVertexNormal.b = srcVertexNormal.b.clone();
  8407. destVertexNormal.c = srcVertexNormal.c.clone();
  8408. morphNormal.vertexNormals.push(destVertexNormal);
  8409. }
  8410. } // face normals
  8411. if (morphNormals[i].faceNormals !== undefined) {
  8412. morphNormal.faceNormals = [];
  8413. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  8414. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  8415. }
  8416. }
  8417. this.morphNormals.push(morphNormal);
  8418. } // skin weights
  8419. var skinWeights = source.skinWeights;
  8420. for (i = 0, il = skinWeights.length; i < il; i++) {
  8421. this.skinWeights.push(skinWeights[i].clone());
  8422. } // skin indices
  8423. var skinIndices = source.skinIndices;
  8424. for (i = 0, il = skinIndices.length; i < il; i++) {
  8425. this.skinIndices.push(skinIndices[i].clone());
  8426. } // line distances
  8427. var lineDistances = source.lineDistances;
  8428. for (i = 0, il = lineDistances.length; i < il; i++) {
  8429. this.lineDistances.push(lineDistances[i]);
  8430. } // bounding box
  8431. var boundingBox = source.boundingBox;
  8432. if (boundingBox !== null) {
  8433. this.boundingBox = boundingBox.clone();
  8434. } // bounding sphere
  8435. var boundingSphere = source.boundingSphere;
  8436. if (boundingSphere !== null) {
  8437. this.boundingSphere = boundingSphere.clone();
  8438. } // update flags
  8439. this.elementsNeedUpdate = source.elementsNeedUpdate;
  8440. this.verticesNeedUpdate = source.verticesNeedUpdate;
  8441. this.uvsNeedUpdate = source.uvsNeedUpdate;
  8442. this.normalsNeedUpdate = source.normalsNeedUpdate;
  8443. this.colorsNeedUpdate = source.colorsNeedUpdate;
  8444. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  8445. this.groupsNeedUpdate = source.groupsNeedUpdate;
  8446. return this;
  8447. },
  8448. dispose: function () {
  8449. this.dispatchEvent({
  8450. type: 'dispose'
  8451. });
  8452. }
  8453. });
  8454. /**
  8455. * @author mrdoob / http://mrdoob.com/
  8456. * @author Mugen87 / https://github.com/Mugen87
  8457. */
  8458. // BoxGeometry
  8459. class BoxGeometry extends Geometry {
  8460. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  8461. super();
  8462. this.type = 'BoxGeometry';
  8463. this.parameters = {
  8464. width: width,
  8465. height: height,
  8466. depth: depth,
  8467. widthSegments: widthSegments,
  8468. heightSegments: heightSegments,
  8469. depthSegments: depthSegments
  8470. };
  8471. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  8472. this.mergeVertices();
  8473. }
  8474. } // BoxBufferGeometry
  8475. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  8476. class BoxBufferGeometry extends BufferGeometry {
  8477. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  8478. super();
  8479. this.type = 'BoxBufferGeometry';
  8480. this.parameters = {
  8481. width: width,
  8482. height: height,
  8483. depth: depth,
  8484. widthSegments: widthSegments,
  8485. heightSegments: heightSegments,
  8486. depthSegments: depthSegments
  8487. };
  8488. var scope = this;
  8489. width = width || 1;
  8490. height = height || 1;
  8491. depth = depth || 1; // segments
  8492. widthSegments = Math.floor(widthSegments) || 1;
  8493. heightSegments = Math.floor(heightSegments) || 1;
  8494. depthSegments = Math.floor(depthSegments) || 1; // buffers
  8495. var indices = [];
  8496. var vertices = [];
  8497. var normals = [];
  8498. var uvs = []; // helper variables
  8499. var numberOfVertices = 0;
  8500. var groupStart = 0; // build each side of the box geometry
  8501. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  8502. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  8503. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  8504. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  8505. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  8506. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  8507. // build geometry
  8508. this.setIndex(indices);
  8509. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  8510. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  8511. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8512. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  8513. var segmentWidth = width / gridX;
  8514. var segmentHeight = height / gridY;
  8515. var widthHalf = width / 2;
  8516. var heightHalf = height / 2;
  8517. var depthHalf = depth / 2;
  8518. var gridX1 = gridX + 1;
  8519. var gridY1 = gridY + 1;
  8520. var vertexCounter = 0;
  8521. var groupCount = 0;
  8522. var ix, iy;
  8523. var vector = new Vector3(); // generate vertices, normals and uvs
  8524. for (iy = 0; iy < gridY1; iy++) {
  8525. var y = iy * segmentHeight - heightHalf;
  8526. for (ix = 0; ix < gridX1; ix++) {
  8527. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  8528. vector[u] = x * udir;
  8529. vector[v] = y * vdir;
  8530. vector[w] = depthHalf; // now apply vector to vertex buffer
  8531. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  8532. vector[u] = 0;
  8533. vector[v] = 0;
  8534. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  8535. normals.push(vector.x, vector.y, vector.z); // uvs
  8536. uvs.push(ix / gridX);
  8537. uvs.push(1 - iy / gridY); // counters
  8538. vertexCounter += 1;
  8539. }
  8540. } // indices
  8541. // 1. you need three indices to draw a single face
  8542. // 2. a single segment consists of two faces
  8543. // 3. so we need to generate six (2*3) indices per segment
  8544. for (iy = 0; iy < gridY; iy++) {
  8545. for (ix = 0; ix < gridX; ix++) {
  8546. var a = numberOfVertices + ix + gridX1 * iy;
  8547. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  8548. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  8549. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  8550. indices.push(a, b, d);
  8551. indices.push(b, c, d); // increase counter
  8552. groupCount += 6;
  8553. }
  8554. } // add a group to the geometry. this will ensure multi material support
  8555. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  8556. groupStart += groupCount; // update total number of vertices
  8557. numberOfVertices += vertexCounter;
  8558. }
  8559. }
  8560. }
  8561. /**
  8562. * Uniform Utilities
  8563. */
  8564. exports.BoxBufferGeometry = BoxBufferGeometry;
  8565. function cloneUniforms(src) {
  8566. var dst = {};
  8567. for (var u in src) {
  8568. dst[u] = {};
  8569. for (var p in src[u]) {
  8570. var property = src[u][p];
  8571. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  8572. dst[u][p] = property.clone();
  8573. } else if (Array.isArray(property)) {
  8574. dst[u][p] = property.slice();
  8575. } else {
  8576. dst[u][p] = property;
  8577. }
  8578. }
  8579. }
  8580. return dst;
  8581. }
  8582. function mergeUniforms(uniforms) {
  8583. var merged = {};
  8584. for (var u = 0; u < uniforms.length; u++) {
  8585. var tmp = cloneUniforms(uniforms[u]);
  8586. for (var p in tmp) {
  8587. merged[p] = tmp[p];
  8588. }
  8589. }
  8590. return merged;
  8591. } // Legacy
  8592. var UniformsUtils = {
  8593. clone: cloneUniforms,
  8594. merge: mergeUniforms
  8595. };
  8596. exports.UniformsUtils = UniformsUtils;
  8597. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  8598. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  8599. /**
  8600. * @author alteredq / http://alteredqualia.com/
  8601. *
  8602. * parameters = {
  8603. * defines: { "label" : "value" },
  8604. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  8605. *
  8606. * fragmentShader: <string>,
  8607. * vertexShader: <string>,
  8608. *
  8609. * wireframe: <boolean>,
  8610. * wireframeLinewidth: <float>,
  8611. *
  8612. * lights: <bool>,
  8613. *
  8614. * skinning: <bool>,
  8615. * morphTargets: <bool>,
  8616. * morphNormals: <bool>
  8617. * }
  8618. */
  8619. function ShaderMaterial(parameters) {
  8620. Material.call(this);
  8621. this.type = 'ShaderMaterial';
  8622. this.defines = {};
  8623. this.uniforms = {};
  8624. this.vertexShader = default_vertex;
  8625. this.fragmentShader = default_fragment;
  8626. this.linewidth = 1;
  8627. this.wireframe = false;
  8628. this.wireframeLinewidth = 1;
  8629. this.fog = false; // set to use scene fog
  8630. this.lights = false; // set to use scene lights
  8631. this.clipping = false; // set to use user-defined clipping planes
  8632. this.skinning = false; // set to use skinning attribute streams
  8633. this.morphTargets = false; // set to use morph targets
  8634. this.morphNormals = false; // set to use morph normals
  8635. this.extensions = {
  8636. derivatives: false,
  8637. // set to use derivatives
  8638. fragDepth: false,
  8639. // set to use fragment depth values
  8640. drawBuffers: false,
  8641. // set to use draw buffers
  8642. shaderTextureLOD: false // set to use shader texture LOD
  8643. }; // When rendered geometry doesn't include these attributes but the material does,
  8644. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8645. this.defaultAttributeValues = {
  8646. 'color': [1, 1, 1],
  8647. 'uv': [0, 0],
  8648. 'uv2': [0, 0]
  8649. };
  8650. this.index0AttributeName = undefined;
  8651. this.uniformsNeedUpdate = false;
  8652. if (parameters !== undefined) {
  8653. if (parameters.attributes !== undefined) {
  8654. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  8655. }
  8656. this.setValues(parameters);
  8657. }
  8658. }
  8659. ShaderMaterial.prototype = Object.create(Material.prototype);
  8660. ShaderMaterial.prototype.constructor = ShaderMaterial;
  8661. ShaderMaterial.prototype.isShaderMaterial = true;
  8662. ShaderMaterial.prototype.copy = function (source) {
  8663. Material.prototype.copy.call(this, source);
  8664. this.fragmentShader = source.fragmentShader;
  8665. this.vertexShader = source.vertexShader;
  8666. this.uniforms = cloneUniforms(source.uniforms);
  8667. this.defines = Object.assign({}, source.defines);
  8668. this.wireframe = source.wireframe;
  8669. this.wireframeLinewidth = source.wireframeLinewidth;
  8670. this.lights = source.lights;
  8671. this.clipping = source.clipping;
  8672. this.skinning = source.skinning;
  8673. this.morphTargets = source.morphTargets;
  8674. this.morphNormals = source.morphNormals;
  8675. this.extensions = source.extensions;
  8676. return this;
  8677. };
  8678. ShaderMaterial.prototype.toJSON = function (meta) {
  8679. var data = Material.prototype.toJSON.call(this, meta);
  8680. data.uniforms = {};
  8681. for (var name in this.uniforms) {
  8682. var uniform = this.uniforms[name];
  8683. var value = uniform.value;
  8684. if (value && value.isTexture) {
  8685. data.uniforms[name] = {
  8686. type: 't',
  8687. value: value.toJSON(meta).uuid
  8688. };
  8689. } else if (value && value.isColor) {
  8690. data.uniforms[name] = {
  8691. type: 'c',
  8692. value: value.getHex()
  8693. };
  8694. } else if (value && value.isVector2) {
  8695. data.uniforms[name] = {
  8696. type: 'v2',
  8697. value: value.toArray()
  8698. };
  8699. } else if (value && value.isVector3) {
  8700. data.uniforms[name] = {
  8701. type: 'v3',
  8702. value: value.toArray()
  8703. };
  8704. } else if (value && value.isVector4) {
  8705. data.uniforms[name] = {
  8706. type: 'v4',
  8707. value: value.toArray()
  8708. };
  8709. } else if (value && value.isMatrix3) {
  8710. data.uniforms[name] = {
  8711. type: 'm3',
  8712. value: value.toArray()
  8713. };
  8714. } else if (value && value.isMatrix4) {
  8715. data.uniforms[name] = {
  8716. type: 'm4',
  8717. value: value.toArray()
  8718. };
  8719. } else {
  8720. data.uniforms[name] = {
  8721. value: value
  8722. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  8723. }
  8724. }
  8725. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  8726. data.vertexShader = this.vertexShader;
  8727. data.fragmentShader = this.fragmentShader;
  8728. var extensions = {};
  8729. for (var key in this.extensions) {
  8730. if (this.extensions[key] === true) extensions[key] = true;
  8731. }
  8732. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  8733. return data;
  8734. };
  8735. /**
  8736. * @author mrdoob / http://mrdoob.com/
  8737. * @author mikael emtinger / http://gomo.se/
  8738. * @author WestLangley / http://github.com/WestLangley
  8739. */
  8740. function Camera() {
  8741. Object3D.call(this);
  8742. this.type = 'Camera';
  8743. this.matrixWorldInverse = new Matrix4();
  8744. this.projectionMatrix = new Matrix4();
  8745. this.projectionMatrixInverse = new Matrix4();
  8746. }
  8747. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  8748. constructor: Camera,
  8749. isCamera: true,
  8750. copy: function (source, recursive) {
  8751. Object3D.prototype.copy.call(this, source, recursive);
  8752. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  8753. this.projectionMatrix.copy(source.projectionMatrix);
  8754. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  8755. return this;
  8756. },
  8757. getWorldDirection: function (target) {
  8758. if (target === undefined) {
  8759. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  8760. target = new Vector3();
  8761. }
  8762. this.updateMatrixWorld(true);
  8763. var e = this.matrixWorld.elements;
  8764. return target.set(-e[8], -e[9], -e[10]).normalize();
  8765. },
  8766. updateMatrixWorld: function (force) {
  8767. Object3D.prototype.updateMatrixWorld.call(this, force);
  8768. this.matrixWorldInverse.getInverse(this.matrixWorld);
  8769. },
  8770. updateWorldMatrix: function (updateParents, updateChildren) {
  8771. Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
  8772. this.matrixWorldInverse.getInverse(this.matrixWorld);
  8773. },
  8774. clone: function () {
  8775. return new this.constructor().copy(this);
  8776. }
  8777. });
  8778. /**
  8779. * @author mrdoob / http://mrdoob.com/
  8780. * @author greggman / http://games.greggman.com/
  8781. * @author zz85 / http://www.lab4games.net/zz85/blog
  8782. * @author tschw
  8783. */
  8784. function PerspectiveCamera(fov, aspect, near, far) {
  8785. Camera.call(this);
  8786. this.type = 'PerspectiveCamera';
  8787. this.fov = fov !== undefined ? fov : 50;
  8788. this.zoom = 1;
  8789. this.near = near !== undefined ? near : 0.1;
  8790. this.far = far !== undefined ? far : 2000;
  8791. this.focus = 10;
  8792. this.aspect = aspect !== undefined ? aspect : 1;
  8793. this.view = null;
  8794. this.filmGauge = 35; // width of the film (default in millimeters)
  8795. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  8796. this.updateProjectionMatrix();
  8797. }
  8798. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  8799. constructor: PerspectiveCamera,
  8800. isPerspectiveCamera: true,
  8801. copy: function (source, recursive) {
  8802. Camera.prototype.copy.call(this, source, recursive);
  8803. this.fov = source.fov;
  8804. this.zoom = source.zoom;
  8805. this.near = source.near;
  8806. this.far = source.far;
  8807. this.focus = source.focus;
  8808. this.aspect = source.aspect;
  8809. this.view = source.view === null ? null : Object.assign({}, source.view);
  8810. this.filmGauge = source.filmGauge;
  8811. this.filmOffset = source.filmOffset;
  8812. return this;
  8813. },
  8814. /**
  8815. * Sets the FOV by focal length in respect to the current .filmGauge.
  8816. *
  8817. * The default film gauge is 35, so that the focal length can be specified for
  8818. * a 35mm (full frame) camera.
  8819. *
  8820. * Values for focal length and film gauge must have the same unit.
  8821. */
  8822. setFocalLength: function (focalLength) {
  8823. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  8824. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  8825. this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
  8826. this.updateProjectionMatrix();
  8827. },
  8828. /**
  8829. * Calculates the focal length from the current .fov and .filmGauge.
  8830. */
  8831. getFocalLength: function () {
  8832. var vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
  8833. return 0.5 * this.getFilmHeight() / vExtentSlope;
  8834. },
  8835. getEffectiveFOV: function () {
  8836. return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
  8837. },
  8838. getFilmWidth: function () {
  8839. // film not completely covered in portrait format (aspect < 1)
  8840. return this.filmGauge * Math.min(this.aspect, 1);
  8841. },
  8842. getFilmHeight: function () {
  8843. // film not completely covered in landscape format (aspect > 1)
  8844. return this.filmGauge / Math.max(this.aspect, 1);
  8845. },
  8846. /**
  8847. * Sets an offset in a larger frustum. This is useful for multi-window or
  8848. * multi-monitor/multi-machine setups.
  8849. *
  8850. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8851. * the monitors are in grid like this
  8852. *
  8853. * +---+---+---+
  8854. * | A | B | C |
  8855. * +---+---+---+
  8856. * | D | E | F |
  8857. * +---+---+---+
  8858. *
  8859. * then for each monitor you would call it like this
  8860. *
  8861. * var w = 1920;
  8862. * var h = 1080;
  8863. * var fullWidth = w * 3;
  8864. * var fullHeight = h * 2;
  8865. *
  8866. * --A--
  8867. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8868. * --B--
  8869. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8870. * --C--
  8871. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8872. * --D--
  8873. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8874. * --E--
  8875. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8876. * --F--
  8877. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8878. *
  8879. * Note there is no reason monitors have to be the same size or in a grid.
  8880. */
  8881. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  8882. this.aspect = fullWidth / fullHeight;
  8883. if (this.view === null) {
  8884. this.view = {
  8885. enabled: true,
  8886. fullWidth: 1,
  8887. fullHeight: 1,
  8888. offsetX: 0,
  8889. offsetY: 0,
  8890. width: 1,
  8891. height: 1
  8892. };
  8893. }
  8894. this.view.enabled = true;
  8895. this.view.fullWidth = fullWidth;
  8896. this.view.fullHeight = fullHeight;
  8897. this.view.offsetX = x;
  8898. this.view.offsetY = y;
  8899. this.view.width = width;
  8900. this.view.height = height;
  8901. this.updateProjectionMatrix();
  8902. },
  8903. clearViewOffset: function () {
  8904. if (this.view !== null) {
  8905. this.view.enabled = false;
  8906. }
  8907. this.updateProjectionMatrix();
  8908. },
  8909. updateProjectionMatrix: function () {
  8910. var near = this.near,
  8911. top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom,
  8912. height = 2 * top,
  8913. width = this.aspect * height,
  8914. left = -0.5 * width,
  8915. view = this.view;
  8916. if (this.view !== null && this.view.enabled) {
  8917. var fullWidth = view.fullWidth,
  8918. fullHeight = view.fullHeight;
  8919. left += view.offsetX * width / fullWidth;
  8920. top -= view.offsetY * height / fullHeight;
  8921. width *= view.width / fullWidth;
  8922. height *= view.height / fullHeight;
  8923. }
  8924. var skew = this.filmOffset;
  8925. if (skew !== 0) left += near * skew / this.getFilmWidth();
  8926. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  8927. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  8928. },
  8929. toJSON: function (meta) {
  8930. var data = Object3D.prototype.toJSON.call(this, meta);
  8931. data.object.fov = this.fov;
  8932. data.object.zoom = this.zoom;
  8933. data.object.near = this.near;
  8934. data.object.far = this.far;
  8935. data.object.focus = this.focus;
  8936. data.object.aspect = this.aspect;
  8937. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  8938. data.object.filmGauge = this.filmGauge;
  8939. data.object.filmOffset = this.filmOffset;
  8940. return data;
  8941. }
  8942. });
  8943. /**
  8944. * Camera for rendering cube maps
  8945. * - renders scene into axis-aligned cube
  8946. *
  8947. * @author alteredq / http://alteredqualia.com/
  8948. */
  8949. var fov = 90,
  8950. aspect = 1;
  8951. function CubeCamera(near, far, cubeResolution, options) {
  8952. Object3D.call(this);
  8953. this.type = 'CubeCamera';
  8954. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  8955. cameraPX.up.set(0, -1, 0);
  8956. cameraPX.lookAt(new Vector3(1, 0, 0));
  8957. this.add(cameraPX);
  8958. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  8959. cameraNX.up.set(0, -1, 0);
  8960. cameraNX.lookAt(new Vector3(-1, 0, 0));
  8961. this.add(cameraNX);
  8962. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  8963. cameraPY.up.set(0, 0, 1);
  8964. cameraPY.lookAt(new Vector3(0, 1, 0));
  8965. this.add(cameraPY);
  8966. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  8967. cameraNY.up.set(0, 0, -1);
  8968. cameraNY.lookAt(new Vector3(0, -1, 0));
  8969. this.add(cameraNY);
  8970. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  8971. cameraPZ.up.set(0, -1, 0);
  8972. cameraPZ.lookAt(new Vector3(0, 0, 1));
  8973. this.add(cameraPZ);
  8974. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  8975. cameraNZ.up.set(0, -1, 0);
  8976. cameraNZ.lookAt(new Vector3(0, 0, -1));
  8977. this.add(cameraNZ);
  8978. options = options || {
  8979. format: RGBFormat,
  8980. magFilter: LinearFilter,
  8981. minFilter: LinearFilter
  8982. };
  8983. this.renderTarget = new WebGLCubeRenderTarget(cubeResolution, options);
  8984. this.renderTarget.texture.name = "CubeCamera";
  8985. this.update = function (renderer, scene) {
  8986. if (this.parent === null) this.updateMatrixWorld();
  8987. var currentRenderTarget = renderer.getRenderTarget();
  8988. var renderTarget = this.renderTarget;
  8989. var generateMipmaps = renderTarget.texture.generateMipmaps;
  8990. renderTarget.texture.generateMipmaps = false;
  8991. renderer.setRenderTarget(renderTarget, 0);
  8992. renderer.render(scene, cameraPX);
  8993. renderer.setRenderTarget(renderTarget, 1);
  8994. renderer.render(scene, cameraNX);
  8995. renderer.setRenderTarget(renderTarget, 2);
  8996. renderer.render(scene, cameraPY);
  8997. renderer.setRenderTarget(renderTarget, 3);
  8998. renderer.render(scene, cameraNY);
  8999. renderer.setRenderTarget(renderTarget, 4);
  9000. renderer.render(scene, cameraPZ);
  9001. renderTarget.texture.generateMipmaps = generateMipmaps;
  9002. renderer.setRenderTarget(renderTarget, 5);
  9003. renderer.render(scene, cameraNZ);
  9004. renderer.setRenderTarget(currentRenderTarget);
  9005. };
  9006. this.clear = function (renderer, color, depth, stencil) {
  9007. var currentRenderTarget = renderer.getRenderTarget();
  9008. var renderTarget = this.renderTarget;
  9009. for (var i = 0; i < 6; i++) {
  9010. renderer.setRenderTarget(renderTarget, i);
  9011. renderer.clear(color, depth, stencil);
  9012. }
  9013. renderer.setRenderTarget(currentRenderTarget);
  9014. };
  9015. }
  9016. CubeCamera.prototype = Object.create(Object3D.prototype);
  9017. CubeCamera.prototype.constructor = CubeCamera;
  9018. /**
  9019. * @author alteredq / http://alteredqualia.com
  9020. * @author WestLangley / http://github.com/WestLangley
  9021. */
  9022. function WebGLCubeRenderTarget(size, options, dummy) {
  9023. if (Number.isInteger(options)) {
  9024. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  9025. options = dummy;
  9026. }
  9027. WebGLRenderTarget.call(this, size, size, options);
  9028. }
  9029. WebGLCubeRenderTarget.prototype = Object.create(WebGLRenderTarget.prototype);
  9030. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  9031. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  9032. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function (renderer, texture) {
  9033. this.texture.type = texture.type;
  9034. this.texture.format = texture.format;
  9035. this.texture.encoding = texture.encoding;
  9036. var scene = new Scene();
  9037. var shader = {
  9038. uniforms: {
  9039. tEquirect: {
  9040. value: null
  9041. }
  9042. },
  9043. 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'),
  9044. 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')
  9045. };
  9046. var material = new ShaderMaterial({
  9047. type: 'CubemapFromEquirect',
  9048. uniforms: cloneUniforms(shader.uniforms),
  9049. vertexShader: shader.vertexShader,
  9050. fragmentShader: shader.fragmentShader,
  9051. side: BackSide,
  9052. blending: NoBlending
  9053. });
  9054. material.uniforms.tEquirect.value = texture;
  9055. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  9056. scene.add(mesh);
  9057. var camera = new CubeCamera(1, 10, 1);
  9058. camera.renderTarget = this;
  9059. camera.renderTarget.texture.name = 'CubeCameraTexture';
  9060. camera.update(renderer, scene);
  9061. mesh.geometry.dispose();
  9062. mesh.material.dispose();
  9063. return this;
  9064. };
  9065. /**
  9066. * @author alteredq / http://alteredqualia.com/
  9067. */
  9068. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  9069. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  9070. this.image = {
  9071. data: data || null,
  9072. width: width || 1,
  9073. height: height || 1
  9074. };
  9075. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  9076. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  9077. this.generateMipmaps = false;
  9078. this.flipY = false;
  9079. this.unpackAlignment = 1;
  9080. this.needsUpdate = true;
  9081. }
  9082. DataTexture.prototype = Object.create(Texture.prototype);
  9083. DataTexture.prototype.constructor = DataTexture;
  9084. DataTexture.prototype.isDataTexture = true;
  9085. /**
  9086. * @author mrdoob / http://mrdoob.com/
  9087. * @author alteredq / http://alteredqualia.com/
  9088. * @author bhouston / http://clara.io
  9089. */
  9090. var _sphere$1 = new Sphere();
  9091. var _vector$5 = new Vector3();
  9092. function Frustum(p0, p1, p2, p3, p4, p5) {
  9093. 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()];
  9094. }
  9095. Object.assign(Frustum.prototype, {
  9096. set: function (p0, p1, p2, p3, p4, p5) {
  9097. var planes = this.planes;
  9098. planes[0].copy(p0);
  9099. planes[1].copy(p1);
  9100. planes[2].copy(p2);
  9101. planes[3].copy(p3);
  9102. planes[4].copy(p4);
  9103. planes[5].copy(p5);
  9104. return this;
  9105. },
  9106. clone: function () {
  9107. return new this.constructor().copy(this);
  9108. },
  9109. copy: function (frustum) {
  9110. var planes = this.planes;
  9111. for (var i = 0; i < 6; i++) {
  9112. planes[i].copy(frustum.planes[i]);
  9113. }
  9114. return this;
  9115. },
  9116. setFromProjectionMatrix: function (m) {
  9117. var planes = this.planes;
  9118. var me = m.elements;
  9119. var me0 = me[0],
  9120. me1 = me[1],
  9121. me2 = me[2],
  9122. me3 = me[3];
  9123. var me4 = me[4],
  9124. me5 = me[5],
  9125. me6 = me[6],
  9126. me7 = me[7];
  9127. var me8 = me[8],
  9128. me9 = me[9],
  9129. me10 = me[10],
  9130. me11 = me[11];
  9131. var me12 = me[12],
  9132. me13 = me[13],
  9133. me14 = me[14],
  9134. me15 = me[15];
  9135. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  9136. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  9137. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  9138. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  9139. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  9140. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  9141. return this;
  9142. },
  9143. intersectsObject: function (object) {
  9144. var geometry = object.geometry;
  9145. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  9146. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  9147. return this.intersectsSphere(_sphere$1);
  9148. },
  9149. intersectsSprite: function (sprite) {
  9150. _sphere$1.center.set(0, 0, 0);
  9151. _sphere$1.radius = 0.7071067811865476;
  9152. _sphere$1.applyMatrix4(sprite.matrixWorld);
  9153. return this.intersectsSphere(_sphere$1);
  9154. },
  9155. intersectsSphere: function (sphere) {
  9156. var planes = this.planes;
  9157. var center = sphere.center;
  9158. var negRadius = -sphere.radius;
  9159. for (var i = 0; i < 6; i++) {
  9160. var distance = planes[i].distanceToPoint(center);
  9161. if (distance < negRadius) {
  9162. return false;
  9163. }
  9164. }
  9165. return true;
  9166. },
  9167. intersectsBox: function (box) {
  9168. var planes = this.planes;
  9169. for (var i = 0; i < 6; i++) {
  9170. var plane = planes[i]; // corner at max distance
  9171. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9172. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9173. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9174. if (plane.distanceToPoint(_vector$5) < 0) {
  9175. return false;
  9176. }
  9177. }
  9178. return true;
  9179. },
  9180. containsPoint: function (point) {
  9181. var planes = this.planes;
  9182. for (var i = 0; i < 6; i++) {
  9183. if (planes[i].distanceToPoint(point) < 0) {
  9184. return false;
  9185. }
  9186. }
  9187. return true;
  9188. }
  9189. });
  9190. /**
  9191. * Uniforms library for shared webgl shaders
  9192. */
  9193. var UniformsLib = {
  9194. common: {
  9195. diffuse: {
  9196. value: new Color(0xeeeeee)
  9197. },
  9198. opacity: {
  9199. value: 1.0
  9200. },
  9201. map: {
  9202. value: null
  9203. },
  9204. uvTransform: {
  9205. value: new Matrix3()
  9206. },
  9207. uv2Transform: {
  9208. value: new Matrix3()
  9209. },
  9210. alphaMap: {
  9211. value: null
  9212. }
  9213. },
  9214. specularmap: {
  9215. specularMap: {
  9216. value: null
  9217. }
  9218. },
  9219. envmap: {
  9220. envMap: {
  9221. value: null
  9222. },
  9223. flipEnvMap: {
  9224. value: -1
  9225. },
  9226. reflectivity: {
  9227. value: 1.0
  9228. },
  9229. refractionRatio: {
  9230. value: 0.98
  9231. },
  9232. maxMipLevel: {
  9233. value: 0
  9234. }
  9235. },
  9236. aomap: {
  9237. aoMap: {
  9238. value: null
  9239. },
  9240. aoMapIntensity: {
  9241. value: 1
  9242. }
  9243. },
  9244. lightmap: {
  9245. lightMap: {
  9246. value: null
  9247. },
  9248. lightMapIntensity: {
  9249. value: 1
  9250. }
  9251. },
  9252. emissivemap: {
  9253. emissiveMap: {
  9254. value: null
  9255. }
  9256. },
  9257. bumpmap: {
  9258. bumpMap: {
  9259. value: null
  9260. },
  9261. bumpScale: {
  9262. value: 1
  9263. }
  9264. },
  9265. normalmap: {
  9266. normalMap: {
  9267. value: null
  9268. },
  9269. normalScale: {
  9270. value: new Vector2(1, 1)
  9271. }
  9272. },
  9273. displacementmap: {
  9274. displacementMap: {
  9275. value: null
  9276. },
  9277. displacementScale: {
  9278. value: 1
  9279. },
  9280. displacementBias: {
  9281. value: 0
  9282. }
  9283. },
  9284. roughnessmap: {
  9285. roughnessMap: {
  9286. value: null
  9287. }
  9288. },
  9289. metalnessmap: {
  9290. metalnessMap: {
  9291. value: null
  9292. }
  9293. },
  9294. gradientmap: {
  9295. gradientMap: {
  9296. value: null
  9297. }
  9298. },
  9299. fog: {
  9300. fogDensity: {
  9301. value: 0.00025
  9302. },
  9303. fogNear: {
  9304. value: 1
  9305. },
  9306. fogFar: {
  9307. value: 2000
  9308. },
  9309. fogColor: {
  9310. value: new Color(0xffffff)
  9311. }
  9312. },
  9313. lights: {
  9314. ambientLightColor: {
  9315. value: []
  9316. },
  9317. lightProbe: {
  9318. value: []
  9319. },
  9320. directionalLights: {
  9321. value: [],
  9322. properties: {
  9323. direction: {},
  9324. color: {}
  9325. }
  9326. },
  9327. directionalLightShadows: {
  9328. value: [],
  9329. properties: {
  9330. shadowBias: {},
  9331. shadowRadius: {},
  9332. shadowMapSize: {}
  9333. }
  9334. },
  9335. directionalShadowMap: {
  9336. value: []
  9337. },
  9338. directionalShadowMatrix: {
  9339. value: []
  9340. },
  9341. spotLights: {
  9342. value: [],
  9343. properties: {
  9344. color: {},
  9345. position: {},
  9346. direction: {},
  9347. distance: {},
  9348. coneCos: {},
  9349. penumbraCos: {},
  9350. decay: {}
  9351. }
  9352. },
  9353. spotLightShadows: {
  9354. value: [],
  9355. properties: {
  9356. shadowBias: {},
  9357. shadowRadius: {},
  9358. shadowMapSize: {}
  9359. }
  9360. },
  9361. spotShadowMap: {
  9362. value: []
  9363. },
  9364. spotShadowMatrix: {
  9365. value: []
  9366. },
  9367. pointLights: {
  9368. value: [],
  9369. properties: {
  9370. color: {},
  9371. position: {},
  9372. decay: {},
  9373. distance: {}
  9374. }
  9375. },
  9376. pointLightShadows: {
  9377. value: [],
  9378. properties: {
  9379. shadowBias: {},
  9380. shadowRadius: {},
  9381. shadowMapSize: {},
  9382. shadowCameraNear: {},
  9383. shadowCameraFar: {}
  9384. }
  9385. },
  9386. pointShadowMap: {
  9387. value: []
  9388. },
  9389. pointShadowMatrix: {
  9390. value: []
  9391. },
  9392. hemisphereLights: {
  9393. value: [],
  9394. properties: {
  9395. direction: {},
  9396. skyColor: {},
  9397. groundColor: {}
  9398. }
  9399. },
  9400. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9401. rectAreaLights: {
  9402. value: [],
  9403. properties: {
  9404. color: {},
  9405. position: {},
  9406. width: {},
  9407. height: {}
  9408. }
  9409. }
  9410. },
  9411. points: {
  9412. diffuse: {
  9413. value: new Color(0xeeeeee)
  9414. },
  9415. opacity: {
  9416. value: 1.0
  9417. },
  9418. size: {
  9419. value: 1.0
  9420. },
  9421. scale: {
  9422. value: 1.0
  9423. },
  9424. map: {
  9425. value: null
  9426. },
  9427. alphaMap: {
  9428. value: null
  9429. },
  9430. uvTransform: {
  9431. value: new Matrix3()
  9432. }
  9433. },
  9434. sprite: {
  9435. diffuse: {
  9436. value: new Color(0xeeeeee)
  9437. },
  9438. opacity: {
  9439. value: 1.0
  9440. },
  9441. center: {
  9442. value: new Vector2(0.5, 0.5)
  9443. },
  9444. rotation: {
  9445. value: 0.0
  9446. },
  9447. map: {
  9448. value: null
  9449. },
  9450. alphaMap: {
  9451. value: null
  9452. },
  9453. uvTransform: {
  9454. value: new Matrix3()
  9455. }
  9456. }
  9457. };
  9458. /**
  9459. * @author mrdoob / http://mrdoob.com/
  9460. */
  9461. exports.UniformsLib = UniformsLib;
  9462. function WebGLAnimation() {
  9463. var context = null;
  9464. var isAnimating = false;
  9465. var animationLoop = null;
  9466. function onAnimationFrame(time, frame) {
  9467. if (isAnimating === false) return;
  9468. animationLoop(time, frame);
  9469. context.requestAnimationFrame(onAnimationFrame);
  9470. }
  9471. return {
  9472. start: function () {
  9473. if (isAnimating === true) return;
  9474. if (animationLoop === null) return;
  9475. context.requestAnimationFrame(onAnimationFrame);
  9476. isAnimating = true;
  9477. },
  9478. stop: function () {
  9479. isAnimating = false;
  9480. },
  9481. setAnimationLoop: function (callback) {
  9482. animationLoop = callback;
  9483. },
  9484. setContext: function (value) {
  9485. context = value;
  9486. }
  9487. };
  9488. }
  9489. /**
  9490. * @author mrdoob / http://mrdoob.com/
  9491. */
  9492. function WebGLAttributes(gl, capabilities) {
  9493. var isWebGL2 = capabilities.isWebGL2;
  9494. var buffers = new WeakMap();
  9495. function createBuffer(attribute, bufferType) {
  9496. var array = attribute.array;
  9497. var usage = attribute.usage;
  9498. var buffer = gl.createBuffer();
  9499. gl.bindBuffer(bufferType, buffer);
  9500. gl.bufferData(bufferType, array, usage);
  9501. attribute.onUploadCallback();
  9502. var type = 5126;
  9503. if (array instanceof Float32Array) {
  9504. type = 5126;
  9505. } else if (array instanceof Float64Array) {
  9506. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  9507. } else if (array instanceof Uint16Array) {
  9508. type = 5123;
  9509. } else if (array instanceof Int16Array) {
  9510. type = 5122;
  9511. } else if (array instanceof Uint32Array) {
  9512. type = 5125;
  9513. } else if (array instanceof Int32Array) {
  9514. type = 5124;
  9515. } else if (array instanceof Int8Array) {
  9516. type = 5120;
  9517. } else if (array instanceof Uint8Array) {
  9518. type = 5121;
  9519. }
  9520. return {
  9521. buffer: buffer,
  9522. type: type,
  9523. bytesPerElement: array.BYTES_PER_ELEMENT,
  9524. version: attribute.version
  9525. };
  9526. }
  9527. function updateBuffer(buffer, attribute, bufferType) {
  9528. var array = attribute.array;
  9529. var updateRange = attribute.updateRange;
  9530. gl.bindBuffer(bufferType, buffer);
  9531. if (updateRange.count === -1) {
  9532. // Not using update ranges
  9533. gl.bufferSubData(bufferType, 0, array);
  9534. } else {
  9535. if (isWebGL2) {
  9536. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  9537. } else {
  9538. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  9539. }
  9540. updateRange.count = -1; // reset range
  9541. }
  9542. } //
  9543. function get(attribute) {
  9544. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9545. return buffers.get(attribute);
  9546. }
  9547. function remove(attribute) {
  9548. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9549. var data = buffers.get(attribute);
  9550. if (data) {
  9551. gl.deleteBuffer(data.buffer);
  9552. buffers.delete(attribute);
  9553. }
  9554. }
  9555. function update(attribute, bufferType) {
  9556. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9557. var data = buffers.get(attribute);
  9558. if (data === undefined) {
  9559. buffers.set(attribute, createBuffer(attribute, bufferType));
  9560. } else if (data.version < attribute.version) {
  9561. updateBuffer(data.buffer, attribute, bufferType);
  9562. data.version = attribute.version;
  9563. }
  9564. }
  9565. return {
  9566. get: get,
  9567. remove: remove,
  9568. update: update
  9569. };
  9570. }
  9571. /**
  9572. * @author mrdoob / http://mrdoob.com/
  9573. * @author Mugen87 / https://github.com/Mugen87
  9574. */
  9575. // PlaneGeometry
  9576. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  9577. Geometry.call(this);
  9578. this.type = 'PlaneGeometry';
  9579. this.parameters = {
  9580. width: width,
  9581. height: height,
  9582. widthSegments: widthSegments,
  9583. heightSegments: heightSegments
  9584. };
  9585. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  9586. this.mergeVertices();
  9587. }
  9588. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  9589. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  9590. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  9591. BufferGeometry.call(this);
  9592. this.type = 'PlaneBufferGeometry';
  9593. this.parameters = {
  9594. width: width,
  9595. height: height,
  9596. widthSegments: widthSegments,
  9597. heightSegments: heightSegments
  9598. };
  9599. width = width || 1;
  9600. height = height || 1;
  9601. var width_half = width / 2;
  9602. var height_half = height / 2;
  9603. var gridX = Math.floor(widthSegments) || 1;
  9604. var gridY = Math.floor(heightSegments) || 1;
  9605. var gridX1 = gridX + 1;
  9606. var gridY1 = gridY + 1;
  9607. var segment_width = width / gridX;
  9608. var segment_height = height / gridY;
  9609. var ix, iy; // buffers
  9610. var indices = [];
  9611. var vertices = [];
  9612. var normals = [];
  9613. var uvs = []; // generate vertices, normals and uvs
  9614. for (iy = 0; iy < gridY1; iy++) {
  9615. var y = iy * segment_height - height_half;
  9616. for (ix = 0; ix < gridX1; ix++) {
  9617. var x = ix * segment_width - width_half;
  9618. vertices.push(x, -y, 0);
  9619. normals.push(0, 0, 1);
  9620. uvs.push(ix / gridX);
  9621. uvs.push(1 - iy / gridY);
  9622. }
  9623. } // indices
  9624. for (iy = 0; iy < gridY; iy++) {
  9625. for (ix = 0; ix < gridX; ix++) {
  9626. var a = ix + gridX1 * iy;
  9627. var b = ix + gridX1 * (iy + 1);
  9628. var c = ix + 1 + gridX1 * (iy + 1);
  9629. var d = ix + 1 + gridX1 * iy; // faces
  9630. indices.push(a, b, d);
  9631. indices.push(b, c, d);
  9632. }
  9633. } // build geometry
  9634. this.setIndex(indices);
  9635. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  9636. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  9637. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9638. }
  9639. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  9640. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9641. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  9642. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  9643. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  9644. 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";
  9645. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  9646. var begin_vertex = "vec3 transformed = vec3( position );";
  9647. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  9648. 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";
  9649. 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";
  9650. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  9651. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  9652. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  9653. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  9654. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  9655. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  9656. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  9657. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  9658. 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}";
  9659. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_maxMipLevel 8.0\n#define cubeUV_minMipLevel 4.0\n#define cubeUV_maxTileSize 256.0\n#define cubeUV_minTileSize 16.0\nfloat getFace(vec3 direction) {\n vec3 absDirection = abs(direction);\n float face = -1.0;\n if (absDirection.x > absDirection.z) {\n if (absDirection.x > absDirection.y)\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if (absDirection.z > absDirection.y)\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n}\nvec2 getUV(vec3 direction, float face) {\n vec2 uv;\n if (face == 0.0) {\n uv = vec2(-direction.z, direction.y) / abs(direction.x);\n } else if (face == 1.0) {\n uv = vec2(direction.x, -direction.z) / abs(direction.y);\n } else if (face == 2.0) {\n uv = direction.xy / abs(direction.z);\n } else if (face == 3.0) {\n uv = vec2(direction.z, direction.y) / abs(direction.x);\n } else if (face == 4.0) {\n uv = direction.xz / abs(direction.y);\n } else {\n uv = vec2(-direction.x, direction.y) / abs(direction.z);\n }\n return 0.5 * (uv + 1.0);\n}\nvec3 bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) {\n float face = getFace(direction);\n float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0);\n mipInt = max(mipInt, cubeUV_minMipLevel);\n float faceSize = exp2(mipInt);\n float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize);\n vec2 uv = getUV(direction, face) * (faceSize - 1.0);\n vec2 f = fract(uv);\n uv += 0.5 - f;\n if (face > 2.0) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n if(mipInt < cubeUV_maxMipLevel){\n uv.y += 2.0 * cubeUV_maxTileSize;\n }\n uv.y += filterInt * 2.0 * cubeUV_minTileSize;\n uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize);\n uv *= texelSize;\n vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x += texelSize;\n vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.y += texelSize;\n vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x -= texelSize;\n vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n vec3 tm = mix(tl, tr, f.x);\n vec3 bm = mix(bl, br, f.x);\n return mix(tm, bm, f.y);\n}\n#define r0 1.0\n#define v0 0.339\n#define m0 -2.0\n#define r1 0.8\n#define v1 0.276\n#define m1 -1.0\n#define r4 0.4\n#define v4 0.046\n#define m4 2.0\n#define r5 0.305\n#define v5 0.016\n#define m5 3.0\n#define r6 0.21\n#define v6 0.0038\n#define m6 4.0\nfloat roughnessToMip(float roughness) {\n float mip = 0.0;\n if (roughness >= r1) {\n mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0;\n } else if (roughness >= r4) {\n mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1;\n } else if (roughness >= r5) {\n mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4;\n } else if (roughness >= r6) {\n mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5;\n } else {\n mip = -2.0 * log2(1.16 * roughness); }\n return mip;\n}\nvec4 textureCubeUV(sampler2D envMap, vec3 sampleDir, float roughness) {\n float mip = clamp(roughnessToMip(roughness), m0, cubeUV_maxMipLevel);\n float mipF = fract(mip);\n float mipInt = floor(mip);\n vec3 color0 = bilinearCubeUV(envMap, sampleDir, mipInt);\n if (mipF == 0.0) {\n return vec4(color0, 1.0);\n } else {\n vec3 color1 = bilinearCubeUV(envMap, sampleDir, mipInt + 1.0);\n return vec4(mix(color0, color1, mipF), 1.0);\n }\n}\n#endif";
  9660. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  9661. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  9662. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  9663. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  9664. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  9665. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  9666. 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 = clamp( floor( D ) / 255.0, 0.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}";
  9667. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\t\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, 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_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\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\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\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";
  9668. 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";
  9669. 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";
  9670. 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";
  9671. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) { \n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\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";
  9672. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  9673. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  9674. 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";
  9675. 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";
  9676. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  9677. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  9678. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  9679. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : 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_start\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\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\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\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\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\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\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\t#pragma unroll_loop_end\n#endif";
  9680. 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};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\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};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\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};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\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";
  9681. 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\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 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\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, 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";
  9682. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  9683. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\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_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  9684. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  9685. 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\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\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)";
  9686. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 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 = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  9687. 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}";
  9688. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : 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#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\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\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\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\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\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\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\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\t#pragma unroll_loop_end\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_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  9689. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * 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";
  9690. 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";
  9691. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  9692. 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";
  9693. 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";
  9694. 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";
  9695. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  9696. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  9697. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  9698. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  9699. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  9700. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  9701. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  9702. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  9703. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  9704. 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\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  9705. 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\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  9706. 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, vec3 mapN ) {\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\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  9707. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  9708. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";
  9709. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  9710. 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 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( 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}";
  9711. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  9712. 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;";
  9713. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  9714. 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";
  9715. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  9716. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  9717. 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 unpackRGBATo2Half( 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 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 dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\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";
  9718. 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";
  9719. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  9720. 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\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  9721. 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";
  9722. 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";
  9723. 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";
  9724. 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";
  9725. 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";
  9726. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  9727. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  9728. 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}";
  9729. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  9730. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  9731. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  9732. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  9733. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  9734. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  9735. 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";
  9736. 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}";
  9737. 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}";
  9738. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  9739. 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}";
  9740. 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>\nvarying vec2 vHighPrecisionZW;\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\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  9741. 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>\nvarying vec2 vHighPrecisionZW;\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\tvHighPrecisionZW = gl_Position.zw;\n}";
  9742. 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}";
  9743. 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}";
  9744. 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}";
  9745. 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}";
  9746. 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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  9747. 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\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  9748. 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 <cube_uv_reflection_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\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * 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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  9749. 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}";
  9750. 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 <cube_uv_reflection_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}";
  9751. 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}";
  9752. 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 <color_pars_fragment>\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 <color_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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  9753. 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 <color_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 <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#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}";
  9754. var meshtoon_frag = "#define TOON\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 <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_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_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  9755. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  9756. 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 <cube_uv_reflection_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}";
  9757. 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}";
  9758. 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_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}";
  9759. 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}";
  9760. 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}";
  9761. 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 <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 <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}";
  9762. 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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  9763. 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}";
  9764. 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 <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  9765. 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}";
  9766. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\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 <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 <alphamap_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}";
  9767. 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}";
  9768. var ShaderChunk = {
  9769. alphamap_fragment: alphamap_fragment,
  9770. alphamap_pars_fragment: alphamap_pars_fragment,
  9771. alphatest_fragment: alphatest_fragment,
  9772. aomap_fragment: aomap_fragment,
  9773. aomap_pars_fragment: aomap_pars_fragment,
  9774. begin_vertex: begin_vertex,
  9775. beginnormal_vertex: beginnormal_vertex,
  9776. bsdfs: bsdfs,
  9777. bumpmap_pars_fragment: bumpmap_pars_fragment,
  9778. clipping_planes_fragment: clipping_planes_fragment,
  9779. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  9780. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  9781. clipping_planes_vertex: clipping_planes_vertex,
  9782. color_fragment: color_fragment,
  9783. color_pars_fragment: color_pars_fragment,
  9784. color_pars_vertex: color_pars_vertex,
  9785. color_vertex: color_vertex,
  9786. common: common,
  9787. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  9788. defaultnormal_vertex: defaultnormal_vertex,
  9789. displacementmap_pars_vertex: displacementmap_pars_vertex,
  9790. displacementmap_vertex: displacementmap_vertex,
  9791. emissivemap_fragment: emissivemap_fragment,
  9792. emissivemap_pars_fragment: emissivemap_pars_fragment,
  9793. encodings_fragment: encodings_fragment,
  9794. encodings_pars_fragment: encodings_pars_fragment,
  9795. envmap_fragment: envmap_fragment,
  9796. envmap_common_pars_fragment: envmap_common_pars_fragment,
  9797. envmap_pars_fragment: envmap_pars_fragment,
  9798. envmap_pars_vertex: envmap_pars_vertex,
  9799. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  9800. envmap_vertex: envmap_vertex,
  9801. fog_vertex: fog_vertex,
  9802. fog_pars_vertex: fog_pars_vertex,
  9803. fog_fragment: fog_fragment,
  9804. fog_pars_fragment: fog_pars_fragment,
  9805. gradientmap_pars_fragment: gradientmap_pars_fragment,
  9806. lightmap_fragment: lightmap_fragment,
  9807. lightmap_pars_fragment: lightmap_pars_fragment,
  9808. lights_lambert_vertex: lights_lambert_vertex,
  9809. lights_pars_begin: lights_pars_begin,
  9810. lights_toon_fragment: lights_toon_fragment,
  9811. lights_toon_pars_fragment: lights_toon_pars_fragment,
  9812. lights_phong_fragment: lights_phong_fragment,
  9813. lights_phong_pars_fragment: lights_phong_pars_fragment,
  9814. lights_physical_fragment: lights_physical_fragment,
  9815. lights_physical_pars_fragment: lights_physical_pars_fragment,
  9816. lights_fragment_begin: lights_fragment_begin,
  9817. lights_fragment_maps: lights_fragment_maps,
  9818. lights_fragment_end: lights_fragment_end,
  9819. logdepthbuf_fragment: logdepthbuf_fragment,
  9820. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  9821. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  9822. logdepthbuf_vertex: logdepthbuf_vertex,
  9823. map_fragment: map_fragment,
  9824. map_pars_fragment: map_pars_fragment,
  9825. map_particle_fragment: map_particle_fragment,
  9826. map_particle_pars_fragment: map_particle_pars_fragment,
  9827. metalnessmap_fragment: metalnessmap_fragment,
  9828. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  9829. morphnormal_vertex: morphnormal_vertex,
  9830. morphtarget_pars_vertex: morphtarget_pars_vertex,
  9831. morphtarget_vertex: morphtarget_vertex,
  9832. normal_fragment_begin: normal_fragment_begin,
  9833. normal_fragment_maps: normal_fragment_maps,
  9834. normalmap_pars_fragment: normalmap_pars_fragment,
  9835. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  9836. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  9837. clearcoat_pars_fragment: clearcoat_pars_fragment,
  9838. packing: packing,
  9839. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  9840. project_vertex: project_vertex,
  9841. dithering_fragment: dithering_fragment,
  9842. dithering_pars_fragment: dithering_pars_fragment,
  9843. roughnessmap_fragment: roughnessmap_fragment,
  9844. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  9845. shadowmap_pars_fragment: shadowmap_pars_fragment,
  9846. shadowmap_pars_vertex: shadowmap_pars_vertex,
  9847. shadowmap_vertex: shadowmap_vertex,
  9848. shadowmask_pars_fragment: shadowmask_pars_fragment,
  9849. skinbase_vertex: skinbase_vertex,
  9850. skinning_pars_vertex: skinning_pars_vertex,
  9851. skinning_vertex: skinning_vertex,
  9852. skinnormal_vertex: skinnormal_vertex,
  9853. specularmap_fragment: specularmap_fragment,
  9854. specularmap_pars_fragment: specularmap_pars_fragment,
  9855. tonemapping_fragment: tonemapping_fragment,
  9856. tonemapping_pars_fragment: tonemapping_pars_fragment,
  9857. uv_pars_fragment: uv_pars_fragment,
  9858. uv_pars_vertex: uv_pars_vertex,
  9859. uv_vertex: uv_vertex,
  9860. uv2_pars_fragment: uv2_pars_fragment,
  9861. uv2_pars_vertex: uv2_pars_vertex,
  9862. uv2_vertex: uv2_vertex,
  9863. worldpos_vertex: worldpos_vertex,
  9864. background_frag: background_frag,
  9865. background_vert: background_vert,
  9866. cube_frag: cube_frag,
  9867. cube_vert: cube_vert,
  9868. depth_frag: depth_frag,
  9869. depth_vert: depth_vert,
  9870. distanceRGBA_frag: distanceRGBA_frag,
  9871. distanceRGBA_vert: distanceRGBA_vert,
  9872. equirect_frag: equirect_frag,
  9873. equirect_vert: equirect_vert,
  9874. linedashed_frag: linedashed_frag,
  9875. linedashed_vert: linedashed_vert,
  9876. meshbasic_frag: meshbasic_frag,
  9877. meshbasic_vert: meshbasic_vert,
  9878. meshlambert_frag: meshlambert_frag,
  9879. meshlambert_vert: meshlambert_vert,
  9880. meshmatcap_frag: meshmatcap_frag,
  9881. meshmatcap_vert: meshmatcap_vert,
  9882. meshtoon_frag: meshtoon_frag,
  9883. meshtoon_vert: meshtoon_vert,
  9884. meshphong_frag: meshphong_frag,
  9885. meshphong_vert: meshphong_vert,
  9886. meshphysical_frag: meshphysical_frag,
  9887. meshphysical_vert: meshphysical_vert,
  9888. normal_frag: normal_frag,
  9889. normal_vert: normal_vert,
  9890. points_frag: points_frag,
  9891. points_vert: points_vert,
  9892. shadow_frag: shadow_frag,
  9893. shadow_vert: shadow_vert,
  9894. sprite_frag: sprite_frag,
  9895. sprite_vert: sprite_vert
  9896. };
  9897. /**
  9898. * @author alteredq / http://alteredqualia.com/
  9899. * @author mrdoob / http://mrdoob.com/
  9900. * @author mikael emtinger / http://gomo.se/
  9901. */
  9902. exports.ShaderChunk = ShaderChunk;
  9903. var ShaderLib = {
  9904. basic: {
  9905. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  9906. vertexShader: ShaderChunk.meshbasic_vert,
  9907. fragmentShader: ShaderChunk.meshbasic_frag
  9908. },
  9909. lambert: {
  9910. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  9911. emissive: {
  9912. value: new Color(0x000000)
  9913. }
  9914. }]),
  9915. vertexShader: ShaderChunk.meshlambert_vert,
  9916. fragmentShader: ShaderChunk.meshlambert_frag
  9917. },
  9918. phong: {
  9919. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  9920. emissive: {
  9921. value: new Color(0x000000)
  9922. },
  9923. specular: {
  9924. value: new Color(0x111111)
  9925. },
  9926. shininess: {
  9927. value: 30
  9928. }
  9929. }]),
  9930. vertexShader: ShaderChunk.meshphong_vert,
  9931. fragmentShader: ShaderChunk.meshphong_frag
  9932. },
  9933. standard: {
  9934. 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, {
  9935. emissive: {
  9936. value: new Color(0x000000)
  9937. },
  9938. roughness: {
  9939. value: 0.5
  9940. },
  9941. metalness: {
  9942. value: 0.5
  9943. },
  9944. envMapIntensity: {
  9945. value: 1
  9946. } // temporary
  9947. }]),
  9948. vertexShader: ShaderChunk.meshphysical_vert,
  9949. fragmentShader: ShaderChunk.meshphysical_frag
  9950. },
  9951. toon: {
  9952. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  9953. emissive: {
  9954. value: new Color(0x000000)
  9955. },
  9956. specular: {
  9957. value: new Color(0x111111)
  9958. },
  9959. shininess: {
  9960. value: 30
  9961. }
  9962. }]),
  9963. vertexShader: ShaderChunk.meshtoon_vert,
  9964. fragmentShader: ShaderChunk.meshtoon_frag
  9965. },
  9966. matcap: {
  9967. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  9968. matcap: {
  9969. value: null
  9970. }
  9971. }]),
  9972. vertexShader: ShaderChunk.meshmatcap_vert,
  9973. fragmentShader: ShaderChunk.meshmatcap_frag
  9974. },
  9975. points: {
  9976. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  9977. vertexShader: ShaderChunk.points_vert,
  9978. fragmentShader: ShaderChunk.points_frag
  9979. },
  9980. dashed: {
  9981. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  9982. scale: {
  9983. value: 1
  9984. },
  9985. dashSize: {
  9986. value: 1
  9987. },
  9988. totalSize: {
  9989. value: 2
  9990. }
  9991. }]),
  9992. vertexShader: ShaderChunk.linedashed_vert,
  9993. fragmentShader: ShaderChunk.linedashed_frag
  9994. },
  9995. depth: {
  9996. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  9997. vertexShader: ShaderChunk.depth_vert,
  9998. fragmentShader: ShaderChunk.depth_frag
  9999. },
  10000. normal: {
  10001. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  10002. opacity: {
  10003. value: 1.0
  10004. }
  10005. }]),
  10006. vertexShader: ShaderChunk.normal_vert,
  10007. fragmentShader: ShaderChunk.normal_frag
  10008. },
  10009. sprite: {
  10010. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  10011. vertexShader: ShaderChunk.sprite_vert,
  10012. fragmentShader: ShaderChunk.sprite_frag
  10013. },
  10014. background: {
  10015. uniforms: {
  10016. uvTransform: {
  10017. value: new Matrix3()
  10018. },
  10019. t2D: {
  10020. value: null
  10021. }
  10022. },
  10023. vertexShader: ShaderChunk.background_vert,
  10024. fragmentShader: ShaderChunk.background_frag
  10025. },
  10026. /* -------------------------------------------------------------------------
  10027. // Cube map shader
  10028. ------------------------------------------------------------------------- */
  10029. cube: {
  10030. uniforms: mergeUniforms([UniformsLib.envmap, {
  10031. opacity: {
  10032. value: 1.0
  10033. }
  10034. }]),
  10035. vertexShader: ShaderChunk.cube_vert,
  10036. fragmentShader: ShaderChunk.cube_frag
  10037. },
  10038. equirect: {
  10039. uniforms: {
  10040. tEquirect: {
  10041. value: null
  10042. }
  10043. },
  10044. vertexShader: ShaderChunk.equirect_vert,
  10045. fragmentShader: ShaderChunk.equirect_frag
  10046. },
  10047. distanceRGBA: {
  10048. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  10049. referencePosition: {
  10050. value: new Vector3()
  10051. },
  10052. nearDistance: {
  10053. value: 1
  10054. },
  10055. farDistance: {
  10056. value: 1000
  10057. }
  10058. }]),
  10059. vertexShader: ShaderChunk.distanceRGBA_vert,
  10060. fragmentShader: ShaderChunk.distanceRGBA_frag
  10061. },
  10062. shadow: {
  10063. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  10064. color: {
  10065. value: new Color(0x00000)
  10066. },
  10067. opacity: {
  10068. value: 1.0
  10069. }
  10070. }]),
  10071. vertexShader: ShaderChunk.shadow_vert,
  10072. fragmentShader: ShaderChunk.shadow_frag
  10073. }
  10074. };
  10075. exports.ShaderLib = ShaderLib;
  10076. ShaderLib.physical = {
  10077. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  10078. clearcoat: {
  10079. value: 0
  10080. },
  10081. clearcoatMap: {
  10082. value: null
  10083. },
  10084. clearcoatRoughness: {
  10085. value: 0
  10086. },
  10087. clearcoatRoughnessMap: {
  10088. value: null
  10089. },
  10090. clearcoatNormalScale: {
  10091. value: new Vector2(1, 1)
  10092. },
  10093. clearcoatNormalMap: {
  10094. value: null
  10095. },
  10096. sheen: {
  10097. value: new Color(0x000000)
  10098. },
  10099. transparency: {
  10100. value: 0
  10101. }
  10102. }]),
  10103. vertexShader: ShaderChunk.meshphysical_vert,
  10104. fragmentShader: ShaderChunk.meshphysical_frag
  10105. };
  10106. /**
  10107. * @author mrdoob / http://mrdoob.com/
  10108. */
  10109. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  10110. var clearColor = new Color(0x000000);
  10111. var clearAlpha = 0;
  10112. var planeMesh;
  10113. var boxMesh;
  10114. var currentBackground = null;
  10115. var currentBackgroundVersion = 0;
  10116. var currentTonemapping = null;
  10117. function render(renderList, scene, camera, forceClear) {
  10118. var background = scene.background; // Ignore background in AR
  10119. // TODO: Reconsider this.
  10120. var xr = renderer.xr;
  10121. var session = xr.getSession && xr.getSession();
  10122. if (session && session.environmentBlendMode === 'additive') {
  10123. background = null;
  10124. }
  10125. if (background === null) {
  10126. setClear(clearColor, clearAlpha);
  10127. } else if (background && background.isColor) {
  10128. setClear(background, 1);
  10129. forceClear = true;
  10130. }
  10131. if (renderer.autoClear || forceClear) {
  10132. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  10133. }
  10134. if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
  10135. if (boxMesh === undefined) {
  10136. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  10137. type: 'BackgroundCubeMaterial',
  10138. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  10139. vertexShader: ShaderLib.cube.vertexShader,
  10140. fragmentShader: ShaderLib.cube.fragmentShader,
  10141. side: BackSide,
  10142. depthTest: false,
  10143. depthWrite: false,
  10144. fog: false
  10145. }));
  10146. boxMesh.geometry.deleteAttribute('normal');
  10147. boxMesh.geometry.deleteAttribute('uv');
  10148. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  10149. this.matrixWorld.copyPosition(camera.matrixWorld);
  10150. }; // enable code injection for non-built-in material
  10151. Object.defineProperty(boxMesh.material, 'envMap', {
  10152. get: function () {
  10153. return this.uniforms.envMap.value;
  10154. }
  10155. });
  10156. objects.update(boxMesh);
  10157. }
  10158. var texture = background.isWebGLCubeRenderTarget ? background.texture : background;
  10159. boxMesh.material.uniforms.envMap.value = texture;
  10160. boxMesh.material.uniforms.flipEnvMap.value = texture.isCubeTexture ? -1 : 1;
  10161. if (currentBackground !== background || currentBackgroundVersion !== texture.version || currentTonemapping !== renderer.toneMapping) {
  10162. boxMesh.material.needsUpdate = true;
  10163. currentBackground = background;
  10164. currentBackgroundVersion = texture.version;
  10165. currentTonemapping = renderer.toneMapping;
  10166. } // push to the pre-sorted opaque render list
  10167. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  10168. } else if (background && background.isTexture) {
  10169. if (planeMesh === undefined) {
  10170. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  10171. type: 'BackgroundMaterial',
  10172. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  10173. vertexShader: ShaderLib.background.vertexShader,
  10174. fragmentShader: ShaderLib.background.fragmentShader,
  10175. side: FrontSide,
  10176. depthTest: false,
  10177. depthWrite: false,
  10178. fog: false
  10179. }));
  10180. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  10181. Object.defineProperty(planeMesh.material, 'map', {
  10182. get: function () {
  10183. return this.uniforms.t2D.value;
  10184. }
  10185. });
  10186. objects.update(planeMesh);
  10187. }
  10188. planeMesh.material.uniforms.t2D.value = background;
  10189. if (background.matrixAutoUpdate === true) {
  10190. background.updateMatrix();
  10191. }
  10192. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  10193. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  10194. planeMesh.material.needsUpdate = true;
  10195. currentBackground = background;
  10196. currentBackgroundVersion = background.version;
  10197. currentTonemapping = renderer.toneMapping;
  10198. } // push to the pre-sorted opaque render list
  10199. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  10200. }
  10201. }
  10202. function setClear(color, alpha) {
  10203. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  10204. }
  10205. return {
  10206. getClearColor: function () {
  10207. return clearColor;
  10208. },
  10209. setClearColor: function (color, alpha) {
  10210. clearColor.set(color);
  10211. clearAlpha = alpha !== undefined ? alpha : 1;
  10212. setClear(clearColor, clearAlpha);
  10213. },
  10214. getClearAlpha: function () {
  10215. return clearAlpha;
  10216. },
  10217. setClearAlpha: function (alpha) {
  10218. clearAlpha = alpha;
  10219. setClear(clearColor, clearAlpha);
  10220. },
  10221. render: render
  10222. };
  10223. }
  10224. /**
  10225. * @author mrdoob / http://mrdoob.com/
  10226. */
  10227. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  10228. var isWebGL2 = capabilities.isWebGL2;
  10229. var mode;
  10230. function setMode(value) {
  10231. mode = value;
  10232. }
  10233. function render(start, count) {
  10234. gl.drawArrays(mode, start, count);
  10235. info.update(count, mode);
  10236. }
  10237. function renderInstances(geometry, start, count, primcount) {
  10238. if (primcount === 0) return;
  10239. var extension, methodName;
  10240. if (isWebGL2) {
  10241. extension = gl;
  10242. methodName = 'drawArraysInstanced';
  10243. } else {
  10244. extension = extensions.get('ANGLE_instanced_arrays');
  10245. methodName = 'drawArraysInstancedANGLE';
  10246. if (extension === null) {
  10247. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10248. return;
  10249. }
  10250. }
  10251. extension[methodName](mode, start, count, primcount);
  10252. info.update(count, mode, primcount);
  10253. } //
  10254. this.setMode = setMode;
  10255. this.render = render;
  10256. this.renderInstances = renderInstances;
  10257. }
  10258. /**
  10259. * @author mrdoob / http://mrdoob.com/
  10260. */
  10261. function WebGLCapabilities(gl, extensions, parameters) {
  10262. var maxAnisotropy;
  10263. function getMaxAnisotropy() {
  10264. if (maxAnisotropy !== undefined) return maxAnisotropy;
  10265. var extension = extensions.get('EXT_texture_filter_anisotropic');
  10266. if (extension !== null) {
  10267. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  10268. } else {
  10269. maxAnisotropy = 0;
  10270. }
  10271. return maxAnisotropy;
  10272. }
  10273. function getMaxPrecision(precision) {
  10274. if (precision === 'highp') {
  10275. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  10276. return 'highp';
  10277. }
  10278. precision = 'mediump';
  10279. }
  10280. if (precision === 'mediump') {
  10281. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  10282. return 'mediump';
  10283. }
  10284. }
  10285. return 'lowp';
  10286. }
  10287. /* eslint-disable no-undef */
  10288. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  10289. /* eslint-enable no-undef */
  10290. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  10291. var maxPrecision = getMaxPrecision(precision);
  10292. if (maxPrecision !== precision) {
  10293. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  10294. precision = maxPrecision;
  10295. }
  10296. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  10297. var maxTextures = gl.getParameter(34930);
  10298. var maxVertexTextures = gl.getParameter(35660);
  10299. var maxTextureSize = gl.getParameter(3379);
  10300. var maxCubemapSize = gl.getParameter(34076);
  10301. var maxAttributes = gl.getParameter(34921);
  10302. var maxVertexUniforms = gl.getParameter(36347);
  10303. var maxVaryings = gl.getParameter(36348);
  10304. var maxFragmentUniforms = gl.getParameter(36349);
  10305. var vertexTextures = maxVertexTextures > 0;
  10306. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  10307. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  10308. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  10309. return {
  10310. isWebGL2: isWebGL2,
  10311. getMaxAnisotropy: getMaxAnisotropy,
  10312. getMaxPrecision: getMaxPrecision,
  10313. precision: precision,
  10314. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10315. maxTextures: maxTextures,
  10316. maxVertexTextures: maxVertexTextures,
  10317. maxTextureSize: maxTextureSize,
  10318. maxCubemapSize: maxCubemapSize,
  10319. maxAttributes: maxAttributes,
  10320. maxVertexUniforms: maxVertexUniforms,
  10321. maxVaryings: maxVaryings,
  10322. maxFragmentUniforms: maxFragmentUniforms,
  10323. vertexTextures: vertexTextures,
  10324. floatFragmentTextures: floatFragmentTextures,
  10325. floatVertexTextures: floatVertexTextures,
  10326. maxSamples: maxSamples
  10327. };
  10328. }
  10329. /**
  10330. * @author tschw
  10331. */
  10332. function WebGLClipping() {
  10333. var scope = this,
  10334. globalState = null,
  10335. numGlobalPlanes = 0,
  10336. localClippingEnabled = false,
  10337. renderingShadows = false,
  10338. plane = new Plane(),
  10339. viewNormalMatrix = new Matrix3(),
  10340. uniform = {
  10341. value: null,
  10342. needsUpdate: false
  10343. };
  10344. this.uniform = uniform;
  10345. this.numPlanes = 0;
  10346. this.numIntersection = 0;
  10347. this.init = function (planes, enableLocalClipping, camera) {
  10348. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  10349. // run another frame in order to reset the state:
  10350. numGlobalPlanes !== 0 || localClippingEnabled;
  10351. localClippingEnabled = enableLocalClipping;
  10352. globalState = projectPlanes(planes, camera, 0);
  10353. numGlobalPlanes = planes.length;
  10354. return enabled;
  10355. };
  10356. this.beginShadows = function () {
  10357. renderingShadows = true;
  10358. projectPlanes(null);
  10359. };
  10360. this.endShadows = function () {
  10361. renderingShadows = false;
  10362. resetGlobalState();
  10363. };
  10364. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  10365. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  10366. // there's no local clipping
  10367. if (renderingShadows) {
  10368. // there's no global clipping
  10369. projectPlanes(null);
  10370. } else {
  10371. resetGlobalState();
  10372. }
  10373. } else {
  10374. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  10375. lGlobal = nGlobal * 4,
  10376. dstArray = cache.clippingState || null;
  10377. uniform.value = dstArray; // ensure unique state
  10378. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  10379. for (var i = 0; i !== lGlobal; ++i) {
  10380. dstArray[i] = globalState[i];
  10381. }
  10382. cache.clippingState = dstArray;
  10383. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  10384. this.numPlanes += nGlobal;
  10385. }
  10386. };
  10387. function resetGlobalState() {
  10388. if (uniform.value !== globalState) {
  10389. uniform.value = globalState;
  10390. uniform.needsUpdate = numGlobalPlanes > 0;
  10391. }
  10392. scope.numPlanes = numGlobalPlanes;
  10393. scope.numIntersection = 0;
  10394. }
  10395. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  10396. var nPlanes = planes !== null ? planes.length : 0,
  10397. dstArray = null;
  10398. if (nPlanes !== 0) {
  10399. dstArray = uniform.value;
  10400. if (skipTransform !== true || dstArray === null) {
  10401. var flatSize = dstOffset + nPlanes * 4,
  10402. viewMatrix = camera.matrixWorldInverse;
  10403. viewNormalMatrix.getNormalMatrix(viewMatrix);
  10404. if (dstArray === null || dstArray.length < flatSize) {
  10405. dstArray = new Float32Array(flatSize);
  10406. }
  10407. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  10408. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  10409. plane.normal.toArray(dstArray, i4);
  10410. dstArray[i4 + 3] = plane.constant;
  10411. }
  10412. }
  10413. uniform.value = dstArray;
  10414. uniform.needsUpdate = true;
  10415. }
  10416. scope.numPlanes = nPlanes;
  10417. scope.numIntersection = 0;
  10418. return dstArray;
  10419. }
  10420. }
  10421. /**
  10422. * @author mrdoob / http://mrdoob.com/
  10423. */
  10424. function WebGLExtensions(gl) {
  10425. var extensions = {};
  10426. return {
  10427. get: function (name) {
  10428. if (extensions[name] !== undefined) {
  10429. return extensions[name];
  10430. }
  10431. var extension;
  10432. switch (name) {
  10433. case 'WEBGL_depth_texture':
  10434. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10435. break;
  10436. case 'EXT_texture_filter_anisotropic':
  10437. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10438. break;
  10439. case 'WEBGL_compressed_texture_s3tc':
  10440. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10441. break;
  10442. case 'WEBGL_compressed_texture_pvrtc':
  10443. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10444. break;
  10445. default:
  10446. extension = gl.getExtension(name);
  10447. }
  10448. if (extension === null) {
  10449. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10450. }
  10451. extensions[name] = extension;
  10452. return extension;
  10453. }
  10454. };
  10455. }
  10456. /**
  10457. * @author mrdoob / http://mrdoob.com/
  10458. */
  10459. function WebGLGeometries(gl, attributes, info) {
  10460. var geometries = new WeakMap();
  10461. var wireframeAttributes = new WeakMap();
  10462. function onGeometryDispose(event) {
  10463. var geometry = event.target;
  10464. var buffergeometry = geometries.get(geometry);
  10465. if (buffergeometry.index !== null) {
  10466. attributes.remove(buffergeometry.index);
  10467. }
  10468. for (var name in buffergeometry.attributes) {
  10469. attributes.remove(buffergeometry.attributes[name]);
  10470. }
  10471. geometry.removeEventListener('dispose', onGeometryDispose);
  10472. geometries.delete(geometry);
  10473. var attribute = wireframeAttributes.get(buffergeometry);
  10474. if (attribute) {
  10475. attributes.remove(attribute);
  10476. wireframeAttributes.delete(buffergeometry);
  10477. } //
  10478. info.memory.geometries--;
  10479. }
  10480. function get(object, geometry) {
  10481. var buffergeometry = geometries.get(geometry);
  10482. if (buffergeometry) return buffergeometry;
  10483. geometry.addEventListener('dispose', onGeometryDispose);
  10484. if (geometry.isBufferGeometry) {
  10485. buffergeometry = geometry;
  10486. } else if (geometry.isGeometry) {
  10487. if (geometry._bufferGeometry === undefined) {
  10488. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  10489. }
  10490. buffergeometry = geometry._bufferGeometry;
  10491. }
  10492. geometries.set(geometry, buffergeometry);
  10493. info.memory.geometries++;
  10494. return buffergeometry;
  10495. }
  10496. function update(geometry) {
  10497. var index = geometry.index;
  10498. var geometryAttributes = geometry.attributes;
  10499. if (index !== null) {
  10500. attributes.update(index, 34963);
  10501. }
  10502. for (var name in geometryAttributes) {
  10503. attributes.update(geometryAttributes[name], 34962);
  10504. } // morph targets
  10505. var morphAttributes = geometry.morphAttributes;
  10506. for (var name in morphAttributes) {
  10507. var array = morphAttributes[name];
  10508. for (var i = 0, l = array.length; i < l; i++) {
  10509. attributes.update(array[i], 34962);
  10510. }
  10511. }
  10512. }
  10513. function updateWireframeAttribute(geometry) {
  10514. var indices = [];
  10515. var geometryIndex = geometry.index;
  10516. var geometryPosition = geometry.attributes.position;
  10517. var version = 0;
  10518. if (geometryIndex !== null) {
  10519. var array = geometryIndex.array;
  10520. version = geometryIndex.version;
  10521. for (var i = 0, l = array.length; i < l; i += 3) {
  10522. var a = array[i + 0];
  10523. var b = array[i + 1];
  10524. var c = array[i + 2];
  10525. indices.push(a, b, b, c, c, a);
  10526. }
  10527. } else {
  10528. var array = geometryPosition.array;
  10529. version = geometryPosition.version;
  10530. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10531. var a = i + 0;
  10532. var b = i + 1;
  10533. var c = i + 2;
  10534. indices.push(a, b, b, c, c, a);
  10535. }
  10536. }
  10537. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10538. attribute.version = version;
  10539. attributes.update(attribute, 34963); //
  10540. var previousAttribute = wireframeAttributes.get(geometry);
  10541. if (previousAttribute) attributes.remove(previousAttribute); //
  10542. wireframeAttributes.set(geometry, attribute);
  10543. }
  10544. function getWireframeAttribute(geometry) {
  10545. var currentAttribute = wireframeAttributes.get(geometry);
  10546. if (currentAttribute) {
  10547. var geometryIndex = geometry.index;
  10548. if (geometryIndex !== null) {
  10549. // if the attribute is obsolete, create a new one
  10550. if (currentAttribute.version < geometryIndex.version) {
  10551. updateWireframeAttribute(geometry);
  10552. }
  10553. }
  10554. } else {
  10555. updateWireframeAttribute(geometry);
  10556. }
  10557. return wireframeAttributes.get(geometry);
  10558. }
  10559. return {
  10560. get: get,
  10561. update: update,
  10562. getWireframeAttribute: getWireframeAttribute
  10563. };
  10564. }
  10565. /**
  10566. * @author mrdoob / http://mrdoob.com/
  10567. */
  10568. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10569. var isWebGL2 = capabilities.isWebGL2;
  10570. var mode;
  10571. function setMode(value) {
  10572. mode = value;
  10573. }
  10574. var type, bytesPerElement;
  10575. function setIndex(value) {
  10576. type = value.type;
  10577. bytesPerElement = value.bytesPerElement;
  10578. }
  10579. function render(start, count) {
  10580. gl.drawElements(mode, count, type, start * bytesPerElement);
  10581. info.update(count, mode);
  10582. }
  10583. function renderInstances(geometry, start, count, primcount) {
  10584. if (primcount === 0) return;
  10585. var extension, methodName;
  10586. if (isWebGL2) {
  10587. extension = gl;
  10588. methodName = 'drawElementsInstanced';
  10589. } else {
  10590. extension = extensions.get('ANGLE_instanced_arrays');
  10591. methodName = 'drawElementsInstancedANGLE';
  10592. if (extension === null) {
  10593. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10594. return;
  10595. }
  10596. }
  10597. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10598. info.update(count, mode, primcount);
  10599. } //
  10600. this.setMode = setMode;
  10601. this.setIndex = setIndex;
  10602. this.render = render;
  10603. this.renderInstances = renderInstances;
  10604. }
  10605. /**
  10606. * @author Mugen87 / https://github.com/Mugen87
  10607. */
  10608. function WebGLInfo(gl) {
  10609. var memory = {
  10610. geometries: 0,
  10611. textures: 0
  10612. };
  10613. var render = {
  10614. frame: 0,
  10615. calls: 0,
  10616. triangles: 0,
  10617. points: 0,
  10618. lines: 0
  10619. };
  10620. function update(count, mode, instanceCount) {
  10621. instanceCount = instanceCount || 1;
  10622. render.calls++;
  10623. switch (mode) {
  10624. case 4:
  10625. render.triangles += instanceCount * (count / 3);
  10626. break;
  10627. case 1:
  10628. render.lines += instanceCount * (count / 2);
  10629. break;
  10630. case 3:
  10631. render.lines += instanceCount * (count - 1);
  10632. break;
  10633. case 2:
  10634. render.lines += instanceCount * count;
  10635. break;
  10636. case 0:
  10637. render.points += instanceCount * count;
  10638. break;
  10639. default:
  10640. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10641. break;
  10642. }
  10643. }
  10644. function reset() {
  10645. render.frame++;
  10646. render.calls = 0;
  10647. render.triangles = 0;
  10648. render.points = 0;
  10649. render.lines = 0;
  10650. }
  10651. return {
  10652. memory: memory,
  10653. render: render,
  10654. programs: null,
  10655. autoReset: true,
  10656. reset: reset,
  10657. update: update
  10658. };
  10659. }
  10660. /**
  10661. * @author mrdoob / http://mrdoob.com/
  10662. */
  10663. function absNumericalSort(a, b) {
  10664. return Math.abs(b[1]) - Math.abs(a[1]);
  10665. }
  10666. function WebGLMorphtargets(gl) {
  10667. var influencesList = {};
  10668. var morphInfluences = new Float32Array(8);
  10669. function update(object, geometry, material, program) {
  10670. var objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10671. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10672. var length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10673. var influences = influencesList[geometry.id];
  10674. if (influences === undefined) {
  10675. // initialise list
  10676. influences = [];
  10677. for (var i = 0; i < length; i++) {
  10678. influences[i] = [i, 0];
  10679. }
  10680. influencesList[geometry.id] = influences;
  10681. }
  10682. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10683. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  10684. for (var i = 0; i < length; i++) {
  10685. var influence = influences[i];
  10686. if (influence[1] !== 0) {
  10687. if (morphTargets) geometry.deleteAttribute('morphTarget' + i);
  10688. if (morphNormals) geometry.deleteAttribute('morphNormal' + i);
  10689. }
  10690. } // Collect influences
  10691. for (var i = 0; i < length; i++) {
  10692. var influence = influences[i];
  10693. influence[0] = i;
  10694. influence[1] = objectInfluences[i];
  10695. }
  10696. influences.sort(absNumericalSort); // Add morphAttributes
  10697. var morphInfluencesSum = 0;
  10698. for (var i = 0; i < 8; i++) {
  10699. var influence = influences[i];
  10700. if (influence) {
  10701. var index = influence[0];
  10702. var value = influence[1];
  10703. if (value) {
  10704. if (morphTargets) geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10705. if (morphNormals) geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10706. morphInfluences[i] = value;
  10707. morphInfluencesSum += value;
  10708. continue;
  10709. }
  10710. }
  10711. morphInfluences[i] = 0;
  10712. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10713. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10714. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10715. var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10716. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10717. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10718. }
  10719. return {
  10720. update: update
  10721. };
  10722. }
  10723. /**
  10724. * @author mrdoob / http://mrdoob.com/
  10725. */
  10726. function WebGLObjects(gl, geometries, attributes, info) {
  10727. var updateMap = new WeakMap();
  10728. function update(object) {
  10729. var frame = info.render.frame;
  10730. var geometry = object.geometry;
  10731. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  10732. if (updateMap.get(buffergeometry) !== frame) {
  10733. if (geometry.isGeometry) {
  10734. buffergeometry.updateFromObject(object);
  10735. }
  10736. geometries.update(buffergeometry);
  10737. updateMap.set(buffergeometry, frame);
  10738. }
  10739. if (object.isInstancedMesh) {
  10740. attributes.update(object.instanceMatrix, 34962);
  10741. }
  10742. return buffergeometry;
  10743. }
  10744. function dispose() {
  10745. updateMap = new WeakMap();
  10746. }
  10747. return {
  10748. update: update,
  10749. dispose: dispose
  10750. };
  10751. }
  10752. /**
  10753. * @author mrdoob / http://mrdoob.com/
  10754. */
  10755. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  10756. images = images !== undefined ? images : [];
  10757. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  10758. format = format !== undefined ? format : RGBFormat;
  10759. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  10760. this.flipY = false;
  10761. }
  10762. CubeTexture.prototype = Object.create(Texture.prototype);
  10763. CubeTexture.prototype.constructor = CubeTexture;
  10764. CubeTexture.prototype.isCubeTexture = true;
  10765. Object.defineProperty(CubeTexture.prototype, 'images', {
  10766. get: function () {
  10767. return this.image;
  10768. },
  10769. set: function (value) {
  10770. this.image = value;
  10771. }
  10772. });
  10773. /**
  10774. * @author Takahiro https://github.com/takahirox
  10775. */
  10776. function DataTexture2DArray(data, width, height, depth) {
  10777. Texture.call(this, null);
  10778. this.image = {
  10779. data: data || null,
  10780. width: width || 1,
  10781. height: height || 1,
  10782. depth: depth || 1
  10783. };
  10784. this.magFilter = NearestFilter;
  10785. this.minFilter = NearestFilter;
  10786. this.wrapR = ClampToEdgeWrapping;
  10787. this.generateMipmaps = false;
  10788. this.flipY = false;
  10789. this.needsUpdate = true;
  10790. }
  10791. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  10792. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10793. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10794. /**
  10795. * @author Artur Trzesiok
  10796. */
  10797. function DataTexture3D(data, width, height, depth) {
  10798. // We're going to add .setXXX() methods for setting properties later.
  10799. // Users can still set in DataTexture3D directly.
  10800. //
  10801. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  10802. // texture.anisotropy = 16;
  10803. //
  10804. // See #14839
  10805. Texture.call(this, null);
  10806. this.image = {
  10807. data: data || null,
  10808. width: width || 1,
  10809. height: height || 1,
  10810. depth: depth || 1
  10811. };
  10812. this.magFilter = NearestFilter;
  10813. this.minFilter = NearestFilter;
  10814. this.wrapR = ClampToEdgeWrapping;
  10815. this.generateMipmaps = false;
  10816. this.flipY = false;
  10817. this.needsUpdate = true;
  10818. }
  10819. DataTexture3D.prototype = Object.create(Texture.prototype);
  10820. DataTexture3D.prototype.constructor = DataTexture3D;
  10821. DataTexture3D.prototype.isDataTexture3D = true;
  10822. /**
  10823. * @author tschw
  10824. * @author Mugen87 / https://github.com/Mugen87
  10825. * @author mrdoob / http://mrdoob.com/
  10826. *
  10827. * Uniforms of a program.
  10828. * Those form a tree structure with a special top-level container for the root,
  10829. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10830. *
  10831. *
  10832. * Properties of inner nodes including the top-level container:
  10833. *
  10834. * .seq - array of nested uniforms
  10835. * .map - nested uniforms by name
  10836. *
  10837. *
  10838. * Methods of all nodes except the top-level container:
  10839. *
  10840. * .setValue( gl, value, [textures] )
  10841. *
  10842. * uploads a uniform value(s)
  10843. * the 'textures' parameter is needed for sampler uniforms
  10844. *
  10845. *
  10846. * Static methods of the top-level container (textures factorizations):
  10847. *
  10848. * .upload( gl, seq, values, textures )
  10849. *
  10850. * sets uniforms in 'seq' to 'values[id].value'
  10851. *
  10852. * .seqWithValue( seq, values ) : filteredSeq
  10853. *
  10854. * filters 'seq' entries with corresponding entry in values
  10855. *
  10856. *
  10857. * Methods of the top-level container (textures factorizations):
  10858. *
  10859. * .setValue( gl, name, value, textures )
  10860. *
  10861. * sets uniform with name 'name' to 'value'
  10862. *
  10863. * .setOptional( gl, obj, prop )
  10864. *
  10865. * like .set for an optional property of the object
  10866. *
  10867. */
  10868. var emptyTexture = new Texture();
  10869. var emptyTexture2dArray = new DataTexture2DArray();
  10870. var emptyTexture3d = new DataTexture3D();
  10871. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10872. // Array Caches (provide typed arrays for temporary by size)
  10873. var arrayCacheF32 = [];
  10874. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10875. var mat4array = new Float32Array(16);
  10876. var mat3array = new Float32Array(9);
  10877. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10878. function flatten(array, nBlocks, blockSize) {
  10879. var firstElem = array[0];
  10880. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10881. // see http://jacksondunstan.com/articles/983
  10882. var n = nBlocks * blockSize,
  10883. r = arrayCacheF32[n];
  10884. if (r === undefined) {
  10885. r = new Float32Array(n);
  10886. arrayCacheF32[n] = r;
  10887. }
  10888. if (nBlocks !== 0) {
  10889. firstElem.toArray(r, 0);
  10890. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  10891. offset += blockSize;
  10892. array[i].toArray(r, offset);
  10893. }
  10894. }
  10895. return r;
  10896. }
  10897. function arraysEqual(a, b) {
  10898. if (a.length !== b.length) return false;
  10899. for (var i = 0, l = a.length; i < l; i++) {
  10900. if (a[i] !== b[i]) return false;
  10901. }
  10902. return true;
  10903. }
  10904. function copyArray(a, b) {
  10905. for (var i = 0, l = b.length; i < l; i++) {
  10906. a[i] = b[i];
  10907. }
  10908. } // Texture unit allocation
  10909. function allocTexUnits(textures, n) {
  10910. var r = arrayCacheI32[n];
  10911. if (r === undefined) {
  10912. r = new Int32Array(n);
  10913. arrayCacheI32[n] = r;
  10914. }
  10915. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  10916. return r;
  10917. } // --- Setters ---
  10918. // Note: Defining these methods externally, because they come in a bunch
  10919. // and this way their names minify.
  10920. // Single scalar
  10921. function setValueV1f(gl, v) {
  10922. var cache = this.cache;
  10923. if (cache[0] === v) return;
  10924. gl.uniform1f(this.addr, v);
  10925. cache[0] = v;
  10926. } // Single float vector (from flat array or THREE.VectorN)
  10927. function setValueV2f(gl, v) {
  10928. var cache = this.cache;
  10929. if (v.x !== undefined) {
  10930. if (cache[0] !== v.x || cache[1] !== v.y) {
  10931. gl.uniform2f(this.addr, v.x, v.y);
  10932. cache[0] = v.x;
  10933. cache[1] = v.y;
  10934. }
  10935. } else {
  10936. if (arraysEqual(cache, v)) return;
  10937. gl.uniform2fv(this.addr, v);
  10938. copyArray(cache, v);
  10939. }
  10940. }
  10941. function setValueV3f(gl, v) {
  10942. var cache = this.cache;
  10943. if (v.x !== undefined) {
  10944. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10945. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10946. cache[0] = v.x;
  10947. cache[1] = v.y;
  10948. cache[2] = v.z;
  10949. }
  10950. } else if (v.r !== undefined) {
  10951. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10952. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10953. cache[0] = v.r;
  10954. cache[1] = v.g;
  10955. cache[2] = v.b;
  10956. }
  10957. } else {
  10958. if (arraysEqual(cache, v)) return;
  10959. gl.uniform3fv(this.addr, v);
  10960. copyArray(cache, v);
  10961. }
  10962. }
  10963. function setValueV4f(gl, v) {
  10964. var cache = this.cache;
  10965. if (v.x !== undefined) {
  10966. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10967. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10968. cache[0] = v.x;
  10969. cache[1] = v.y;
  10970. cache[2] = v.z;
  10971. cache[3] = v.w;
  10972. }
  10973. } else {
  10974. if (arraysEqual(cache, v)) return;
  10975. gl.uniform4fv(this.addr, v);
  10976. copyArray(cache, v);
  10977. }
  10978. } // Single matrix (from flat array or MatrixN)
  10979. function setValueM2(gl, v) {
  10980. var cache = this.cache;
  10981. var elements = v.elements;
  10982. if (elements === undefined) {
  10983. if (arraysEqual(cache, v)) return;
  10984. gl.uniformMatrix2fv(this.addr, false, v);
  10985. copyArray(cache, v);
  10986. } else {
  10987. if (arraysEqual(cache, elements)) return;
  10988. mat2array.set(elements);
  10989. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10990. copyArray(cache, elements);
  10991. }
  10992. }
  10993. function setValueM3(gl, v) {
  10994. var cache = this.cache;
  10995. var elements = v.elements;
  10996. if (elements === undefined) {
  10997. if (arraysEqual(cache, v)) return;
  10998. gl.uniformMatrix3fv(this.addr, false, v);
  10999. copyArray(cache, v);
  11000. } else {
  11001. if (arraysEqual(cache, elements)) return;
  11002. mat3array.set(elements);
  11003. gl.uniformMatrix3fv(this.addr, false, mat3array);
  11004. copyArray(cache, elements);
  11005. }
  11006. }
  11007. function setValueM4(gl, v) {
  11008. var cache = this.cache;
  11009. var elements = v.elements;
  11010. if (elements === undefined) {
  11011. if (arraysEqual(cache, v)) return;
  11012. gl.uniformMatrix4fv(this.addr, false, v);
  11013. copyArray(cache, v);
  11014. } else {
  11015. if (arraysEqual(cache, elements)) return;
  11016. mat4array.set(elements);
  11017. gl.uniformMatrix4fv(this.addr, false, mat4array);
  11018. copyArray(cache, elements);
  11019. }
  11020. } // Single texture (2D / Cube)
  11021. function setValueT1(gl, v, textures) {
  11022. var cache = this.cache;
  11023. var unit = textures.allocateTextureUnit();
  11024. if (cache[0] !== unit) {
  11025. gl.uniform1i(this.addr, unit);
  11026. cache[0] = unit;
  11027. }
  11028. textures.safeSetTexture2D(v || emptyTexture, unit);
  11029. }
  11030. function setValueT2DArray1(gl, v, textures) {
  11031. var cache = this.cache;
  11032. var unit = textures.allocateTextureUnit();
  11033. if (cache[0] !== unit) {
  11034. gl.uniform1i(this.addr, unit);
  11035. cache[0] = unit;
  11036. }
  11037. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  11038. }
  11039. function setValueT3D1(gl, v, textures) {
  11040. var cache = this.cache;
  11041. var unit = textures.allocateTextureUnit();
  11042. if (cache[0] !== unit) {
  11043. gl.uniform1i(this.addr, unit);
  11044. cache[0] = unit;
  11045. }
  11046. textures.setTexture3D(v || emptyTexture3d, unit);
  11047. }
  11048. function setValueT6(gl, v, textures) {
  11049. var cache = this.cache;
  11050. var unit = textures.allocateTextureUnit();
  11051. if (cache[0] !== unit) {
  11052. gl.uniform1i(this.addr, unit);
  11053. cache[0] = unit;
  11054. }
  11055. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  11056. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11057. function setValueV1i(gl, v) {
  11058. var cache = this.cache;
  11059. if (cache[0] === v) return;
  11060. gl.uniform1i(this.addr, v);
  11061. cache[0] = v;
  11062. }
  11063. function setValueV2i(gl, v) {
  11064. var cache = this.cache;
  11065. if (arraysEqual(cache, v)) return;
  11066. gl.uniform2iv(this.addr, v);
  11067. copyArray(cache, v);
  11068. }
  11069. function setValueV3i(gl, v) {
  11070. var cache = this.cache;
  11071. if (arraysEqual(cache, v)) return;
  11072. gl.uniform3iv(this.addr, v);
  11073. copyArray(cache, v);
  11074. }
  11075. function setValueV4i(gl, v) {
  11076. var cache = this.cache;
  11077. if (arraysEqual(cache, v)) return;
  11078. gl.uniform4iv(this.addr, v);
  11079. copyArray(cache, v);
  11080. } // uint
  11081. function setValueV1ui(gl, v) {
  11082. var cache = this.cache;
  11083. if (cache[0] === v) return;
  11084. gl.uniform1ui(this.addr, v);
  11085. cache[0] = v;
  11086. } // Helper to pick the right setter for the singular case
  11087. function getSingularSetter(type) {
  11088. switch (type) {
  11089. case 0x1406:
  11090. return setValueV1f;
  11091. // FLOAT
  11092. case 0x8b50:
  11093. return setValueV2f;
  11094. // _VEC2
  11095. case 0x8b51:
  11096. return setValueV3f;
  11097. // _VEC3
  11098. case 0x8b52:
  11099. return setValueV4f;
  11100. // _VEC4
  11101. case 0x8b5a:
  11102. return setValueM2;
  11103. // _MAT2
  11104. case 0x8b5b:
  11105. return setValueM3;
  11106. // _MAT3
  11107. case 0x8b5c:
  11108. return setValueM4;
  11109. // _MAT4
  11110. case 0x1404:
  11111. case 0x8b56:
  11112. return setValueV1i;
  11113. // INT, BOOL
  11114. case 0x8b53:
  11115. case 0x8b57:
  11116. return setValueV2i;
  11117. // _VEC2
  11118. case 0x8b54:
  11119. case 0x8b58:
  11120. return setValueV3i;
  11121. // _VEC3
  11122. case 0x8b55:
  11123. case 0x8b59:
  11124. return setValueV4i;
  11125. // _VEC4
  11126. case 0x1405:
  11127. return setValueV1ui;
  11128. // UINT
  11129. case 0x8b5e: // SAMPLER_2D
  11130. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11131. case 0x8dca: // INT_SAMPLER_2D
  11132. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11133. case 0x8b62:
  11134. // SAMPLER_2D_SHADOW
  11135. return setValueT1;
  11136. case 0x8b5f: // SAMPLER_3D
  11137. case 0x8dcb: // INT_SAMPLER_3D
  11138. case 0x8dd3:
  11139. // UNSIGNED_INT_SAMPLER_3D
  11140. return setValueT3D1;
  11141. case 0x8b60: // SAMPLER_CUBE
  11142. case 0x8dcc: // INT_SAMPLER_CUBE
  11143. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11144. case 0x8dc5:
  11145. // SAMPLER_CUBE_SHADOW
  11146. return setValueT6;
  11147. case 0x8dc1: // SAMPLER_2D_ARRAY
  11148. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11149. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11150. case 0x8dc4:
  11151. // SAMPLER_2D_ARRAY_SHADOW
  11152. return setValueT2DArray1;
  11153. }
  11154. } // Array of scalars
  11155. function setValueV1fArray(gl, v) {
  11156. gl.uniform1fv(this.addr, v);
  11157. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11158. function setValueV1iArray(gl, v) {
  11159. gl.uniform1iv(this.addr, v);
  11160. }
  11161. function setValueV2iArray(gl, v) {
  11162. gl.uniform2iv(this.addr, v);
  11163. }
  11164. function setValueV3iArray(gl, v) {
  11165. gl.uniform3iv(this.addr, v);
  11166. }
  11167. function setValueV4iArray(gl, v) {
  11168. gl.uniform4iv(this.addr, v);
  11169. } // Array of vectors (flat or from THREE classes)
  11170. function setValueV2fArray(gl, v) {
  11171. var data = flatten(v, this.size, 2);
  11172. gl.uniform2fv(this.addr, data);
  11173. }
  11174. function setValueV3fArray(gl, v) {
  11175. var data = flatten(v, this.size, 3);
  11176. gl.uniform3fv(this.addr, data);
  11177. }
  11178. function setValueV4fArray(gl, v) {
  11179. var data = flatten(v, this.size, 4);
  11180. gl.uniform4fv(this.addr, data);
  11181. } // Array of matrices (flat or from THREE clases)
  11182. function setValueM2Array(gl, v) {
  11183. var data = flatten(v, this.size, 4);
  11184. gl.uniformMatrix2fv(this.addr, false, data);
  11185. }
  11186. function setValueM3Array(gl, v) {
  11187. var data = flatten(v, this.size, 9);
  11188. gl.uniformMatrix3fv(this.addr, false, data);
  11189. }
  11190. function setValueM4Array(gl, v) {
  11191. var data = flatten(v, this.size, 16);
  11192. gl.uniformMatrix4fv(this.addr, false, data);
  11193. } // Array of textures (2D / Cube)
  11194. function setValueT1Array(gl, v, textures) {
  11195. var n = v.length;
  11196. var units = allocTexUnits(textures, n);
  11197. gl.uniform1iv(this.addr, units);
  11198. for (var i = 0; i !== n; ++i) {
  11199. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  11200. }
  11201. }
  11202. function setValueT6Array(gl, v, textures) {
  11203. var n = v.length;
  11204. var units = allocTexUnits(textures, n);
  11205. gl.uniform1iv(this.addr, units);
  11206. for (var i = 0; i !== n; ++i) {
  11207. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  11208. }
  11209. } // Helper to pick the right setter for a pure (bottom-level) array
  11210. function getPureArraySetter(type) {
  11211. switch (type) {
  11212. case 0x1406:
  11213. return setValueV1fArray;
  11214. // FLOAT
  11215. case 0x8b50:
  11216. return setValueV2fArray;
  11217. // _VEC2
  11218. case 0x8b51:
  11219. return setValueV3fArray;
  11220. // _VEC3
  11221. case 0x8b52:
  11222. return setValueV4fArray;
  11223. // _VEC4
  11224. case 0x8b5a:
  11225. return setValueM2Array;
  11226. // _MAT2
  11227. case 0x8b5b:
  11228. return setValueM3Array;
  11229. // _MAT3
  11230. case 0x8b5c:
  11231. return setValueM4Array;
  11232. // _MAT4
  11233. case 0x1404:
  11234. case 0x8b56:
  11235. return setValueV1iArray;
  11236. // INT, BOOL
  11237. case 0x8b53:
  11238. case 0x8b57:
  11239. return setValueV2iArray;
  11240. // _VEC2
  11241. case 0x8b54:
  11242. case 0x8b58:
  11243. return setValueV3iArray;
  11244. // _VEC3
  11245. case 0x8b55:
  11246. case 0x8b59:
  11247. return setValueV4iArray;
  11248. // _VEC4
  11249. case 0x8b5e: // SAMPLER_2D
  11250. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11251. case 0x8dca: // INT_SAMPLER_2D
  11252. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11253. case 0x8b62:
  11254. // SAMPLER_2D_SHADOW
  11255. return setValueT1Array;
  11256. case 0x8b60: // SAMPLER_CUBE
  11257. case 0x8dcc: // INT_SAMPLER_CUBE
  11258. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11259. case 0x8dc5:
  11260. // SAMPLER_CUBE_SHADOW
  11261. return setValueT6Array;
  11262. }
  11263. } // --- Uniform Classes ---
  11264. function SingleUniform(id, activeInfo, addr) {
  11265. this.id = id;
  11266. this.addr = addr;
  11267. this.cache = [];
  11268. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11269. }
  11270. function PureArrayUniform(id, activeInfo, addr) {
  11271. this.id = id;
  11272. this.addr = addr;
  11273. this.cache = [];
  11274. this.size = activeInfo.size;
  11275. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11276. }
  11277. PureArrayUniform.prototype.updateCache = function (data) {
  11278. var cache = this.cache;
  11279. if (data instanceof Float32Array && cache.length !== data.length) {
  11280. this.cache = new Float32Array(data.length);
  11281. }
  11282. copyArray(cache, data);
  11283. };
  11284. function StructuredUniform(id) {
  11285. this.id = id;
  11286. this.seq = [];
  11287. this.map = {};
  11288. }
  11289. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  11290. var seq = this.seq;
  11291. for (var i = 0, n = seq.length; i !== n; ++i) {
  11292. var u = seq[i];
  11293. u.setValue(gl, value[u.id], textures);
  11294. }
  11295. }; // --- Top-level ---
  11296. // Parser - builds up the property tree from the path strings
  11297. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  11298. // - the identifier (member name or array index)
  11299. // - followed by an optional right bracket (found when array index)
  11300. // - followed by an optional left bracket or dot (type of subscript)
  11301. //
  11302. // Note: These portions can be read in a non-overlapping fashion and
  11303. // allow straightforward parsing of the hierarchy that WebGL encodes
  11304. // in the uniform names.
  11305. function addUniform(container, uniformObject) {
  11306. container.seq.push(uniformObject);
  11307. container.map[uniformObject.id] = uniformObject;
  11308. }
  11309. function parseUniform(activeInfo, addr, container) {
  11310. var path = activeInfo.name,
  11311. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11312. RePathPart.lastIndex = 0;
  11313. while (true) {
  11314. var match = RePathPart.exec(path),
  11315. matchEnd = RePathPart.lastIndex,
  11316. id = match[1],
  11317. idIsIndex = match[2] === ']',
  11318. subscript = match[3];
  11319. if (idIsIndex) id = id | 0; // convert to integer
  11320. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11321. // bare name or "pure" bottom-level array "[0]" suffix
  11322. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11323. break;
  11324. } else {
  11325. // step into inner node / create it in case it doesn't exist
  11326. var map = container.map,
  11327. next = map[id];
  11328. if (next === undefined) {
  11329. next = new StructuredUniform(id);
  11330. addUniform(container, next);
  11331. }
  11332. container = next;
  11333. }
  11334. }
  11335. } // Root Container
  11336. function WebGLUniforms(gl, program) {
  11337. this.seq = [];
  11338. this.map = {};
  11339. var n = gl.getProgramParameter(program, 35718);
  11340. for (var i = 0; i < n; ++i) {
  11341. var info = gl.getActiveUniform(program, i),
  11342. addr = gl.getUniformLocation(program, info.name);
  11343. parseUniform(info, addr, this);
  11344. }
  11345. }
  11346. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11347. var u = this.map[name];
  11348. if (u !== undefined) u.setValue(gl, value, textures);
  11349. };
  11350. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11351. var v = object[name];
  11352. if (v !== undefined) this.setValue(gl, name, v);
  11353. }; // Static interface
  11354. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11355. for (var i = 0, n = seq.length; i !== n; ++i) {
  11356. var u = seq[i],
  11357. v = values[u.id];
  11358. if (v.needsUpdate !== false) {
  11359. // note: always updating when .needsUpdate is undefined
  11360. u.setValue(gl, v.value, textures);
  11361. }
  11362. }
  11363. };
  11364. WebGLUniforms.seqWithValue = function (seq, values) {
  11365. var r = [];
  11366. for (var i = 0, n = seq.length; i !== n; ++i) {
  11367. var u = seq[i];
  11368. if (u.id in values) r.push(u);
  11369. }
  11370. return r;
  11371. };
  11372. /**
  11373. * @author mrdoob / http://mrdoob.com/
  11374. */
  11375. function WebGLShader(gl, type, string) {
  11376. var shader = gl.createShader(type);
  11377. gl.shaderSource(shader, string);
  11378. gl.compileShader(shader);
  11379. return shader;
  11380. }
  11381. /**
  11382. * @author mrdoob / http://mrdoob.com/
  11383. */
  11384. var programIdCount = 0;
  11385. function addLineNumbers(string) {
  11386. var lines = string.split('\n');
  11387. for (var i = 0; i < lines.length; i++) {
  11388. lines[i] = i + 1 + ': ' + lines[i];
  11389. }
  11390. return lines.join('\n');
  11391. }
  11392. function getEncodingComponents(encoding) {
  11393. switch (encoding) {
  11394. case LinearEncoding:
  11395. return ['Linear', '( value )'];
  11396. case sRGBEncoding:
  11397. return ['sRGB', '( value )'];
  11398. case RGBEEncoding:
  11399. return ['RGBE', '( value )'];
  11400. case RGBM7Encoding:
  11401. return ['RGBM', '( value, 7.0 )'];
  11402. case RGBM16Encoding:
  11403. return ['RGBM', '( value, 16.0 )'];
  11404. case RGBDEncoding:
  11405. return ['RGBD', '( value, 256.0 )'];
  11406. case GammaEncoding:
  11407. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11408. case LogLuvEncoding:
  11409. return ['LogLuv', '( value )'];
  11410. default:
  11411. throw new Error('unsupported encoding: ' + encoding);
  11412. }
  11413. }
  11414. function getShaderErrors(gl, shader, type) {
  11415. var status = gl.getShaderParameter(shader, 35713);
  11416. var log = gl.getShaderInfoLog(shader).trim();
  11417. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  11418. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11419. var source = gl.getShaderSource(shader);
  11420. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  11421. }
  11422. function getTexelDecodingFunction(functionName, encoding) {
  11423. var components = getEncodingComponents(encoding);
  11424. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11425. }
  11426. function getTexelEncodingFunction(functionName, encoding) {
  11427. var components = getEncodingComponents(encoding);
  11428. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11429. }
  11430. function getToneMappingFunction(functionName, toneMapping) {
  11431. var toneMappingName;
  11432. switch (toneMapping) {
  11433. case LinearToneMapping:
  11434. toneMappingName = 'Linear';
  11435. break;
  11436. case ReinhardToneMapping:
  11437. toneMappingName = 'Reinhard';
  11438. break;
  11439. case Uncharted2ToneMapping:
  11440. toneMappingName = 'Uncharted2';
  11441. break;
  11442. case CineonToneMapping:
  11443. toneMappingName = 'OptimizedCineon';
  11444. break;
  11445. case ACESFilmicToneMapping:
  11446. toneMappingName = 'ACESFilmic';
  11447. break;
  11448. default:
  11449. throw new Error('unsupported toneMapping: ' + toneMapping);
  11450. }
  11451. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11452. }
  11453. function generateExtensions(parameters) {
  11454. var chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11455. return chunks.filter(filterEmptyLine).join('\n');
  11456. }
  11457. function generateDefines(defines) {
  11458. var chunks = [];
  11459. for (var name in defines) {
  11460. var value = defines[name];
  11461. if (value === false) continue;
  11462. chunks.push('#define ' + name + ' ' + value);
  11463. }
  11464. return chunks.join('\n');
  11465. }
  11466. function fetchAttributeLocations(gl, program) {
  11467. var attributes = {};
  11468. var n = gl.getProgramParameter(program, 35721);
  11469. for (var i = 0; i < n; i++) {
  11470. var info = gl.getActiveAttrib(program, i);
  11471. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11472. attributes[name] = gl.getAttribLocation(program, name);
  11473. }
  11474. return attributes;
  11475. }
  11476. function filterEmptyLine(string) {
  11477. return string !== '';
  11478. }
  11479. function replaceLightNums(string, parameters) {
  11480. 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);
  11481. }
  11482. function replaceClippingPlaneNums(string, parameters) {
  11483. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11484. } // Resolve Includes
  11485. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11486. function resolveIncludes(string) {
  11487. return string.replace(includePattern, includeReplacer);
  11488. }
  11489. function includeReplacer(match, include) {
  11490. var string = ShaderChunk[include];
  11491. if (string === undefined) {
  11492. throw new Error('Can not resolve #include <' + include + '>');
  11493. }
  11494. return resolveIncludes(string);
  11495. } // Unroll Loops
  11496. var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11497. var unrollLoopPattern = /#pragma unroll_loop_start[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}[\s]+?#pragma unroll_loop_end/g;
  11498. function unrollLoops(string) {
  11499. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11500. }
  11501. function deprecatedLoopReplacer(match, start, end, snippet) {
  11502. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11503. return loopReplacer(match, start, end, snippet);
  11504. }
  11505. function loopReplacer(match, start, end, snippet) {
  11506. var string = '';
  11507. for (var i = parseInt(start); i < parseInt(end); i++) {
  11508. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11509. }
  11510. return string;
  11511. } //
  11512. function generatePrecision(parameters) {
  11513. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  11514. if (parameters.precision === "highp") {
  11515. precisionstring += "\n#define HIGH_PRECISION";
  11516. } else if (parameters.precision === "mediump") {
  11517. precisionstring += "\n#define MEDIUM_PRECISION";
  11518. } else if (parameters.precision === "lowp") {
  11519. precisionstring += "\n#define LOW_PRECISION";
  11520. }
  11521. return precisionstring;
  11522. }
  11523. function generateShadowMapTypeDefine(parameters) {
  11524. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11525. if (parameters.shadowMapType === PCFShadowMap) {
  11526. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11527. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11528. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11529. } else if (parameters.shadowMapType === VSMShadowMap) {
  11530. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11531. }
  11532. return shadowMapTypeDefine;
  11533. }
  11534. function generateEnvMapTypeDefine(parameters) {
  11535. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11536. if (parameters.envMap) {
  11537. switch (parameters.envMapMode) {
  11538. case CubeReflectionMapping:
  11539. case CubeRefractionMapping:
  11540. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11541. break;
  11542. case CubeUVReflectionMapping:
  11543. case CubeUVRefractionMapping:
  11544. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11545. break;
  11546. case EquirectangularReflectionMapping:
  11547. case EquirectangularRefractionMapping:
  11548. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  11549. break;
  11550. case SphericalReflectionMapping:
  11551. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  11552. break;
  11553. }
  11554. }
  11555. return envMapTypeDefine;
  11556. }
  11557. function generateEnvMapModeDefine(parameters) {
  11558. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11559. if (parameters.envMap) {
  11560. switch (parameters.envMapMode) {
  11561. case CubeRefractionMapping:
  11562. case EquirectangularRefractionMapping:
  11563. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11564. break;
  11565. }
  11566. }
  11567. return envMapModeDefine;
  11568. }
  11569. function generateEnvMapBlendingDefine(parameters) {
  11570. var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11571. if (parameters.envMap) {
  11572. switch (parameters.combine) {
  11573. case MultiplyOperation:
  11574. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11575. break;
  11576. case MixOperation:
  11577. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11578. break;
  11579. case AddOperation:
  11580. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11581. break;
  11582. }
  11583. }
  11584. return envMapBlendingDefine;
  11585. }
  11586. function WebGLProgram(renderer, cacheKey, parameters) {
  11587. var gl = renderer.getContext();
  11588. var defines = parameters.defines;
  11589. var vertexShader = parameters.vertexShader;
  11590. var fragmentShader = parameters.fragmentShader;
  11591. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11592. var envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11593. var envMapModeDefine = generateEnvMapModeDefine(parameters);
  11594. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11595. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11596. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11597. var customDefines = generateDefines(defines);
  11598. var program = gl.createProgram();
  11599. var prefixVertex, prefixFragment;
  11600. if (parameters.isRawShaderMaterial) {
  11601. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11602. if (prefixVertex.length > 0) {
  11603. prefixVertex += '\n';
  11604. }
  11605. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11606. if (prefixFragment.length > 0) {
  11607. prefixFragment += '\n';
  11608. }
  11609. } else {
  11610. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, 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.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', 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.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', 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.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#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');
  11611. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  11612. '#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.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', 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.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', 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.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', 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
  11613. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding || parameters.lightMapEncoding ? ShaderChunk['encodings_pars_fragment'] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  11614. 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.lightMapEncoding ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', parameters.outputEncoding ? getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding) : '', parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11615. }
  11616. vertexShader = resolveIncludes(vertexShader);
  11617. vertexShader = replaceLightNums(vertexShader, parameters);
  11618. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11619. fragmentShader = resolveIncludes(fragmentShader);
  11620. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11621. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11622. vertexShader = unrollLoops(vertexShader);
  11623. fragmentShader = unrollLoops(fragmentShader);
  11624. if (parameters.isWebGL2 && !parameters.isRawShaderMaterial) {
  11625. var isGLSL3ShaderMaterial = false;
  11626. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  11627. if (parameters.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  11628. isGLSL3ShaderMaterial = true;
  11629. vertexShader = vertexShader.replace(versionRegex, '');
  11630. fragmentShader = fragmentShader.replace(versionRegex, '');
  11631. } // GLSL 3.0 conversion
  11632. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11633. 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;
  11634. }
  11635. var vertexGlsl = prefixVertex + vertexShader;
  11636. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11637. // console.log( '*FRAGMENT*', fragmentGlsl );
  11638. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  11639. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  11640. gl.attachShader(program, glVertexShader);
  11641. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11642. if (parameters.index0AttributeName !== undefined) {
  11643. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11644. } else if (parameters.morphTargets === true) {
  11645. // programs with morphTargets displace position out of attribute 0
  11646. gl.bindAttribLocation(program, 0, 'position');
  11647. }
  11648. gl.linkProgram(program); // check for link errors
  11649. if (renderer.debug.checkShaderErrors) {
  11650. var programLog = gl.getProgramInfoLog(program).trim();
  11651. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11652. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11653. var runnable = true;
  11654. var haveDiagnostics = true;
  11655. if (gl.getProgramParameter(program, 35714) === false) {
  11656. runnable = false;
  11657. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11658. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11659. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  11660. } else if (programLog !== '') {
  11661. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  11662. } else if (vertexLog === '' || fragmentLog === '') {
  11663. haveDiagnostics = false;
  11664. }
  11665. if (haveDiagnostics) {
  11666. this.diagnostics = {
  11667. runnable: runnable,
  11668. programLog: programLog,
  11669. vertexShader: {
  11670. log: vertexLog,
  11671. prefix: prefixVertex
  11672. },
  11673. fragmentShader: {
  11674. log: fragmentLog,
  11675. prefix: prefixFragment
  11676. }
  11677. };
  11678. }
  11679. } // clean up
  11680. gl.detachShader(program, glVertexShader);
  11681. gl.detachShader(program, glFragmentShader);
  11682. gl.deleteShader(glVertexShader);
  11683. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11684. var cachedUniforms;
  11685. this.getUniforms = function () {
  11686. if (cachedUniforms === undefined) {
  11687. cachedUniforms = new WebGLUniforms(gl, program);
  11688. }
  11689. return cachedUniforms;
  11690. }; // set up caching for attribute locations
  11691. var cachedAttributes;
  11692. this.getAttributes = function () {
  11693. if (cachedAttributes === undefined) {
  11694. cachedAttributes = fetchAttributeLocations(gl, program);
  11695. }
  11696. return cachedAttributes;
  11697. }; // free resource
  11698. this.destroy = function () {
  11699. gl.deleteProgram(program);
  11700. this.program = undefined;
  11701. }; //
  11702. this.name = parameters.shaderName;
  11703. this.id = programIdCount++;
  11704. this.cacheKey = cacheKey;
  11705. this.usedTimes = 1;
  11706. this.program = program;
  11707. this.vertexShader = glVertexShader;
  11708. this.fragmentShader = glFragmentShader;
  11709. return this;
  11710. }
  11711. /**
  11712. * @author mrdoob / http://mrdoob.com/
  11713. */
  11714. function WebGLPrograms(renderer, extensions, capabilities) {
  11715. var programs = [];
  11716. var isWebGL2 = capabilities.isWebGL2;
  11717. var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11718. var floatVertexTextures = capabilities.floatVertexTextures;
  11719. var precision = capabilities.precision;
  11720. var maxVertexUniforms = capabilities.maxVertexUniforms;
  11721. var vertexTextures = capabilities.vertexTextures;
  11722. var shaderIDs = {
  11723. MeshDepthMaterial: 'depth',
  11724. MeshDistanceMaterial: 'distanceRGBA',
  11725. MeshNormalMaterial: 'normal',
  11726. MeshBasicMaterial: 'basic',
  11727. MeshLambertMaterial: 'lambert',
  11728. MeshPhongMaterial: 'phong',
  11729. MeshToonMaterial: 'toon',
  11730. MeshStandardMaterial: 'physical',
  11731. MeshPhysicalMaterial: 'physical',
  11732. MeshMatcapMaterial: 'matcap',
  11733. LineBasicMaterial: 'basic',
  11734. LineDashedMaterial: 'dashed',
  11735. PointsMaterial: 'points',
  11736. ShadowMaterial: 'shadow',
  11737. SpriteMaterial: 'sprite'
  11738. };
  11739. var parameterNames = ["precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV", "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen"];
  11740. function getShaderObject(material, shaderID) {
  11741. var shaderobject;
  11742. if (shaderID) {
  11743. var shader = ShaderLib[shaderID];
  11744. shaderobject = {
  11745. name: material.type,
  11746. uniforms: UniformsUtils.clone(shader.uniforms),
  11747. vertexShader: shader.vertexShader,
  11748. fragmentShader: shader.fragmentShader
  11749. };
  11750. } else {
  11751. shaderobject = {
  11752. name: material.type,
  11753. uniforms: material.uniforms,
  11754. vertexShader: material.vertexShader,
  11755. fragmentShader: material.fragmentShader
  11756. };
  11757. }
  11758. return shaderobject;
  11759. }
  11760. function allocateBones(object) {
  11761. var skeleton = object.skeleton;
  11762. var bones = skeleton.bones;
  11763. if (floatVertexTextures) {
  11764. return 1024;
  11765. } else {
  11766. // default for when object is not specified
  11767. // ( for example when prebuilding shader to be used with multiple objects )
  11768. //
  11769. // - leave some extra space for other uniforms
  11770. // - limit here is ANGLE's 254 max uniform vectors
  11771. // (up to 54 should be safe)
  11772. var nVertexUniforms = maxVertexUniforms;
  11773. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11774. var maxBones = Math.min(nVertexMatrices, bones.length);
  11775. if (maxBones < bones.length) {
  11776. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11777. return 0;
  11778. }
  11779. return maxBones;
  11780. }
  11781. }
  11782. function getTextureEncodingFromMap(map) {
  11783. var encoding;
  11784. if (!map) {
  11785. encoding = LinearEncoding;
  11786. } else if (map.isTexture) {
  11787. encoding = map.encoding;
  11788. } else if (map.isWebGLRenderTarget) {
  11789. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  11790. encoding = map.texture.encoding;
  11791. }
  11792. return encoding;
  11793. }
  11794. this.getParameters = function (material, lights, shadows, scene, nClipPlanes, nClipIntersection, object) {
  11795. var fog = scene.fog;
  11796. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  11797. var envMap = material.envMap || environment;
  11798. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11799. // (not to blow over maxLights budget)
  11800. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  11801. if (material.precision !== null) {
  11802. precision = capabilities.getMaxPrecision(material.precision);
  11803. if (precision !== material.precision) {
  11804. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11805. }
  11806. }
  11807. var shaderobject = getShaderObject(material, shaderID);
  11808. material.onBeforeCompile(shaderobject, renderer);
  11809. var currentRenderTarget = renderer.getRenderTarget();
  11810. var parameters = {
  11811. isWebGL2: isWebGL2,
  11812. shaderID: shaderID,
  11813. shaderName: shaderobject.name,
  11814. uniforms: shaderobject.uniforms,
  11815. vertexShader: shaderobject.vertexShader,
  11816. fragmentShader: shaderobject.fragmentShader,
  11817. defines: material.defines,
  11818. isRawShaderMaterial: material.isRawShaderMaterial,
  11819. isShaderMaterial: material.isShaderMaterial,
  11820. precision: precision,
  11821. instancing: object.isInstancedMesh === true,
  11822. supportsVertexTextures: vertexTextures,
  11823. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11824. map: !!material.map,
  11825. mapEncoding: getTextureEncodingFromMap(material.map),
  11826. matcap: !!material.matcap,
  11827. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11828. envMap: !!envMap,
  11829. envMapMode: envMap && envMap.mapping,
  11830. envMapEncoding: getTextureEncodingFromMap(envMap),
  11831. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11832. lightMap: !!material.lightMap,
  11833. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11834. aoMap: !!material.aoMap,
  11835. emissiveMap: !!material.emissiveMap,
  11836. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11837. bumpMap: !!material.bumpMap,
  11838. normalMap: !!material.normalMap,
  11839. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11840. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11841. clearcoatMap: !!material.clearcoatMap,
  11842. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  11843. clearcoatNormalMap: !!material.clearcoatNormalMap,
  11844. displacementMap: !!material.displacementMap,
  11845. roughnessMap: !!material.roughnessMap,
  11846. metalnessMap: !!material.metalnessMap,
  11847. specularMap: !!material.specularMap,
  11848. alphaMap: !!material.alphaMap,
  11849. gradientMap: !!material.gradientMap,
  11850. sheen: !!material.sheen,
  11851. combine: material.combine,
  11852. vertexTangents: material.normalMap && material.vertexTangents,
  11853. vertexColors: material.vertexColors,
  11854. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap,
  11855. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap) && !!material.displacementMap,
  11856. fog: !!fog,
  11857. useFog: material.fog,
  11858. fogExp2: fog && fog.isFogExp2,
  11859. flatShading: material.flatShading,
  11860. sizeAttenuation: material.sizeAttenuation,
  11861. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11862. skinning: material.skinning && maxBones > 0,
  11863. maxBones: maxBones,
  11864. useVertexTexture: floatVertexTextures,
  11865. morphTargets: material.morphTargets,
  11866. morphNormals: material.morphNormals,
  11867. maxMorphTargets: renderer.maxMorphTargets,
  11868. maxMorphNormals: renderer.maxMorphNormals,
  11869. numDirLights: lights.directional.length,
  11870. numPointLights: lights.point.length,
  11871. numSpotLights: lights.spot.length,
  11872. numRectAreaLights: lights.rectArea.length,
  11873. numHemiLights: lights.hemi.length,
  11874. numDirLightShadows: lights.directionalShadowMap.length,
  11875. numPointLightShadows: lights.pointShadowMap.length,
  11876. numSpotLightShadows: lights.spotShadowMap.length,
  11877. numClippingPlanes: nClipPlanes,
  11878. numClipIntersection: nClipIntersection,
  11879. dithering: material.dithering,
  11880. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11881. shadowMapType: renderer.shadowMap.type,
  11882. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11883. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11884. premultipliedAlpha: material.premultipliedAlpha,
  11885. alphaTest: material.alphaTest,
  11886. doubleSided: material.side === DoubleSide,
  11887. flipSided: material.side === BackSide,
  11888. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11889. index0AttributeName: material.index0AttributeName,
  11890. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11891. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11892. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11893. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11894. rendererExtensionFragDepth: isWebGL2 || extensions.get('EXT_frag_depth') !== null,
  11895. rendererExtensionDrawBuffers: isWebGL2 || extensions.get('WEBGL_draw_buffers') !== null,
  11896. rendererExtensionShaderTextureLod: isWebGL2 || extensions.get('EXT_shader_texture_lod') !== null,
  11897. onBeforeCompile: material.onBeforeCompile
  11898. };
  11899. return parameters;
  11900. };
  11901. this.getProgramCacheKey = function (parameters) {
  11902. var array = [];
  11903. if (parameters.shaderID) {
  11904. array.push(parameters.shaderID);
  11905. } else {
  11906. array.push(parameters.fragmentShader);
  11907. array.push(parameters.vertexShader);
  11908. }
  11909. if (parameters.defines !== undefined) {
  11910. for (var name in parameters.defines) {
  11911. array.push(name);
  11912. array.push(parameters.defines[name]);
  11913. }
  11914. }
  11915. if (parameters.isRawShaderMaterial === undefined) {
  11916. for (var i = 0; i < parameterNames.length; i++) {
  11917. array.push(parameters[parameterNames[i]]);
  11918. }
  11919. array.push(renderer.outputEncoding);
  11920. array.push(renderer.gammaFactor);
  11921. }
  11922. array.push(parameters.onBeforeCompile.toString());
  11923. return array.join();
  11924. };
  11925. this.acquireProgram = function (parameters, cacheKey) {
  11926. var program; // Check if code has been already compiled
  11927. for (var p = 0, pl = programs.length; p < pl; p++) {
  11928. var preexistingProgram = programs[p];
  11929. if (preexistingProgram.cacheKey === cacheKey) {
  11930. program = preexistingProgram;
  11931. ++program.usedTimes;
  11932. break;
  11933. }
  11934. }
  11935. if (program === undefined) {
  11936. program = new WebGLProgram(renderer, cacheKey, parameters);
  11937. programs.push(program);
  11938. }
  11939. return program;
  11940. };
  11941. this.releaseProgram = function (program) {
  11942. if (--program.usedTimes === 0) {
  11943. // Remove from unordered set
  11944. var i = programs.indexOf(program);
  11945. programs[i] = programs[programs.length - 1];
  11946. programs.pop(); // Free WebGL resources
  11947. program.destroy();
  11948. }
  11949. }; // Exposed for resource monitoring & error feedback via renderer.info:
  11950. this.programs = programs;
  11951. }
  11952. /**
  11953. * @author fordacious / fordacious.github.io
  11954. */
  11955. function WebGLProperties() {
  11956. var properties = new WeakMap();
  11957. function get(object) {
  11958. var map = properties.get(object);
  11959. if (map === undefined) {
  11960. map = {};
  11961. properties.set(object, map);
  11962. }
  11963. return map;
  11964. }
  11965. function remove(object) {
  11966. properties.delete(object);
  11967. }
  11968. function update(object, key, value) {
  11969. properties.get(object)[key] = value;
  11970. }
  11971. function dispose() {
  11972. properties = new WeakMap();
  11973. }
  11974. return {
  11975. get: get,
  11976. remove: remove,
  11977. update: update,
  11978. dispose: dispose
  11979. };
  11980. }
  11981. /**
  11982. * @author mrdoob / http://mrdoob.com/
  11983. */
  11984. function painterSortStable(a, b) {
  11985. if (a.groupOrder !== b.groupOrder) {
  11986. return a.groupOrder - b.groupOrder;
  11987. } else if (a.renderOrder !== b.renderOrder) {
  11988. return a.renderOrder - b.renderOrder;
  11989. } else if (a.program !== b.program) {
  11990. return a.program.id - b.program.id;
  11991. } else if (a.material.id !== b.material.id) {
  11992. return a.material.id - b.material.id;
  11993. } else if (a.z !== b.z) {
  11994. return a.z - b.z;
  11995. } else {
  11996. return a.id - b.id;
  11997. }
  11998. }
  11999. function reversePainterSortStable(a, b) {
  12000. if (a.groupOrder !== b.groupOrder) {
  12001. return a.groupOrder - b.groupOrder;
  12002. } else if (a.renderOrder !== b.renderOrder) {
  12003. return a.renderOrder - b.renderOrder;
  12004. } else if (a.z !== b.z) {
  12005. return b.z - a.z;
  12006. } else {
  12007. return a.id - b.id;
  12008. }
  12009. }
  12010. function WebGLRenderList() {
  12011. var renderItems = [];
  12012. var renderItemsIndex = 0;
  12013. var opaque = [];
  12014. var transparent = [];
  12015. var defaultProgram = {
  12016. id: -1
  12017. };
  12018. function init() {
  12019. renderItemsIndex = 0;
  12020. opaque.length = 0;
  12021. transparent.length = 0;
  12022. }
  12023. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12024. var renderItem = renderItems[renderItemsIndex];
  12025. if (renderItem === undefined) {
  12026. renderItem = {
  12027. id: object.id,
  12028. object: object,
  12029. geometry: geometry,
  12030. material: material,
  12031. program: material.program || defaultProgram,
  12032. groupOrder: groupOrder,
  12033. renderOrder: object.renderOrder,
  12034. z: z,
  12035. group: group
  12036. };
  12037. renderItems[renderItemsIndex] = renderItem;
  12038. } else {
  12039. renderItem.id = object.id;
  12040. renderItem.object = object;
  12041. renderItem.geometry = geometry;
  12042. renderItem.material = material;
  12043. renderItem.program = material.program || defaultProgram;
  12044. renderItem.groupOrder = groupOrder;
  12045. renderItem.renderOrder = object.renderOrder;
  12046. renderItem.z = z;
  12047. renderItem.group = group;
  12048. }
  12049. renderItemsIndex++;
  12050. return renderItem;
  12051. }
  12052. function push(object, geometry, material, groupOrder, z, group) {
  12053. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12054. (material.transparent === true ? transparent : opaque).push(renderItem);
  12055. }
  12056. function unshift(object, geometry, material, groupOrder, z, group) {
  12057. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12058. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  12059. }
  12060. function sort(customOpaqueSort, customTransparentSort) {
  12061. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12062. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12063. }
  12064. function finish() {
  12065. // Clear references from inactive renderItems in the list
  12066. for (var i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12067. var renderItem = renderItems[i];
  12068. if (renderItem.id === null) break;
  12069. renderItem.id = null;
  12070. renderItem.object = null;
  12071. renderItem.geometry = null;
  12072. renderItem.material = null;
  12073. renderItem.program = null;
  12074. renderItem.group = null;
  12075. }
  12076. }
  12077. return {
  12078. opaque: opaque,
  12079. transparent: transparent,
  12080. init: init,
  12081. push: push,
  12082. unshift: unshift,
  12083. finish: finish,
  12084. sort: sort
  12085. };
  12086. }
  12087. function WebGLRenderLists() {
  12088. var lists = new WeakMap();
  12089. function onSceneDispose(event) {
  12090. var scene = event.target;
  12091. scene.removeEventListener('dispose', onSceneDispose);
  12092. lists.delete(scene);
  12093. }
  12094. function get(scene, camera) {
  12095. var cameras = lists.get(scene);
  12096. var list;
  12097. if (cameras === undefined) {
  12098. list = new WebGLRenderList();
  12099. lists.set(scene, new WeakMap());
  12100. lists.get(scene).set(camera, list);
  12101. scene.addEventListener('dispose', onSceneDispose);
  12102. } else {
  12103. list = cameras.get(camera);
  12104. if (list === undefined) {
  12105. list = new WebGLRenderList();
  12106. cameras.set(camera, list);
  12107. }
  12108. }
  12109. return list;
  12110. }
  12111. function dispose() {
  12112. lists = new WeakMap();
  12113. }
  12114. return {
  12115. get: get,
  12116. dispose: dispose
  12117. };
  12118. }
  12119. /**
  12120. * @author mrdoob / http://mrdoob.com/
  12121. */
  12122. function UniformsCache() {
  12123. var lights = {};
  12124. return {
  12125. get: function (light) {
  12126. if (lights[light.id] !== undefined) {
  12127. return lights[light.id];
  12128. }
  12129. var uniforms;
  12130. switch (light.type) {
  12131. case 'DirectionalLight':
  12132. uniforms = {
  12133. direction: new Vector3(),
  12134. color: new Color()
  12135. };
  12136. break;
  12137. case 'SpotLight':
  12138. uniforms = {
  12139. position: new Vector3(),
  12140. direction: new Vector3(),
  12141. color: new Color(),
  12142. distance: 0,
  12143. coneCos: 0,
  12144. penumbraCos: 0,
  12145. decay: 0
  12146. };
  12147. break;
  12148. case 'PointLight':
  12149. uniforms = {
  12150. position: new Vector3(),
  12151. color: new Color(),
  12152. distance: 0,
  12153. decay: 0
  12154. };
  12155. break;
  12156. case 'HemisphereLight':
  12157. uniforms = {
  12158. direction: new Vector3(),
  12159. skyColor: new Color(),
  12160. groundColor: new Color()
  12161. };
  12162. break;
  12163. case 'RectAreaLight':
  12164. uniforms = {
  12165. color: new Color(),
  12166. position: new Vector3(),
  12167. halfWidth: new Vector3(),
  12168. halfHeight: new Vector3()
  12169. };
  12170. break;
  12171. }
  12172. lights[light.id] = uniforms;
  12173. return uniforms;
  12174. }
  12175. };
  12176. }
  12177. function ShadowUniformsCache() {
  12178. var lights = {};
  12179. return {
  12180. get: function (light) {
  12181. if (lights[light.id] !== undefined) {
  12182. return lights[light.id];
  12183. }
  12184. var uniforms;
  12185. switch (light.type) {
  12186. case 'DirectionalLight':
  12187. uniforms = {
  12188. shadowBias: 0,
  12189. shadowRadius: 1,
  12190. shadowMapSize: new Vector2()
  12191. };
  12192. break;
  12193. case 'SpotLight':
  12194. uniforms = {
  12195. shadowBias: 0,
  12196. shadowRadius: 1,
  12197. shadowMapSize: new Vector2()
  12198. };
  12199. break;
  12200. case 'PointLight':
  12201. uniforms = {
  12202. shadowBias: 0,
  12203. shadowRadius: 1,
  12204. shadowMapSize: new Vector2(),
  12205. shadowCameraNear: 1,
  12206. shadowCameraFar: 1000
  12207. };
  12208. break;
  12209. // TODO (abelnation): set RectAreaLight shadow uniforms
  12210. }
  12211. lights[light.id] = uniforms;
  12212. return uniforms;
  12213. }
  12214. };
  12215. }
  12216. var nextVersion = 0;
  12217. function shadowCastingLightsFirst(lightA, lightB) {
  12218. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  12219. }
  12220. function WebGLLights() {
  12221. var cache = new UniformsCache();
  12222. var shadowCache = ShadowUniformsCache();
  12223. var state = {
  12224. version: 0,
  12225. hash: {
  12226. directionalLength: -1,
  12227. pointLength: -1,
  12228. spotLength: -1,
  12229. rectAreaLength: -1,
  12230. hemiLength: -1,
  12231. numDirectionalShadows: -1,
  12232. numPointShadows: -1,
  12233. numSpotShadows: -1
  12234. },
  12235. ambient: [0, 0, 0],
  12236. probe: [],
  12237. directional: [],
  12238. directionalShadow: [],
  12239. directionalShadowMap: [],
  12240. directionalShadowMatrix: [],
  12241. spot: [],
  12242. spotShadow: [],
  12243. spotShadowMap: [],
  12244. spotShadowMatrix: [],
  12245. rectArea: [],
  12246. point: [],
  12247. pointShadow: [],
  12248. pointShadowMap: [],
  12249. pointShadowMatrix: [],
  12250. hemi: []
  12251. };
  12252. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  12253. var vector3 = new Vector3();
  12254. var matrix4 = new Matrix4();
  12255. var matrix42 = new Matrix4();
  12256. function setup(lights, shadows, camera) {
  12257. var r = 0,
  12258. g = 0,
  12259. b = 0;
  12260. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12261. var directionalLength = 0;
  12262. var pointLength = 0;
  12263. var spotLength = 0;
  12264. var rectAreaLength = 0;
  12265. var hemiLength = 0;
  12266. var numDirectionalShadows = 0;
  12267. var numPointShadows = 0;
  12268. var numSpotShadows = 0;
  12269. var viewMatrix = camera.matrixWorldInverse;
  12270. lights.sort(shadowCastingLightsFirst);
  12271. for (var i = 0, l = lights.length; i < l; i++) {
  12272. var light = lights[i];
  12273. var color = light.color;
  12274. var intensity = light.intensity;
  12275. var distance = light.distance;
  12276. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12277. if (light.isAmbientLight) {
  12278. r += color.r * intensity;
  12279. g += color.g * intensity;
  12280. b += color.b * intensity;
  12281. } else if (light.isLightProbe) {
  12282. for (var j = 0; j < 9; j++) {
  12283. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12284. }
  12285. } else if (light.isDirectionalLight) {
  12286. var uniforms = cache.get(light);
  12287. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  12288. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12289. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12290. uniforms.direction.sub(vector3);
  12291. uniforms.direction.transformDirection(viewMatrix);
  12292. if (light.castShadow) {
  12293. var shadow = light.shadow;
  12294. var shadowUniforms = shadowCache.get(light);
  12295. shadowUniforms.shadowBias = shadow.bias;
  12296. shadowUniforms.shadowRadius = shadow.radius;
  12297. shadowUniforms.shadowMapSize = shadow.mapSize;
  12298. state.directionalShadow[directionalLength] = shadowUniforms;
  12299. state.directionalShadowMap[directionalLength] = shadowMap;
  12300. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12301. numDirectionalShadows++;
  12302. }
  12303. state.directional[directionalLength] = uniforms;
  12304. directionalLength++;
  12305. } else if (light.isSpotLight) {
  12306. var uniforms = cache.get(light);
  12307. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12308. uniforms.position.applyMatrix4(viewMatrix);
  12309. uniforms.color.copy(color).multiplyScalar(intensity);
  12310. uniforms.distance = distance;
  12311. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12312. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12313. uniforms.direction.sub(vector3);
  12314. uniforms.direction.transformDirection(viewMatrix);
  12315. uniforms.coneCos = Math.cos(light.angle);
  12316. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12317. uniforms.decay = light.decay;
  12318. if (light.castShadow) {
  12319. var shadow = light.shadow;
  12320. var shadowUniforms = shadowCache.get(light);
  12321. shadowUniforms.shadowBias = shadow.bias;
  12322. shadowUniforms.shadowRadius = shadow.radius;
  12323. shadowUniforms.shadowMapSize = shadow.mapSize;
  12324. state.spotShadow[spotLength] = shadowUniforms;
  12325. state.spotShadowMap[spotLength] = shadowMap;
  12326. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12327. numSpotShadows++;
  12328. }
  12329. state.spot[spotLength] = uniforms;
  12330. spotLength++;
  12331. } else if (light.isRectAreaLight) {
  12332. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12333. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12334. // (b) intensity is the brightness of the light
  12335. uniforms.color.copy(color).multiplyScalar(intensity);
  12336. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12337. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12338. matrix42.identity();
  12339. matrix4.copy(light.matrixWorld);
  12340. matrix4.premultiply(viewMatrix);
  12341. matrix42.extractRotation(matrix4);
  12342. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12343. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12344. uniforms.halfWidth.applyMatrix4(matrix42);
  12345. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  12346. // uniforms.distance = distance;
  12347. state.rectArea[rectAreaLength] = uniforms;
  12348. rectAreaLength++;
  12349. } else if (light.isPointLight) {
  12350. var uniforms = cache.get(light);
  12351. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12352. uniforms.position.applyMatrix4(viewMatrix);
  12353. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  12354. uniforms.distance = light.distance;
  12355. uniforms.decay = light.decay;
  12356. if (light.castShadow) {
  12357. var shadow = light.shadow;
  12358. var shadowUniforms = shadowCache.get(light);
  12359. shadowUniforms.shadowBias = shadow.bias;
  12360. shadowUniforms.shadowRadius = shadow.radius;
  12361. shadowUniforms.shadowMapSize = shadow.mapSize;
  12362. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12363. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12364. state.pointShadow[pointLength] = shadowUniforms;
  12365. state.pointShadowMap[pointLength] = shadowMap;
  12366. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12367. numPointShadows++;
  12368. }
  12369. state.point[pointLength] = uniforms;
  12370. pointLength++;
  12371. } else if (light.isHemisphereLight) {
  12372. var uniforms = cache.get(light);
  12373. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12374. uniforms.direction.transformDirection(viewMatrix);
  12375. uniforms.direction.normalize();
  12376. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  12377. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  12378. state.hemi[hemiLength] = uniforms;
  12379. hemiLength++;
  12380. }
  12381. }
  12382. state.ambient[0] = r;
  12383. state.ambient[1] = g;
  12384. state.ambient[2] = b;
  12385. var hash = state.hash;
  12386. 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) {
  12387. state.directional.length = directionalLength;
  12388. state.spot.length = spotLength;
  12389. state.rectArea.length = rectAreaLength;
  12390. state.point.length = pointLength;
  12391. state.hemi.length = hemiLength;
  12392. state.directionalShadow.length = numDirectionalShadows;
  12393. state.directionalShadowMap.length = numDirectionalShadows;
  12394. state.pointShadow.length = numPointShadows;
  12395. state.pointShadowMap.length = numPointShadows;
  12396. state.spotShadow.length = numSpotShadows;
  12397. state.spotShadowMap.length = numSpotShadows;
  12398. state.directionalShadowMatrix.length = numDirectionalShadows;
  12399. state.pointShadowMatrix.length = numPointShadows;
  12400. state.spotShadowMatrix.length = numSpotShadows;
  12401. hash.directionalLength = directionalLength;
  12402. hash.pointLength = pointLength;
  12403. hash.spotLength = spotLength;
  12404. hash.rectAreaLength = rectAreaLength;
  12405. hash.hemiLength = hemiLength;
  12406. hash.numDirectionalShadows = numDirectionalShadows;
  12407. hash.numPointShadows = numPointShadows;
  12408. hash.numSpotShadows = numSpotShadows;
  12409. state.version = nextVersion++;
  12410. }
  12411. }
  12412. return {
  12413. setup: setup,
  12414. state: state
  12415. };
  12416. }
  12417. /**
  12418. * @author Mugen87 / https://github.com/Mugen87
  12419. */
  12420. function WebGLRenderState() {
  12421. var lights = new WebGLLights();
  12422. var lightsArray = [];
  12423. var shadowsArray = [];
  12424. function init() {
  12425. lightsArray.length = 0;
  12426. shadowsArray.length = 0;
  12427. }
  12428. function pushLight(light) {
  12429. lightsArray.push(light);
  12430. }
  12431. function pushShadow(shadowLight) {
  12432. shadowsArray.push(shadowLight);
  12433. }
  12434. function setupLights(camera) {
  12435. lights.setup(lightsArray, shadowsArray, camera);
  12436. }
  12437. var state = {
  12438. lightsArray: lightsArray,
  12439. shadowsArray: shadowsArray,
  12440. lights: lights
  12441. };
  12442. return {
  12443. init: init,
  12444. state: state,
  12445. setupLights: setupLights,
  12446. pushLight: pushLight,
  12447. pushShadow: pushShadow
  12448. };
  12449. }
  12450. function WebGLRenderStates() {
  12451. var renderStates = new WeakMap();
  12452. function onSceneDispose(event) {
  12453. var scene = event.target;
  12454. scene.removeEventListener('dispose', onSceneDispose);
  12455. renderStates.delete(scene);
  12456. }
  12457. function get(scene, camera) {
  12458. var renderState;
  12459. if (renderStates.has(scene) === false) {
  12460. renderState = new WebGLRenderState();
  12461. renderStates.set(scene, new WeakMap());
  12462. renderStates.get(scene).set(camera, renderState);
  12463. scene.addEventListener('dispose', onSceneDispose);
  12464. } else {
  12465. if (renderStates.get(scene).has(camera) === false) {
  12466. renderState = new WebGLRenderState();
  12467. renderStates.get(scene).set(camera, renderState);
  12468. } else {
  12469. renderState = renderStates.get(scene).get(camera);
  12470. }
  12471. }
  12472. return renderState;
  12473. }
  12474. function dispose() {
  12475. renderStates = new WeakMap();
  12476. }
  12477. return {
  12478. get: get,
  12479. dispose: dispose
  12480. };
  12481. }
  12482. /**
  12483. * @author mrdoob / http://mrdoob.com/
  12484. * @author alteredq / http://alteredqualia.com/
  12485. * @author bhouston / https://clara.io
  12486. * @author WestLangley / http://github.com/WestLangley
  12487. *
  12488. * parameters = {
  12489. *
  12490. * opacity: <float>,
  12491. *
  12492. * map: new THREE.Texture( <Image> ),
  12493. *
  12494. * alphaMap: new THREE.Texture( <Image> ),
  12495. *
  12496. * displacementMap: new THREE.Texture( <Image> ),
  12497. * displacementScale: <float>,
  12498. * displacementBias: <float>,
  12499. *
  12500. * wireframe: <boolean>,
  12501. * wireframeLinewidth: <float>
  12502. * }
  12503. */
  12504. function MeshDepthMaterial(parameters) {
  12505. Material.call(this);
  12506. this.type = 'MeshDepthMaterial';
  12507. this.depthPacking = BasicDepthPacking;
  12508. this.skinning = false;
  12509. this.morphTargets = false;
  12510. this.map = null;
  12511. this.alphaMap = null;
  12512. this.displacementMap = null;
  12513. this.displacementScale = 1;
  12514. this.displacementBias = 0;
  12515. this.wireframe = false;
  12516. this.wireframeLinewidth = 1;
  12517. this.fog = false;
  12518. this.setValues(parameters);
  12519. }
  12520. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  12521. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12522. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12523. MeshDepthMaterial.prototype.copy = function (source) {
  12524. Material.prototype.copy.call(this, source);
  12525. this.depthPacking = source.depthPacking;
  12526. this.skinning = source.skinning;
  12527. this.morphTargets = source.morphTargets;
  12528. this.map = source.map;
  12529. this.alphaMap = source.alphaMap;
  12530. this.displacementMap = source.displacementMap;
  12531. this.displacementScale = source.displacementScale;
  12532. this.displacementBias = source.displacementBias;
  12533. this.wireframe = source.wireframe;
  12534. this.wireframeLinewidth = source.wireframeLinewidth;
  12535. return this;
  12536. };
  12537. /**
  12538. * @author WestLangley / http://github.com/WestLangley
  12539. *
  12540. * parameters = {
  12541. *
  12542. * referencePosition: <float>,
  12543. * nearDistance: <float>,
  12544. * farDistance: <float>,
  12545. *
  12546. * skinning: <bool>,
  12547. * morphTargets: <bool>,
  12548. *
  12549. * map: new THREE.Texture( <Image> ),
  12550. *
  12551. * alphaMap: new THREE.Texture( <Image> ),
  12552. *
  12553. * displacementMap: new THREE.Texture( <Image> ),
  12554. * displacementScale: <float>,
  12555. * displacementBias: <float>
  12556. *
  12557. * }
  12558. */
  12559. function MeshDistanceMaterial(parameters) {
  12560. Material.call(this);
  12561. this.type = 'MeshDistanceMaterial';
  12562. this.referencePosition = new Vector3();
  12563. this.nearDistance = 1;
  12564. this.farDistance = 1000;
  12565. this.skinning = false;
  12566. this.morphTargets = false;
  12567. this.map = null;
  12568. this.alphaMap = null;
  12569. this.displacementMap = null;
  12570. this.displacementScale = 1;
  12571. this.displacementBias = 0;
  12572. this.fog = false;
  12573. this.setValues(parameters);
  12574. }
  12575. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  12576. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12577. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12578. MeshDistanceMaterial.prototype.copy = function (source) {
  12579. Material.prototype.copy.call(this, source);
  12580. this.referencePosition.copy(source.referencePosition);
  12581. this.nearDistance = source.nearDistance;
  12582. this.farDistance = source.farDistance;
  12583. this.skinning = source.skinning;
  12584. this.morphTargets = source.morphTargets;
  12585. this.map = source.map;
  12586. this.alphaMap = source.alphaMap;
  12587. this.displacementMap = source.displacementMap;
  12588. this.displacementScale = source.displacementScale;
  12589. this.displacementBias = source.displacementBias;
  12590. return this;
  12591. };
  12592. 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\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 = unpackRGBATo2Half( 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 = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12593. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12594. /**
  12595. * @author alteredq / http://alteredqualia.com/
  12596. * @author mrdoob / http://mrdoob.com/
  12597. */
  12598. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  12599. var _frustum = new Frustum(),
  12600. _shadowMapSize = new Vector2(),
  12601. _viewportSize = new Vector2(),
  12602. _viewport = new Vector4(),
  12603. _depthMaterials = [],
  12604. _distanceMaterials = [],
  12605. _materialCache = {};
  12606. var shadowSide = {
  12607. 0: BackSide,
  12608. 1: FrontSide,
  12609. 2: DoubleSide
  12610. };
  12611. var shadowMaterialVertical = new ShaderMaterial({
  12612. defines: {
  12613. SAMPLE_RATE: 2.0 / 8.0,
  12614. HALF_SAMPLE_RATE: 1.0 / 8.0
  12615. },
  12616. uniforms: {
  12617. shadow_pass: {
  12618. value: null
  12619. },
  12620. resolution: {
  12621. value: new Vector2()
  12622. },
  12623. radius: {
  12624. value: 4.0
  12625. }
  12626. },
  12627. vertexShader: vsm_vert,
  12628. fragmentShader: vsm_frag
  12629. });
  12630. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  12631. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  12632. var fullScreenTri = new BufferGeometry();
  12633. fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12634. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12635. var scope = this;
  12636. this.enabled = false;
  12637. this.autoUpdate = true;
  12638. this.needsUpdate = false;
  12639. this.type = PCFShadowMap;
  12640. this.render = function (lights, scene, camera) {
  12641. if (scope.enabled === false) return;
  12642. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12643. if (lights.length === 0) return;
  12644. var currentRenderTarget = _renderer.getRenderTarget();
  12645. var activeCubeFace = _renderer.getActiveCubeFace();
  12646. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12647. var _state = _renderer.state; // Set GL state for depth map.
  12648. _state.setBlending(NoBlending);
  12649. _state.buffers.color.setClear(1, 1, 1, 1);
  12650. _state.buffers.depth.setTest(true);
  12651. _state.setScissorTest(false); // render depth map
  12652. for (var i = 0, il = lights.length; i < il; i++) {
  12653. var light = lights[i];
  12654. var shadow = light.shadow;
  12655. if (shadow === undefined) {
  12656. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12657. continue;
  12658. }
  12659. _shadowMapSize.copy(shadow.mapSize);
  12660. var shadowFrameExtents = shadow.getFrameExtents();
  12661. _shadowMapSize.multiply(shadowFrameExtents);
  12662. _viewportSize.copy(shadow.mapSize);
  12663. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  12664. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  12665. if (_shadowMapSize.x > maxTextureSize) {
  12666. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  12667. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12668. shadow.mapSize.x = _viewportSize.x;
  12669. }
  12670. if (_shadowMapSize.y > maxTextureSize) {
  12671. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  12672. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12673. shadow.mapSize.y = _viewportSize.y;
  12674. }
  12675. }
  12676. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12677. var pars = {
  12678. minFilter: LinearFilter,
  12679. magFilter: LinearFilter,
  12680. format: RGBAFormat
  12681. };
  12682. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12683. shadow.map.texture.name = light.name + ".shadowMap";
  12684. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12685. shadow.camera.updateProjectionMatrix();
  12686. }
  12687. if (shadow.map === null) {
  12688. var pars = {
  12689. minFilter: NearestFilter,
  12690. magFilter: NearestFilter,
  12691. format: RGBAFormat
  12692. };
  12693. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12694. shadow.map.texture.name = light.name + ".shadowMap";
  12695. shadow.camera.updateProjectionMatrix();
  12696. }
  12697. _renderer.setRenderTarget(shadow.map);
  12698. _renderer.clear();
  12699. var viewportCount = shadow.getViewportCount();
  12700. for (var vp = 0; vp < viewportCount; vp++) {
  12701. var viewport = shadow.getViewport(vp);
  12702. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12703. _state.viewport(_viewport);
  12704. shadow.updateMatrices(light, vp);
  12705. _frustum = shadow.getFrustum();
  12706. renderObject(scene, camera, shadow.camera, light, this.type);
  12707. } // do blur pass for VSM
  12708. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12709. VSMPass(shadow, camera);
  12710. }
  12711. }
  12712. scope.needsUpdate = false;
  12713. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12714. };
  12715. function VSMPass(shadow, camera) {
  12716. var geometry = _objects.update(fullScreenMesh); // vertical pass
  12717. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12718. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12719. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12720. _renderer.setRenderTarget(shadow.mapPass);
  12721. _renderer.clear();
  12722. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  12723. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12724. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  12725. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  12726. _renderer.setRenderTarget(shadow.map);
  12727. _renderer.clear();
  12728. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  12729. }
  12730. function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12731. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12732. var material = _depthMaterials[index];
  12733. if (material === undefined) {
  12734. material = new MeshDepthMaterial({
  12735. depthPacking: RGBADepthPacking,
  12736. morphTargets: useMorphing,
  12737. skinning: useSkinning
  12738. });
  12739. _depthMaterials[index] = material;
  12740. }
  12741. return material;
  12742. }
  12743. function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12744. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12745. var material = _distanceMaterials[index];
  12746. if (material === undefined) {
  12747. material = new MeshDistanceMaterial({
  12748. morphTargets: useMorphing,
  12749. skinning: useSkinning
  12750. });
  12751. _distanceMaterials[index] = material;
  12752. }
  12753. return material;
  12754. }
  12755. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  12756. var geometry = object.geometry;
  12757. var result = null;
  12758. var getMaterialVariant = getDepthMaterialVariant;
  12759. var customMaterial = object.customDepthMaterial;
  12760. if (light.isPointLight === true) {
  12761. getMaterialVariant = getDistanceMaterialVariant;
  12762. customMaterial = object.customDistanceMaterial;
  12763. }
  12764. if (customMaterial === undefined) {
  12765. var useMorphing = false;
  12766. if (material.morphTargets === true) {
  12767. if (geometry.isBufferGeometry === true) {
  12768. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12769. } else if (geometry.isGeometry === true) {
  12770. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  12771. }
  12772. }
  12773. var useSkinning = false;
  12774. if (object.isSkinnedMesh === true) {
  12775. if (material.skinning === true) {
  12776. useSkinning = true;
  12777. } else {
  12778. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  12779. }
  12780. }
  12781. var useInstancing = object.isInstancedMesh === true;
  12782. result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
  12783. } else {
  12784. result = customMaterial;
  12785. }
  12786. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  12787. // in this case we need a unique material instance reflecting the
  12788. // appropriate state
  12789. var keyA = result.uuid,
  12790. keyB = material.uuid;
  12791. var materialsForVariant = _materialCache[keyA];
  12792. if (materialsForVariant === undefined) {
  12793. materialsForVariant = {};
  12794. _materialCache[keyA] = materialsForVariant;
  12795. }
  12796. var cachedMaterial = materialsForVariant[keyB];
  12797. if (cachedMaterial === undefined) {
  12798. cachedMaterial = result.clone();
  12799. materialsForVariant[keyB] = cachedMaterial;
  12800. }
  12801. result = cachedMaterial;
  12802. }
  12803. result.visible = material.visible;
  12804. result.wireframe = material.wireframe;
  12805. if (type === VSMShadowMap) {
  12806. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12807. } else {
  12808. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12809. }
  12810. result.clipShadows = material.clipShadows;
  12811. result.clippingPlanes = material.clippingPlanes;
  12812. result.clipIntersection = material.clipIntersection;
  12813. result.wireframeLinewidth = material.wireframeLinewidth;
  12814. result.linewidth = material.linewidth;
  12815. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12816. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12817. result.nearDistance = shadowCameraNear;
  12818. result.farDistance = shadowCameraFar;
  12819. }
  12820. return result;
  12821. }
  12822. function renderObject(object, camera, shadowCamera, light, type) {
  12823. if (object.visible === false) return;
  12824. var visible = object.layers.test(camera.layers);
  12825. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12826. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12827. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12828. var geometry = _objects.update(object);
  12829. var material = object.material;
  12830. if (Array.isArray(material)) {
  12831. var groups = geometry.groups;
  12832. for (var k = 0, kl = groups.length; k < kl; k++) {
  12833. var group = groups[k];
  12834. var groupMaterial = material[group.materialIndex];
  12835. if (groupMaterial && groupMaterial.visible) {
  12836. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12837. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12838. }
  12839. }
  12840. } else if (material.visible) {
  12841. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  12842. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12843. }
  12844. }
  12845. }
  12846. var children = object.children;
  12847. for (var i = 0, l = children.length; i < l; i++) {
  12848. renderObject(children[i], camera, shadowCamera, light, type);
  12849. }
  12850. }
  12851. }
  12852. /**
  12853. * @author mrdoob / http://mrdoob.com/
  12854. */
  12855. function WebGLState(gl, extensions, capabilities) {
  12856. var isWebGL2 = capabilities.isWebGL2;
  12857. function ColorBuffer() {
  12858. var locked = false;
  12859. var color = new Vector4();
  12860. var currentColorMask = null;
  12861. var currentColorClear = new Vector4(0, 0, 0, 0);
  12862. return {
  12863. setMask: function (colorMask) {
  12864. if (currentColorMask !== colorMask && !locked) {
  12865. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12866. currentColorMask = colorMask;
  12867. }
  12868. },
  12869. setLocked: function (lock) {
  12870. locked = lock;
  12871. },
  12872. setClear: function (r, g, b, a, premultipliedAlpha) {
  12873. if (premultipliedAlpha === true) {
  12874. r *= a;
  12875. g *= a;
  12876. b *= a;
  12877. }
  12878. color.set(r, g, b, a);
  12879. if (currentColorClear.equals(color) === false) {
  12880. gl.clearColor(r, g, b, a);
  12881. currentColorClear.copy(color);
  12882. }
  12883. },
  12884. reset: function () {
  12885. locked = false;
  12886. currentColorMask = null;
  12887. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12888. }
  12889. };
  12890. }
  12891. function DepthBuffer() {
  12892. var locked = false;
  12893. var currentDepthMask = null;
  12894. var currentDepthFunc = null;
  12895. var currentDepthClear = null;
  12896. return {
  12897. setTest: function (depthTest) {
  12898. if (depthTest) {
  12899. enable(2929);
  12900. } else {
  12901. disable(2929);
  12902. }
  12903. },
  12904. setMask: function (depthMask) {
  12905. if (currentDepthMask !== depthMask && !locked) {
  12906. gl.depthMask(depthMask);
  12907. currentDepthMask = depthMask;
  12908. }
  12909. },
  12910. setFunc: function (depthFunc) {
  12911. if (currentDepthFunc !== depthFunc) {
  12912. if (depthFunc) {
  12913. switch (depthFunc) {
  12914. case NeverDepth:
  12915. gl.depthFunc(512);
  12916. break;
  12917. case AlwaysDepth:
  12918. gl.depthFunc(519);
  12919. break;
  12920. case LessDepth:
  12921. gl.depthFunc(513);
  12922. break;
  12923. case LessEqualDepth:
  12924. gl.depthFunc(515);
  12925. break;
  12926. case EqualDepth:
  12927. gl.depthFunc(514);
  12928. break;
  12929. case GreaterEqualDepth:
  12930. gl.depthFunc(518);
  12931. break;
  12932. case GreaterDepth:
  12933. gl.depthFunc(516);
  12934. break;
  12935. case NotEqualDepth:
  12936. gl.depthFunc(517);
  12937. break;
  12938. default:
  12939. gl.depthFunc(515);
  12940. }
  12941. } else {
  12942. gl.depthFunc(515);
  12943. }
  12944. currentDepthFunc = depthFunc;
  12945. }
  12946. },
  12947. setLocked: function (lock) {
  12948. locked = lock;
  12949. },
  12950. setClear: function (depth) {
  12951. if (currentDepthClear !== depth) {
  12952. gl.clearDepth(depth);
  12953. currentDepthClear = depth;
  12954. }
  12955. },
  12956. reset: function () {
  12957. locked = false;
  12958. currentDepthMask = null;
  12959. currentDepthFunc = null;
  12960. currentDepthClear = null;
  12961. }
  12962. };
  12963. }
  12964. function StencilBuffer() {
  12965. var locked = false;
  12966. var currentStencilMask = null;
  12967. var currentStencilFunc = null;
  12968. var currentStencilRef = null;
  12969. var currentStencilFuncMask = null;
  12970. var currentStencilFail = null;
  12971. var currentStencilZFail = null;
  12972. var currentStencilZPass = null;
  12973. var currentStencilClear = null;
  12974. return {
  12975. setTest: function (stencilTest) {
  12976. if (!locked) {
  12977. if (stencilTest) {
  12978. enable(2960);
  12979. } else {
  12980. disable(2960);
  12981. }
  12982. }
  12983. },
  12984. setMask: function (stencilMask) {
  12985. if (currentStencilMask !== stencilMask && !locked) {
  12986. gl.stencilMask(stencilMask);
  12987. currentStencilMask = stencilMask;
  12988. }
  12989. },
  12990. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12991. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12992. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12993. currentStencilFunc = stencilFunc;
  12994. currentStencilRef = stencilRef;
  12995. currentStencilFuncMask = stencilMask;
  12996. }
  12997. },
  12998. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12999. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13000. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13001. currentStencilFail = stencilFail;
  13002. currentStencilZFail = stencilZFail;
  13003. currentStencilZPass = stencilZPass;
  13004. }
  13005. },
  13006. setLocked: function (lock) {
  13007. locked = lock;
  13008. },
  13009. setClear: function (stencil) {
  13010. if (currentStencilClear !== stencil) {
  13011. gl.clearStencil(stencil);
  13012. currentStencilClear = stencil;
  13013. }
  13014. },
  13015. reset: function () {
  13016. locked = false;
  13017. currentStencilMask = null;
  13018. currentStencilFunc = null;
  13019. currentStencilRef = null;
  13020. currentStencilFuncMask = null;
  13021. currentStencilFail = null;
  13022. currentStencilZFail = null;
  13023. currentStencilZPass = null;
  13024. currentStencilClear = null;
  13025. }
  13026. };
  13027. } //
  13028. var colorBuffer = new ColorBuffer();
  13029. var depthBuffer = new DepthBuffer();
  13030. var stencilBuffer = new StencilBuffer();
  13031. var maxVertexAttributes = gl.getParameter(34921);
  13032. var newAttributes = new Uint8Array(maxVertexAttributes);
  13033. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  13034. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  13035. var enabledCapabilities = {};
  13036. var currentProgram = null;
  13037. var currentBlendingEnabled = null;
  13038. var currentBlending = null;
  13039. var currentBlendEquation = null;
  13040. var currentBlendSrc = null;
  13041. var currentBlendDst = null;
  13042. var currentBlendEquationAlpha = null;
  13043. var currentBlendSrcAlpha = null;
  13044. var currentBlendDstAlpha = null;
  13045. var currentPremultipledAlpha = false;
  13046. var currentFlipSided = null;
  13047. var currentCullFace = null;
  13048. var currentLineWidth = null;
  13049. var currentPolygonOffsetFactor = null;
  13050. var currentPolygonOffsetUnits = null;
  13051. var maxTextures = gl.getParameter(35661);
  13052. var lineWidthAvailable = false;
  13053. var version = 0;
  13054. var glVersion = gl.getParameter(7938);
  13055. if (glVersion.indexOf('WebGL') !== -1) {
  13056. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  13057. lineWidthAvailable = version >= 1.0;
  13058. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13059. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  13060. lineWidthAvailable = version >= 2.0;
  13061. }
  13062. var currentTextureSlot = null;
  13063. var currentBoundTextures = {};
  13064. var currentScissor = new Vector4();
  13065. var currentViewport = new Vector4();
  13066. function createTexture(type, target, count) {
  13067. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13068. var texture = gl.createTexture();
  13069. gl.bindTexture(type, texture);
  13070. gl.texParameteri(type, 10241, 9728);
  13071. gl.texParameteri(type, 10240, 9728);
  13072. for (var i = 0; i < count; i++) {
  13073. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  13074. }
  13075. return texture;
  13076. }
  13077. var emptyTextures = {};
  13078. emptyTextures[3553] = createTexture(3553, 3553, 1);
  13079. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  13080. colorBuffer.setClear(0, 0, 0, 1);
  13081. depthBuffer.setClear(1);
  13082. stencilBuffer.setClear(0);
  13083. enable(2929);
  13084. depthBuffer.setFunc(LessEqualDepth);
  13085. setFlipSided(false);
  13086. setCullFace(CullFaceBack);
  13087. enable(2884);
  13088. setBlending(NoBlending); //
  13089. function initAttributes() {
  13090. for (var i = 0, l = newAttributes.length; i < l; i++) {
  13091. newAttributes[i] = 0;
  13092. }
  13093. }
  13094. function enableAttribute(attribute) {
  13095. enableAttributeAndDivisor(attribute, 0);
  13096. }
  13097. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  13098. newAttributes[attribute] = 1;
  13099. if (enabledAttributes[attribute] === 0) {
  13100. gl.enableVertexAttribArray(attribute);
  13101. enabledAttributes[attribute] = 1;
  13102. }
  13103. if (attributeDivisors[attribute] !== meshPerAttribute) {
  13104. var extension = isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  13105. extension[isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  13106. attributeDivisors[attribute] = meshPerAttribute;
  13107. }
  13108. }
  13109. function disableUnusedAttributes() {
  13110. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  13111. if (enabledAttributes[i] !== newAttributes[i]) {
  13112. gl.disableVertexAttribArray(i);
  13113. enabledAttributes[i] = 0;
  13114. }
  13115. }
  13116. }
  13117. function enable(id) {
  13118. if (enabledCapabilities[id] !== true) {
  13119. gl.enable(id);
  13120. enabledCapabilities[id] = true;
  13121. }
  13122. }
  13123. function disable(id) {
  13124. if (enabledCapabilities[id] !== false) {
  13125. gl.disable(id);
  13126. enabledCapabilities[id] = false;
  13127. }
  13128. }
  13129. function useProgram(program) {
  13130. if (currentProgram !== program) {
  13131. gl.useProgram(program);
  13132. currentProgram = program;
  13133. return true;
  13134. }
  13135. return false;
  13136. }
  13137. var equationToGL = {
  13138. [AddEquation]: 32774,
  13139. [SubtractEquation]: 32778,
  13140. [ReverseSubtractEquation]: 32779
  13141. };
  13142. if (isWebGL2) {
  13143. equationToGL[MinEquation] = 32775;
  13144. equationToGL[MaxEquation] = 32776;
  13145. } else {
  13146. var extension = extensions.get('EXT_blend_minmax');
  13147. if (extension !== null) {
  13148. equationToGL[MinEquation] = extension.MIN_EXT;
  13149. equationToGL[MaxEquation] = extension.MAX_EXT;
  13150. }
  13151. }
  13152. var factorToGL = {
  13153. [ZeroFactor]: 0,
  13154. [OneFactor]: 1,
  13155. [SrcColorFactor]: 768,
  13156. [SrcAlphaFactor]: 770,
  13157. [SrcAlphaSaturateFactor]: 776,
  13158. [DstColorFactor]: 774,
  13159. [DstAlphaFactor]: 772,
  13160. [OneMinusSrcColorFactor]: 769,
  13161. [OneMinusSrcAlphaFactor]: 771,
  13162. [OneMinusDstColorFactor]: 775,
  13163. [OneMinusDstAlphaFactor]: 773
  13164. };
  13165. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13166. if (blending === NoBlending) {
  13167. if (currentBlendingEnabled) {
  13168. disable(3042);
  13169. currentBlendingEnabled = false;
  13170. }
  13171. return;
  13172. }
  13173. if (!currentBlendingEnabled) {
  13174. enable(3042);
  13175. currentBlendingEnabled = true;
  13176. }
  13177. if (blending !== CustomBlending) {
  13178. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13179. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13180. gl.blendEquation(32774);
  13181. currentBlendEquation = AddEquation;
  13182. currentBlendEquationAlpha = AddEquation;
  13183. }
  13184. if (premultipliedAlpha) {
  13185. switch (blending) {
  13186. case NormalBlending:
  13187. gl.blendFuncSeparate(1, 771, 1, 771);
  13188. break;
  13189. case AdditiveBlending:
  13190. gl.blendFunc(1, 1);
  13191. break;
  13192. case SubtractiveBlending:
  13193. gl.blendFuncSeparate(0, 0, 769, 771);
  13194. break;
  13195. case MultiplyBlending:
  13196. gl.blendFuncSeparate(0, 768, 0, 770);
  13197. break;
  13198. default:
  13199. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13200. break;
  13201. }
  13202. } else {
  13203. switch (blending) {
  13204. case NormalBlending:
  13205. gl.blendFuncSeparate(770, 771, 1, 771);
  13206. break;
  13207. case AdditiveBlending:
  13208. gl.blendFunc(770, 1);
  13209. break;
  13210. case SubtractiveBlending:
  13211. gl.blendFunc(0, 769);
  13212. break;
  13213. case MultiplyBlending:
  13214. gl.blendFunc(0, 768);
  13215. break;
  13216. default:
  13217. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13218. break;
  13219. }
  13220. }
  13221. currentBlendSrc = null;
  13222. currentBlendDst = null;
  13223. currentBlendSrcAlpha = null;
  13224. currentBlendDstAlpha = null;
  13225. currentBlending = blending;
  13226. currentPremultipledAlpha = premultipliedAlpha;
  13227. }
  13228. return;
  13229. } // custom blending
  13230. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13231. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13232. blendDstAlpha = blendDstAlpha || blendDst;
  13233. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13234. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13235. currentBlendEquation = blendEquation;
  13236. currentBlendEquationAlpha = blendEquationAlpha;
  13237. }
  13238. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13239. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13240. currentBlendSrc = blendSrc;
  13241. currentBlendDst = blendDst;
  13242. currentBlendSrcAlpha = blendSrcAlpha;
  13243. currentBlendDstAlpha = blendDstAlpha;
  13244. }
  13245. currentBlending = blending;
  13246. currentPremultipledAlpha = null;
  13247. }
  13248. function setMaterial(material, frontFaceCW) {
  13249. material.side === DoubleSide ? disable(2884) : enable(2884);
  13250. var flipSided = material.side === BackSide;
  13251. if (frontFaceCW) flipSided = !flipSided;
  13252. setFlipSided(flipSided);
  13253. 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);
  13254. depthBuffer.setFunc(material.depthFunc);
  13255. depthBuffer.setTest(material.depthTest);
  13256. depthBuffer.setMask(material.depthWrite);
  13257. colorBuffer.setMask(material.colorWrite);
  13258. var stencilWrite = material.stencilWrite;
  13259. stencilBuffer.setTest(stencilWrite);
  13260. if (stencilWrite) {
  13261. stencilBuffer.setMask(material.stencilWriteMask);
  13262. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13263. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13264. }
  13265. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13266. } //
  13267. function setFlipSided(flipSided) {
  13268. if (currentFlipSided !== flipSided) {
  13269. if (flipSided) {
  13270. gl.frontFace(2304);
  13271. } else {
  13272. gl.frontFace(2305);
  13273. }
  13274. currentFlipSided = flipSided;
  13275. }
  13276. }
  13277. function setCullFace(cullFace) {
  13278. if (cullFace !== CullFaceNone) {
  13279. enable(2884);
  13280. if (cullFace !== currentCullFace) {
  13281. if (cullFace === CullFaceBack) {
  13282. gl.cullFace(1029);
  13283. } else if (cullFace === CullFaceFront) {
  13284. gl.cullFace(1028);
  13285. } else {
  13286. gl.cullFace(1032);
  13287. }
  13288. }
  13289. } else {
  13290. disable(2884);
  13291. }
  13292. currentCullFace = cullFace;
  13293. }
  13294. function setLineWidth(width) {
  13295. if (width !== currentLineWidth) {
  13296. if (lineWidthAvailable) gl.lineWidth(width);
  13297. currentLineWidth = width;
  13298. }
  13299. }
  13300. function setPolygonOffset(polygonOffset, factor, units) {
  13301. if (polygonOffset) {
  13302. enable(32823);
  13303. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13304. gl.polygonOffset(factor, units);
  13305. currentPolygonOffsetFactor = factor;
  13306. currentPolygonOffsetUnits = units;
  13307. }
  13308. } else {
  13309. disable(32823);
  13310. }
  13311. }
  13312. function setScissorTest(scissorTest) {
  13313. if (scissorTest) {
  13314. enable(3089);
  13315. } else {
  13316. disable(3089);
  13317. }
  13318. } // texture
  13319. function activeTexture(webglSlot) {
  13320. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  13321. if (currentTextureSlot !== webglSlot) {
  13322. gl.activeTexture(webglSlot);
  13323. currentTextureSlot = webglSlot;
  13324. }
  13325. }
  13326. function bindTexture(webglType, webglTexture) {
  13327. if (currentTextureSlot === null) {
  13328. activeTexture();
  13329. }
  13330. var boundTexture = currentBoundTextures[currentTextureSlot];
  13331. if (boundTexture === undefined) {
  13332. boundTexture = {
  13333. type: undefined,
  13334. texture: undefined
  13335. };
  13336. currentBoundTextures[currentTextureSlot] = boundTexture;
  13337. }
  13338. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13339. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13340. boundTexture.type = webglType;
  13341. boundTexture.texture = webglTexture;
  13342. }
  13343. }
  13344. function unbindTexture() {
  13345. var boundTexture = currentBoundTextures[currentTextureSlot];
  13346. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13347. gl.bindTexture(boundTexture.type, null);
  13348. boundTexture.type = undefined;
  13349. boundTexture.texture = undefined;
  13350. }
  13351. }
  13352. function compressedTexImage2D() {
  13353. try {
  13354. gl.compressedTexImage2D.apply(gl, arguments);
  13355. } catch (error) {
  13356. console.error('THREE.WebGLState:', error);
  13357. }
  13358. }
  13359. function texImage2D() {
  13360. try {
  13361. gl.texImage2D.apply(gl, arguments);
  13362. } catch (error) {
  13363. console.error('THREE.WebGLState:', error);
  13364. }
  13365. }
  13366. function texImage3D() {
  13367. try {
  13368. gl.texImage3D.apply(gl, arguments);
  13369. } catch (error) {
  13370. console.error('THREE.WebGLState:', error);
  13371. }
  13372. } //
  13373. function scissor(scissor) {
  13374. if (currentScissor.equals(scissor) === false) {
  13375. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13376. currentScissor.copy(scissor);
  13377. }
  13378. }
  13379. function viewport(viewport) {
  13380. if (currentViewport.equals(viewport) === false) {
  13381. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13382. currentViewport.copy(viewport);
  13383. }
  13384. } //
  13385. function reset() {
  13386. for (var i = 0; i < enabledAttributes.length; i++) {
  13387. if (enabledAttributes[i] === 1) {
  13388. gl.disableVertexAttribArray(i);
  13389. enabledAttributes[i] = 0;
  13390. }
  13391. }
  13392. enabledCapabilities = {};
  13393. currentTextureSlot = null;
  13394. currentBoundTextures = {};
  13395. currentProgram = null;
  13396. currentBlending = null;
  13397. currentFlipSided = null;
  13398. currentCullFace = null;
  13399. colorBuffer.reset();
  13400. depthBuffer.reset();
  13401. stencilBuffer.reset();
  13402. }
  13403. return {
  13404. buffers: {
  13405. color: colorBuffer,
  13406. depth: depthBuffer,
  13407. stencil: stencilBuffer
  13408. },
  13409. initAttributes: initAttributes,
  13410. enableAttribute: enableAttribute,
  13411. enableAttributeAndDivisor: enableAttributeAndDivisor,
  13412. disableUnusedAttributes: disableUnusedAttributes,
  13413. enable: enable,
  13414. disable: disable,
  13415. useProgram: useProgram,
  13416. setBlending: setBlending,
  13417. setMaterial: setMaterial,
  13418. setFlipSided: setFlipSided,
  13419. setCullFace: setCullFace,
  13420. setLineWidth: setLineWidth,
  13421. setPolygonOffset: setPolygonOffset,
  13422. setScissorTest: setScissorTest,
  13423. activeTexture: activeTexture,
  13424. bindTexture: bindTexture,
  13425. unbindTexture: unbindTexture,
  13426. compressedTexImage2D: compressedTexImage2D,
  13427. texImage2D: texImage2D,
  13428. texImage3D: texImage3D,
  13429. scissor: scissor,
  13430. viewport: viewport,
  13431. reset: reset
  13432. };
  13433. }
  13434. /**
  13435. * @author mrdoob / http://mrdoob.com/
  13436. */
  13437. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13438. var isWebGL2 = capabilities.isWebGL2;
  13439. var maxTextures = capabilities.maxTextures;
  13440. var maxCubemapSize = capabilities.maxCubemapSize;
  13441. var maxTextureSize = capabilities.maxTextureSize;
  13442. var maxSamples = capabilities.maxSamples;
  13443. var _videoTextures = new WeakMap();
  13444. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13445. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13446. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13447. var useOffscreenCanvas = false;
  13448. try {
  13449. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  13450. } catch (err) {// Ignore any errors
  13451. }
  13452. function createCanvas(width, height) {
  13453. // Use OffscreenCanvas when available. Specially needed in web workers
  13454. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  13455. }
  13456. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13457. var scale = 1; // handle case if texture exceeds max size
  13458. if (image.width > maxSize || image.height > maxSize) {
  13459. scale = maxSize / Math.max(image.width, image.height);
  13460. } // only perform resize if necessary
  13461. if (scale < 1 || needsPowerOfTwo === true) {
  13462. // only perform resize for certain image types
  13463. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13464. var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  13465. var width = floor(scale * image.width);
  13466. var height = floor(scale * image.height);
  13467. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13468. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13469. canvas.width = width;
  13470. canvas.height = height;
  13471. var context = canvas.getContext('2d');
  13472. context.drawImage(image, 0, 0, width, height);
  13473. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13474. return canvas;
  13475. } else {
  13476. if ('data' in image) {
  13477. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13478. }
  13479. return image;
  13480. }
  13481. }
  13482. return image;
  13483. }
  13484. function isPowerOfTwo(image) {
  13485. return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
  13486. }
  13487. function textureNeedsPowerOfTwo(texture) {
  13488. if (isWebGL2) return false;
  13489. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13490. }
  13491. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13492. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13493. }
  13494. function generateMipmap(target, texture, width, height) {
  13495. _gl.generateMipmap(target);
  13496. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13497. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  13498. }
  13499. function getInternalFormat(internalFormatName, glFormat, glType) {
  13500. if (isWebGL2 === false) return glFormat;
  13501. if (internalFormatName !== null) {
  13502. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13503. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13504. }
  13505. var internalFormat = glFormat;
  13506. if (glFormat === 6403) {
  13507. if (glType === 5126) internalFormat = 33326;
  13508. if (glType === 5131) internalFormat = 33325;
  13509. if (glType === 5121) internalFormat = 33321;
  13510. }
  13511. if (glFormat === 6407) {
  13512. if (glType === 5126) internalFormat = 34837;
  13513. if (glType === 5131) internalFormat = 34843;
  13514. if (glType === 5121) internalFormat = 32849;
  13515. }
  13516. if (glFormat === 6408) {
  13517. if (glType === 5126) internalFormat = 34836;
  13518. if (glType === 5131) internalFormat = 34842;
  13519. if (glType === 5121) internalFormat = 32856;
  13520. }
  13521. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  13522. extensions.get('EXT_color_buffer_float');
  13523. }
  13524. return internalFormat;
  13525. } // Fallback filters for non-power-of-2 textures
  13526. function filterFallback(f) {
  13527. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13528. return 9728;
  13529. }
  13530. return 9729;
  13531. } //
  13532. function onTextureDispose(event) {
  13533. var texture = event.target;
  13534. texture.removeEventListener('dispose', onTextureDispose);
  13535. deallocateTexture(texture);
  13536. if (texture.isVideoTexture) {
  13537. _videoTextures.delete(texture);
  13538. }
  13539. info.memory.textures--;
  13540. }
  13541. function onRenderTargetDispose(event) {
  13542. var renderTarget = event.target;
  13543. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13544. deallocateRenderTarget(renderTarget);
  13545. info.memory.textures--;
  13546. } //
  13547. function deallocateTexture(texture) {
  13548. var textureProperties = properties.get(texture);
  13549. if (textureProperties.__webglInit === undefined) return;
  13550. _gl.deleteTexture(textureProperties.__webglTexture);
  13551. properties.remove(texture);
  13552. }
  13553. function deallocateRenderTarget(renderTarget) {
  13554. var renderTargetProperties = properties.get(renderTarget);
  13555. var textureProperties = properties.get(renderTarget.texture);
  13556. if (!renderTarget) return;
  13557. if (textureProperties.__webglTexture !== undefined) {
  13558. _gl.deleteTexture(textureProperties.__webglTexture);
  13559. }
  13560. if (renderTarget.depthTexture) {
  13561. renderTarget.depthTexture.dispose();
  13562. }
  13563. if (renderTarget.isWebGLCubeRenderTarget) {
  13564. for (var i = 0; i < 6; i++) {
  13565. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13566. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13567. }
  13568. } else {
  13569. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13570. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13571. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13572. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13573. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13574. }
  13575. properties.remove(renderTarget.texture);
  13576. properties.remove(renderTarget);
  13577. } //
  13578. var textureUnits = 0;
  13579. function resetTextureUnits() {
  13580. textureUnits = 0;
  13581. }
  13582. function allocateTextureUnit() {
  13583. var textureUnit = textureUnits;
  13584. if (textureUnit >= maxTextures) {
  13585. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13586. }
  13587. textureUnits += 1;
  13588. return textureUnit;
  13589. } //
  13590. function setTexture2D(texture, slot) {
  13591. var textureProperties = properties.get(texture);
  13592. if (texture.isVideoTexture) updateVideoTexture(texture);
  13593. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13594. var image = texture.image;
  13595. if (image === undefined) {
  13596. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13597. } else if (image.complete === false) {
  13598. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13599. } else {
  13600. uploadTexture(textureProperties, texture, slot);
  13601. return;
  13602. }
  13603. }
  13604. state.activeTexture(33984 + slot);
  13605. state.bindTexture(3553, textureProperties.__webglTexture);
  13606. }
  13607. function setTexture2DArray(texture, slot) {
  13608. var textureProperties = properties.get(texture);
  13609. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13610. uploadTexture(textureProperties, texture, slot);
  13611. return;
  13612. }
  13613. state.activeTexture(33984 + slot);
  13614. state.bindTexture(35866, textureProperties.__webglTexture);
  13615. }
  13616. function setTexture3D(texture, slot) {
  13617. var textureProperties = properties.get(texture);
  13618. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13619. uploadTexture(textureProperties, texture, slot);
  13620. return;
  13621. }
  13622. state.activeTexture(33984 + slot);
  13623. state.bindTexture(32879, textureProperties.__webglTexture);
  13624. }
  13625. function setTextureCube(texture, slot) {
  13626. if (texture.image.length !== 6) return;
  13627. var textureProperties = properties.get(texture);
  13628. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13629. initTexture(textureProperties, texture);
  13630. state.activeTexture(33984 + slot);
  13631. state.bindTexture(34067, textureProperties.__webglTexture);
  13632. _gl.pixelStorei(37440, texture.flipY);
  13633. var isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13634. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13635. var cubeImage = [];
  13636. for (var i = 0; i < 6; i++) {
  13637. if (!isCompressed && !isDataTexture) {
  13638. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13639. } else {
  13640. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13641. }
  13642. }
  13643. var image = cubeImage[0],
  13644. supportsMips = isPowerOfTwo(image) || isWebGL2,
  13645. glFormat = utils.convert(texture.format),
  13646. glType = utils.convert(texture.type),
  13647. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13648. setTextureParameters(34067, texture, supportsMips);
  13649. var mipmaps;
  13650. if (isCompressed) {
  13651. for (var i = 0; i < 6; i++) {
  13652. mipmaps = cubeImage[i].mipmaps;
  13653. for (var j = 0; j < mipmaps.length; j++) {
  13654. var mipmap = mipmaps[j];
  13655. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13656. if (glFormat !== null) {
  13657. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13658. } else {
  13659. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13660. }
  13661. } else {
  13662. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13663. }
  13664. }
  13665. }
  13666. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13667. } else {
  13668. mipmaps = texture.mipmaps;
  13669. for (var i = 0; i < 6; i++) {
  13670. if (isDataTexture) {
  13671. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13672. for (var j = 0; j < mipmaps.length; j++) {
  13673. var mipmap = mipmaps[j];
  13674. var mipmapImage = mipmap.image[i].image;
  13675. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13676. }
  13677. } else {
  13678. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13679. for (var j = 0; j < mipmaps.length; j++) {
  13680. var mipmap = mipmaps[j];
  13681. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13682. }
  13683. }
  13684. }
  13685. textureProperties.__maxMipLevel = mipmaps.length;
  13686. }
  13687. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13688. // We assume images for cube map have the same size.
  13689. generateMipmap(34067, texture, image.width, image.height);
  13690. }
  13691. textureProperties.__version = texture.version;
  13692. if (texture.onUpdate) texture.onUpdate(texture);
  13693. } else {
  13694. state.activeTexture(33984 + slot);
  13695. state.bindTexture(34067, textureProperties.__webglTexture);
  13696. }
  13697. }
  13698. function setTextureCubeDynamic(texture, slot) {
  13699. state.activeTexture(33984 + slot);
  13700. state.bindTexture(34067, properties.get(texture).__webglTexture);
  13701. }
  13702. var wrappingToGL = {
  13703. [RepeatWrapping]: 10497,
  13704. [ClampToEdgeWrapping]: 33071,
  13705. [MirroredRepeatWrapping]: 33648
  13706. };
  13707. var filterToGL = {
  13708. [NearestFilter]: 9728,
  13709. [NearestMipmapNearestFilter]: 9984,
  13710. [NearestMipmapLinearFilter]: 9986,
  13711. [LinearFilter]: 9729,
  13712. [LinearMipmapNearestFilter]: 9985,
  13713. [LinearMipmapLinearFilter]: 9987
  13714. };
  13715. function setTextureParameters(textureType, texture, supportsMips) {
  13716. if (supportsMips) {
  13717. _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
  13718. _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
  13719. if (textureType === 32879 || textureType === 35866) {
  13720. _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
  13721. }
  13722. _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
  13723. _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
  13724. } else {
  13725. _gl.texParameteri(textureType, 10242, 33071);
  13726. _gl.texParameteri(textureType, 10243, 33071);
  13727. if (textureType === 32879 || textureType === 35866) {
  13728. _gl.texParameteri(textureType, 32882, 33071);
  13729. }
  13730. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13731. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13732. }
  13733. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  13734. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  13735. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13736. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13737. }
  13738. }
  13739. var extension = extensions.get('EXT_texture_filter_anisotropic');
  13740. if (extension) {
  13741. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  13742. if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  13743. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13744. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13745. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13746. }
  13747. }
  13748. }
  13749. function initTexture(textureProperties, texture) {
  13750. if (textureProperties.__webglInit === undefined) {
  13751. textureProperties.__webglInit = true;
  13752. texture.addEventListener('dispose', onTextureDispose);
  13753. textureProperties.__webglTexture = _gl.createTexture();
  13754. info.memory.textures++;
  13755. }
  13756. }
  13757. function uploadTexture(textureProperties, texture, slot) {
  13758. var textureType = 3553;
  13759. if (texture.isDataTexture2DArray) textureType = 35866;
  13760. if (texture.isDataTexture3D) textureType = 32879;
  13761. initTexture(textureProperties, texture);
  13762. state.activeTexture(33984 + slot);
  13763. state.bindTexture(textureType, textureProperties.__webglTexture);
  13764. _gl.pixelStorei(37440, texture.flipY);
  13765. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  13766. _gl.pixelStorei(3317, texture.unpackAlignment);
  13767. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  13768. var image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13769. var supportsMips = isPowerOfTwo(image) || isWebGL2,
  13770. glFormat = utils.convert(texture.format),
  13771. glType = utils.convert(texture.type),
  13772. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13773. setTextureParameters(textureType, texture, supportsMips);
  13774. var mipmap,
  13775. mipmaps = texture.mipmaps;
  13776. if (texture.isDepthTexture) {
  13777. // populate depth texture with dummy data
  13778. glInternalFormat = 6402;
  13779. if (isWebGL2) {
  13780. if (texture.type === FloatType) {
  13781. glInternalFormat = 36012;
  13782. } else if (texture.type === UnsignedIntType) {
  13783. glInternalFormat = 33190;
  13784. } else if (texture.type === UnsignedInt248Type) {
  13785. glInternalFormat = 35056;
  13786. } else {
  13787. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13788. }
  13789. } else {
  13790. if (texture.type === FloatType) {
  13791. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13792. }
  13793. } // validation checks for WebGL 1
  13794. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  13795. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13796. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13797. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13798. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13799. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13800. texture.type = UnsignedShortType;
  13801. glType = utils.convert(texture.type);
  13802. }
  13803. }
  13804. if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
  13805. // Depth stencil textures need the DEPTH_STENCIL internal format
  13806. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13807. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13808. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13809. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13810. if (texture.type !== UnsignedInt248Type) {
  13811. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13812. texture.type = UnsignedInt248Type;
  13813. glType = utils.convert(texture.type);
  13814. }
  13815. } //
  13816. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13817. } else if (texture.isDataTexture) {
  13818. // use manually created mipmaps if available
  13819. // if there are no manual mipmaps
  13820. // set 0 level mipmap and then use GL to generate other mipmap levels
  13821. if (mipmaps.length > 0 && supportsMips) {
  13822. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13823. mipmap = mipmaps[i];
  13824. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13825. }
  13826. texture.generateMipmaps = false;
  13827. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13828. } else {
  13829. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13830. textureProperties.__maxMipLevel = 0;
  13831. }
  13832. } else if (texture.isCompressedTexture) {
  13833. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13834. mipmap = mipmaps[i];
  13835. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13836. if (glFormat !== null) {
  13837. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13838. } else {
  13839. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13840. }
  13841. } else {
  13842. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13843. }
  13844. }
  13845. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13846. } else if (texture.isDataTexture2DArray) {
  13847. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13848. textureProperties.__maxMipLevel = 0;
  13849. } else if (texture.isDataTexture3D) {
  13850. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13851. textureProperties.__maxMipLevel = 0;
  13852. } else {
  13853. // regular Texture (image, video, canvas)
  13854. // use manually created mipmaps if available
  13855. // if there are no manual mipmaps
  13856. // set 0 level mipmap and then use GL to generate other mipmap levels
  13857. if (mipmaps.length > 0 && supportsMips) {
  13858. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13859. mipmap = mipmaps[i];
  13860. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  13861. }
  13862. texture.generateMipmaps = false;
  13863. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13864. } else {
  13865. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  13866. textureProperties.__maxMipLevel = 0;
  13867. }
  13868. }
  13869. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13870. generateMipmap(textureType, texture, image.width, image.height);
  13871. }
  13872. textureProperties.__version = texture.version;
  13873. if (texture.onUpdate) texture.onUpdate(texture);
  13874. } // Render targets
  13875. // Setup storage for target texture and bind it to correct framebuffer
  13876. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  13877. var glFormat = utils.convert(renderTarget.texture.format);
  13878. var glType = utils.convert(renderTarget.texture.type);
  13879. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13880. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13881. _gl.bindFramebuffer(36160, framebuffer);
  13882. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  13883. _gl.bindFramebuffer(36160, null);
  13884. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13885. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13886. _gl.bindRenderbuffer(36161, renderbuffer);
  13887. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13888. var glInternalFormat = 33189;
  13889. if (isMultisample) {
  13890. var depthTexture = renderTarget.depthTexture;
  13891. if (depthTexture && depthTexture.isDepthTexture) {
  13892. if (depthTexture.type === FloatType) {
  13893. glInternalFormat = 36012;
  13894. } else if (depthTexture.type === UnsignedIntType) {
  13895. glInternalFormat = 33190;
  13896. }
  13897. }
  13898. var samples = getRenderTargetSamples(renderTarget);
  13899. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13900. } else {
  13901. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13902. }
  13903. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  13904. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13905. if (isMultisample) {
  13906. var samples = getRenderTargetSamples(renderTarget);
  13907. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  13908. } else {
  13909. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  13910. }
  13911. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  13912. } else {
  13913. var glFormat = utils.convert(renderTarget.texture.format);
  13914. var glType = utils.convert(renderTarget.texture.type);
  13915. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13916. if (isMultisample) {
  13917. var samples = getRenderTargetSamples(renderTarget);
  13918. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13919. } else {
  13920. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13921. }
  13922. }
  13923. _gl.bindRenderbuffer(36161, null);
  13924. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13925. function setupDepthTexture(framebuffer, renderTarget) {
  13926. var isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  13927. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13928. _gl.bindFramebuffer(36160, framebuffer);
  13929. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13930. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13931. } // upload an empty depth texture with framebuffer size
  13932. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13933. renderTarget.depthTexture.image.width = renderTarget.width;
  13934. renderTarget.depthTexture.image.height = renderTarget.height;
  13935. renderTarget.depthTexture.needsUpdate = true;
  13936. }
  13937. setTexture2D(renderTarget.depthTexture, 0);
  13938. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13939. if (renderTarget.depthTexture.format === DepthFormat) {
  13940. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  13941. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13942. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  13943. } else {
  13944. throw new Error('Unknown depthTexture format');
  13945. }
  13946. } // Setup GL resources for a non-texture depth buffer
  13947. function setupDepthRenderbuffer(renderTarget) {
  13948. var renderTargetProperties = properties.get(renderTarget);
  13949. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13950. if (renderTarget.depthTexture) {
  13951. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13952. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13953. } else {
  13954. if (isCube) {
  13955. renderTargetProperties.__webglDepthbuffer = [];
  13956. for (var i = 0; i < 6; i++) {
  13957. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  13958. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13959. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  13960. }
  13961. } else {
  13962. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  13963. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13964. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  13965. }
  13966. }
  13967. _gl.bindFramebuffer(36160, null);
  13968. } // Set up GL resources for the render target
  13969. function setupRenderTarget(renderTarget) {
  13970. var renderTargetProperties = properties.get(renderTarget);
  13971. var textureProperties = properties.get(renderTarget.texture);
  13972. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13973. textureProperties.__webglTexture = _gl.createTexture();
  13974. info.memory.textures++;
  13975. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13976. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13977. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  13978. if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
  13979. renderTarget.texture.format = RGBAFormat;
  13980. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  13981. } // Setup framebuffer
  13982. if (isCube) {
  13983. renderTargetProperties.__webglFramebuffer = [];
  13984. for (var i = 0; i < 6; i++) {
  13985. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13986. }
  13987. } else {
  13988. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13989. if (isMultisample) {
  13990. if (isWebGL2) {
  13991. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13992. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13993. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  13994. var glFormat = utils.convert(renderTarget.texture.format);
  13995. var glType = utils.convert(renderTarget.texture.type);
  13996. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13997. var samples = getRenderTargetSamples(renderTarget);
  13998. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13999. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  14000. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  14001. _gl.bindRenderbuffer(36161, null);
  14002. if (renderTarget.depthBuffer) {
  14003. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14004. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14005. }
  14006. _gl.bindFramebuffer(36160, null);
  14007. } else {
  14008. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14009. }
  14010. }
  14011. } // Setup color buffer
  14012. if (isCube) {
  14013. state.bindTexture(34067, textureProperties.__webglTexture);
  14014. setTextureParameters(34067, renderTarget.texture, supportsMips);
  14015. for (var i = 0; i < 6; i++) {
  14016. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  14017. }
  14018. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14019. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  14020. }
  14021. state.bindTexture(34067, null);
  14022. } else {
  14023. state.bindTexture(3553, textureProperties.__webglTexture);
  14024. setTextureParameters(3553, renderTarget.texture, supportsMips);
  14025. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  14026. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14027. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  14028. }
  14029. state.bindTexture(3553, null);
  14030. } // Setup depth and stencil buffers
  14031. if (renderTarget.depthBuffer) {
  14032. setupDepthRenderbuffer(renderTarget);
  14033. }
  14034. }
  14035. function updateRenderTargetMipmap(renderTarget) {
  14036. var texture = renderTarget.texture;
  14037. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
  14038. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14039. var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14040. var webglTexture = properties.get(texture).__webglTexture;
  14041. state.bindTexture(target, webglTexture);
  14042. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  14043. state.bindTexture(target, null);
  14044. }
  14045. }
  14046. function updateMultisampleRenderTarget(renderTarget) {
  14047. if (renderTarget.isWebGLMultisampleRenderTarget) {
  14048. if (isWebGL2) {
  14049. var renderTargetProperties = properties.get(renderTarget);
  14050. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  14051. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  14052. var width = renderTarget.width;
  14053. var height = renderTarget.height;
  14054. var mask = 16384;
  14055. if (renderTarget.depthBuffer) mask |= 256;
  14056. if (renderTarget.stencilBuffer) mask |= 1024;
  14057. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  14058. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
  14059. } else {
  14060. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14061. }
  14062. }
  14063. }
  14064. function getRenderTargetSamples(renderTarget) {
  14065. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  14066. }
  14067. function updateVideoTexture(texture) {
  14068. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14069. if (_videoTextures.get(texture) !== frame) {
  14070. _videoTextures.set(texture, frame);
  14071. texture.update();
  14072. }
  14073. } // backwards compatibility
  14074. var warnedTexture2D = false;
  14075. var warnedTextureCube = false;
  14076. function safeSetTexture2D(texture, slot) {
  14077. if (texture && texture.isWebGLRenderTarget) {
  14078. if (warnedTexture2D === false) {
  14079. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  14080. warnedTexture2D = true;
  14081. }
  14082. texture = texture.texture;
  14083. }
  14084. setTexture2D(texture, slot);
  14085. }
  14086. function safeSetTextureCube(texture, slot) {
  14087. if (texture && texture.isWebGLCubeRenderTarget) {
  14088. if (warnedTextureCube === false) {
  14089. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  14090. warnedTextureCube = true;
  14091. }
  14092. texture = texture.texture;
  14093. } // currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture
  14094. // TODO: unify these code paths
  14095. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  14096. // CompressedTexture can have Array in image :/
  14097. // this function alone should take care of cube textures
  14098. setTextureCube(texture, slot);
  14099. } else {
  14100. // assumed: texture property of THREE.WebGLCubeRenderTarget
  14101. setTextureCubeDynamic(texture, slot);
  14102. }
  14103. } //
  14104. this.allocateTextureUnit = allocateTextureUnit;
  14105. this.resetTextureUnits = resetTextureUnits;
  14106. this.setTexture2D = setTexture2D;
  14107. this.setTexture2DArray = setTexture2DArray;
  14108. this.setTexture3D = setTexture3D;
  14109. this.setTextureCube = setTextureCube;
  14110. this.setTextureCubeDynamic = setTextureCubeDynamic;
  14111. this.setupRenderTarget = setupRenderTarget;
  14112. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14113. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14114. this.safeSetTexture2D = safeSetTexture2D;
  14115. this.safeSetTextureCube = safeSetTextureCube;
  14116. }
  14117. /**
  14118. * @author thespite / http://www.twitter.com/thespite
  14119. */
  14120. function WebGLUtils(gl, extensions, capabilities) {
  14121. var isWebGL2 = capabilities.isWebGL2;
  14122. function convert(p) {
  14123. var extension;
  14124. if (p === UnsignedByteType) return 5121;
  14125. if (p === UnsignedShort4444Type) return 32819;
  14126. if (p === UnsignedShort5551Type) return 32820;
  14127. if (p === UnsignedShort565Type) return 33635;
  14128. if (p === ByteType) return 5120;
  14129. if (p === ShortType) return 5122;
  14130. if (p === UnsignedShortType) return 5123;
  14131. if (p === IntType) return 5124;
  14132. if (p === UnsignedIntType) return 5125;
  14133. if (p === FloatType) return 5126;
  14134. if (p === HalfFloatType) {
  14135. if (isWebGL2) return 5131;
  14136. extension = extensions.get('OES_texture_half_float');
  14137. if (extension !== null) {
  14138. return extension.HALF_FLOAT_OES;
  14139. } else {
  14140. return null;
  14141. }
  14142. }
  14143. if (p === AlphaFormat) return 6406;
  14144. if (p === RGBFormat) return 6407;
  14145. if (p === RGBAFormat) return 6408;
  14146. if (p === LuminanceFormat) return 6409;
  14147. if (p === LuminanceAlphaFormat) return 6410;
  14148. if (p === DepthFormat) return 6402;
  14149. if (p === DepthStencilFormat) return 34041;
  14150. if (p === RedFormat) return 6403; // WebGL2 formats.
  14151. if (p === RedIntegerFormat) return 36244;
  14152. if (p === RGFormat) return 33319;
  14153. if (p === RGIntegerFormat) return 33320;
  14154. if (p === RGBIntegerFormat) return 36248;
  14155. if (p === RGBAIntegerFormat) return 36249;
  14156. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14157. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14158. if (extension !== null) {
  14159. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14160. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14161. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14162. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14163. } else {
  14164. return null;
  14165. }
  14166. }
  14167. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14168. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14169. if (extension !== null) {
  14170. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14171. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14172. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14173. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14174. } else {
  14175. return null;
  14176. }
  14177. }
  14178. if (p === RGB_ETC1_Format) {
  14179. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14180. if (extension !== null) {
  14181. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14182. } else {
  14183. return null;
  14184. }
  14185. }
  14186. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14187. extension = extensions.get('WEBGL_compressed_texture_etc');
  14188. if (extension !== null) {
  14189. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  14190. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  14191. }
  14192. }
  14193. 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 || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
  14194. extension = extensions.get('WEBGL_compressed_texture_astc');
  14195. if (extension !== null) {
  14196. // TODO Complete?
  14197. return p;
  14198. } else {
  14199. return null;
  14200. }
  14201. }
  14202. if (p === RGBA_BPTC_Format) {
  14203. extension = extensions.get('EXT_texture_compression_bptc');
  14204. if (extension !== null) {
  14205. // TODO Complete?
  14206. return p;
  14207. } else {
  14208. return null;
  14209. }
  14210. }
  14211. if (p === UnsignedInt248Type) {
  14212. if (isWebGL2) return 34042;
  14213. extension = extensions.get('WEBGL_depth_texture');
  14214. if (extension !== null) {
  14215. return extension.UNSIGNED_INT_24_8_WEBGL;
  14216. } else {
  14217. return null;
  14218. }
  14219. }
  14220. }
  14221. return {
  14222. convert: convert
  14223. };
  14224. }
  14225. /**
  14226. * @author mrdoob / http://mrdoob.com/
  14227. */
  14228. function ArrayCamera(array) {
  14229. PerspectiveCamera.call(this);
  14230. this.cameras = array || [];
  14231. }
  14232. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  14233. constructor: ArrayCamera,
  14234. isArrayCamera: true
  14235. });
  14236. /**
  14237. * @author mrdoob / http://mrdoob.com/
  14238. */
  14239. function Group() {
  14240. Object3D.call(this);
  14241. this.type = 'Group';
  14242. }
  14243. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  14244. constructor: Group,
  14245. isGroup: true
  14246. });
  14247. /**
  14248. * @author mrdoob / http://mrdoob.com/
  14249. */
  14250. function WebXRManager(renderer, gl) {
  14251. var scope = this;
  14252. var session = null;
  14253. var framebufferScaleFactor = 1.0;
  14254. var referenceSpace = null;
  14255. var referenceSpaceType = 'local-floor';
  14256. var pose = null;
  14257. var controllers = [];
  14258. var inputSourcesMap = new Map(); //
  14259. var cameraL = new PerspectiveCamera();
  14260. cameraL.layers.enable(1);
  14261. cameraL.viewport = new Vector4();
  14262. var cameraR = new PerspectiveCamera();
  14263. cameraR.layers.enable(2);
  14264. cameraR.viewport = new Vector4();
  14265. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  14266. cameraVR.layers.enable(1);
  14267. cameraVR.layers.enable(2);
  14268. var _currentDepthNear = null;
  14269. var _currentDepthFar = null; //
  14270. this.enabled = false;
  14271. this.isPresenting = false;
  14272. this.getController = function (id) {
  14273. var controller = controllers[id];
  14274. if (controller === undefined) {
  14275. controller = {};
  14276. controllers[id] = controller;
  14277. }
  14278. if (controller.targetRay === undefined) {
  14279. controller.targetRay = new Group();
  14280. controller.targetRay.matrixAutoUpdate = false;
  14281. controller.targetRay.visible = false;
  14282. }
  14283. return controller.targetRay;
  14284. };
  14285. this.getControllerGrip = function (id) {
  14286. var controller = controllers[id];
  14287. if (controller === undefined) {
  14288. controller = {};
  14289. controllers[id] = controller;
  14290. }
  14291. if (controller.grip === undefined) {
  14292. controller.grip = new Group();
  14293. controller.grip.matrixAutoUpdate = false;
  14294. controller.grip.visible = false;
  14295. }
  14296. return controller.grip;
  14297. }; //
  14298. function onSessionEvent(event) {
  14299. var controller = inputSourcesMap.get(event.inputSource);
  14300. if (controller) {
  14301. if (controller.targetRay) {
  14302. controller.targetRay.dispatchEvent({
  14303. type: event.type
  14304. });
  14305. }
  14306. if (controller.grip) {
  14307. controller.grip.dispatchEvent({
  14308. type: event.type
  14309. });
  14310. }
  14311. }
  14312. }
  14313. function onSessionEnd() {
  14314. inputSourcesMap.forEach(function (controller, inputSource) {
  14315. if (controller.targetRay) {
  14316. controller.targetRay.dispatchEvent({
  14317. type: 'disconnected',
  14318. data: inputSource
  14319. });
  14320. controller.targetRay.visible = false;
  14321. }
  14322. if (controller.grip) {
  14323. controller.grip.dispatchEvent({
  14324. type: 'disconnected',
  14325. data: inputSource
  14326. });
  14327. controller.grip.visible = false;
  14328. }
  14329. });
  14330. inputSourcesMap.clear(); //
  14331. renderer.setFramebuffer(null);
  14332. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  14333. animation.stop();
  14334. scope.isPresenting = false;
  14335. scope.dispatchEvent({
  14336. type: 'sessionend'
  14337. });
  14338. }
  14339. function onRequestReferenceSpace(value) {
  14340. referenceSpace = value;
  14341. animation.setContext(session);
  14342. animation.start();
  14343. scope.isPresenting = true;
  14344. scope.dispatchEvent({
  14345. type: 'sessionstart'
  14346. });
  14347. }
  14348. this.setFramebufferScaleFactor = function (value) {
  14349. framebufferScaleFactor = value; // Warn if function is used while presenting
  14350. if (scope.isPresenting == true) {
  14351. console.warn("WebXRManager: Cannot change framebuffer scale while presenting VR content");
  14352. }
  14353. };
  14354. this.setReferenceSpaceType = function (value) {
  14355. referenceSpaceType = value;
  14356. };
  14357. this.getReferenceSpace = function () {
  14358. return referenceSpace;
  14359. };
  14360. this.getSession = function () {
  14361. return session;
  14362. };
  14363. this.setSession = function (value) {
  14364. session = value;
  14365. if (session !== null) {
  14366. session.addEventListener('select', onSessionEvent);
  14367. session.addEventListener('selectstart', onSessionEvent);
  14368. session.addEventListener('selectend', onSessionEvent);
  14369. session.addEventListener('squeeze', onSessionEvent);
  14370. session.addEventListener('squeezestart', onSessionEvent);
  14371. session.addEventListener('squeezeend', onSessionEvent);
  14372. session.addEventListener('end', onSessionEnd);
  14373. var attributes = gl.getContextAttributes();
  14374. var layerInit = {
  14375. antialias: attributes.antialias,
  14376. alpha: attributes.alpha,
  14377. depth: attributes.depth,
  14378. stencil: attributes.stencil,
  14379. framebufferScaleFactor: framebufferScaleFactor
  14380. }; // eslint-disable-next-line no-undef
  14381. var baseLayer = new XRWebGLLayer(session, gl, layerInit);
  14382. session.updateRenderState({
  14383. baseLayer: baseLayer
  14384. });
  14385. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  14386. session.addEventListener('inputsourceschange', updateInputSources);
  14387. }
  14388. };
  14389. function updateInputSources(event) {
  14390. var inputSources = session.inputSources; // Assign inputSources to available controllers
  14391. for (var i = 0; i < controllers.length; i++) {
  14392. inputSourcesMap.set(inputSources[i], controllers[i]);
  14393. } // Notify disconnected
  14394. for (var i = 0; i < event.removed.length; i++) {
  14395. var inputSource = event.removed[i];
  14396. var controller = inputSourcesMap.get(inputSource);
  14397. if (controller) {
  14398. if (controller.targetRay) {
  14399. controller.targetRay.dispatchEvent({
  14400. type: 'disconnected',
  14401. data: inputSource
  14402. });
  14403. }
  14404. if (controller.grip) {
  14405. controller.grip.dispatchEvent({
  14406. type: 'disconnected',
  14407. data: inputSource
  14408. });
  14409. }
  14410. inputSourcesMap.delete(inputSource);
  14411. }
  14412. } // Notify connected
  14413. for (var i = 0; i < event.added.length; i++) {
  14414. var inputSource = event.added[i];
  14415. var controller = inputSourcesMap.get(inputSource);
  14416. if (controller) {
  14417. if (controller.targetRay) {
  14418. controller.targetRay.dispatchEvent({
  14419. type: 'connected',
  14420. data: inputSource
  14421. });
  14422. }
  14423. if (controller.grip) {
  14424. controller.grip.dispatchEvent({
  14425. type: 'connected',
  14426. data: inputSource
  14427. });
  14428. }
  14429. }
  14430. }
  14431. } //
  14432. var cameraLPos = new Vector3();
  14433. var cameraRPos = new Vector3();
  14434. /**
  14435. * @author jsantell / https://www.jsantell.com/
  14436. *
  14437. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14438. * the cameras' projection and world matrices have already been set.
  14439. * And that near and far planes are identical for both cameras.
  14440. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14441. */
  14442. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14443. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14444. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14445. var ipd = cameraLPos.distanceTo(cameraRPos);
  14446. var projL = cameraL.projectionMatrix.elements;
  14447. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14448. // most likely identical top and bottom frustum extents.
  14449. // Use the left camera for these values.
  14450. var near = projL[14] / (projL[10] - 1);
  14451. var far = projL[14] / (projL[10] + 1);
  14452. var topFov = (projL[9] + 1) / projL[5];
  14453. var bottomFov = (projL[9] - 1) / projL[5];
  14454. var leftFov = (projL[8] - 1) / projL[0];
  14455. var rightFov = (projR[8] + 1) / projR[0];
  14456. var left = near * leftFov;
  14457. var right = near * rightFov; // Calculate the new camera's position offset from the
  14458. // left camera. xOffset should be roughly half `ipd`.
  14459. var zOffset = ipd / (-leftFov + rightFov);
  14460. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14461. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14462. camera.translateX(xOffset);
  14463. camera.translateZ(zOffset);
  14464. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14465. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  14466. // the values so that the near plane's position does not change in world space,
  14467. // although must now be relative to the new union camera.
  14468. var near2 = near + zOffset;
  14469. var far2 = far + zOffset;
  14470. var left2 = left - xOffset;
  14471. var right2 = right + (ipd - xOffset);
  14472. var top2 = topFov * far / far2 * near2;
  14473. var bottom2 = bottomFov * far / far2 * near2;
  14474. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14475. }
  14476. function updateCamera(camera, parent) {
  14477. if (parent === null) {
  14478. camera.matrixWorld.copy(camera.matrix);
  14479. } else {
  14480. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14481. }
  14482. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  14483. }
  14484. this.getCamera = function (camera) {
  14485. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14486. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14487. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14488. // Note that the new renderState won't apply until the next frame. See #18320
  14489. session.updateRenderState({
  14490. depthNear: cameraVR.near,
  14491. depthFar: cameraVR.far
  14492. });
  14493. _currentDepthNear = cameraVR.near;
  14494. _currentDepthFar = cameraVR.far;
  14495. }
  14496. var parent = camera.parent;
  14497. var cameras = cameraVR.cameras;
  14498. updateCamera(cameraVR, parent);
  14499. for (var i = 0; i < cameras.length; i++) {
  14500. updateCamera(cameras[i], parent);
  14501. } // update camera and its children
  14502. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14503. var children = camera.children;
  14504. for (var i = 0, l = children.length; i < l; i++) {
  14505. children[i].updateMatrixWorld(true);
  14506. }
  14507. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14508. return cameraVR;
  14509. }; // Animation Loop
  14510. var onAnimationFrameCallback = null;
  14511. function onAnimationFrame(time, frame) {
  14512. pose = frame.getViewerPose(referenceSpace);
  14513. if (pose !== null) {
  14514. var views = pose.views;
  14515. var baseLayer = session.renderState.baseLayer;
  14516. renderer.setFramebuffer(baseLayer.framebuffer);
  14517. for (var i = 0; i < views.length; i++) {
  14518. var view = views[i];
  14519. var viewport = baseLayer.getViewport(view);
  14520. var camera = cameraVR.cameras[i];
  14521. camera.matrix.fromArray(view.transform.matrix);
  14522. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14523. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14524. if (i === 0) {
  14525. cameraVR.matrix.copy(camera.matrix);
  14526. }
  14527. }
  14528. } //
  14529. var inputSources = session.inputSources;
  14530. for (var i = 0; i < controllers.length; i++) {
  14531. var controller = controllers[i];
  14532. var inputSource = inputSources[i];
  14533. var inputPose = null;
  14534. var gripPose = null;
  14535. if (inputSource) {
  14536. if (controller.targetRay) {
  14537. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14538. if (inputPose !== null) {
  14539. controller.targetRay.matrix.fromArray(inputPose.transform.matrix);
  14540. controller.targetRay.matrix.decompose(controller.targetRay.position, controller.targetRay.rotation, controller.targetRay.scale);
  14541. }
  14542. }
  14543. if (controller.grip && inputSource.gripSpace) {
  14544. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14545. if (gripPose !== null) {
  14546. controller.grip.matrix.fromArray(gripPose.transform.matrix);
  14547. controller.grip.matrix.decompose(controller.grip.position, controller.grip.rotation, controller.grip.scale);
  14548. }
  14549. }
  14550. }
  14551. if (controller.targetRay) {
  14552. controller.targetRay.visible = inputPose !== null;
  14553. }
  14554. if (controller.grip) {
  14555. controller.grip.visible = gripPose !== null;
  14556. }
  14557. }
  14558. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  14559. }
  14560. var animation = new WebGLAnimation();
  14561. animation.setAnimationLoop(onAnimationFrame);
  14562. this.setAnimationLoop = function (callback) {
  14563. onAnimationFrameCallback = callback;
  14564. };
  14565. this.dispose = function () {};
  14566. }
  14567. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  14568. /**
  14569. * @author supereggbert / http://www.paulbrunt.co.uk/
  14570. * @author mrdoob / http://mrdoob.com/
  14571. * @author alteredq / http://alteredqualia.com/
  14572. * @author szimek / https://github.com/szimek/
  14573. * @author tschw
  14574. */
  14575. function WebGLRenderer(parameters) {
  14576. parameters = parameters || {};
  14577. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  14578. _context = parameters.context !== undefined ? parameters.context : null,
  14579. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14580. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14581. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14582. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14583. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14584. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14585. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14586. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14587. var currentRenderList = null;
  14588. var currentRenderState = null; // public properties
  14589. this.domElement = _canvas; // Debug configuration container
  14590. this.debug = {
  14591. /**
  14592. * Enables error checking and reporting when shader programs are being compiled
  14593. * @type {boolean}
  14594. */
  14595. checkShaderErrors: true
  14596. }; // clearing
  14597. this.autoClear = true;
  14598. this.autoClearColor = true;
  14599. this.autoClearDepth = true;
  14600. this.autoClearStencil = true; // scene graph
  14601. this.sortObjects = true; // user-defined clipping
  14602. this.clippingPlanes = [];
  14603. this.localClippingEnabled = false; // physically based shading
  14604. this.gammaFactor = 2.0; // for backwards compatibility
  14605. this.outputEncoding = LinearEncoding; // physical lights
  14606. this.physicallyCorrectLights = false; // tone mapping
  14607. this.toneMapping = LinearToneMapping;
  14608. this.toneMappingExposure = 1.0;
  14609. this.toneMappingWhitePoint = 1.0; // morphs
  14610. this.maxMorphTargets = 8;
  14611. this.maxMorphNormals = 4; // internal properties
  14612. var _this = this,
  14613. _isContextLost = false,
  14614. // internal state cache
  14615. _framebuffer = null,
  14616. _currentActiveCubeFace = 0,
  14617. _currentActiveMipmapLevel = 0,
  14618. _currentRenderTarget = null,
  14619. _currentFramebuffer = null,
  14620. _currentMaterialId = -1,
  14621. // geometry and program caching
  14622. _currentGeometryProgram = {
  14623. geometry: null,
  14624. program: null,
  14625. wireframe: false
  14626. },
  14627. _currentCamera = null,
  14628. _currentArrayCamera = null,
  14629. _currentViewport = new Vector4(),
  14630. _currentScissor = new Vector4(),
  14631. _currentScissorTest = null,
  14632. //
  14633. _width = _canvas.width,
  14634. _height = _canvas.height,
  14635. _pixelRatio = 1,
  14636. _opaqueSort = null,
  14637. _transparentSort = null,
  14638. _viewport = new Vector4(0, 0, _width, _height),
  14639. _scissor = new Vector4(0, 0, _width, _height),
  14640. _scissorTest = false,
  14641. // frustum
  14642. _frustum = new Frustum(),
  14643. // clipping
  14644. _clipping = new WebGLClipping(),
  14645. _clippingEnabled = false,
  14646. _localClippingEnabled = false,
  14647. // camera matrices cache
  14648. _projScreenMatrix = new Matrix4(),
  14649. _vector3 = new Vector3();
  14650. function getTargetPixelRatio() {
  14651. return _currentRenderTarget === null ? _pixelRatio : 1;
  14652. } // initialize
  14653. var _gl;
  14654. try {
  14655. var contextAttributes = {
  14656. alpha: _alpha,
  14657. depth: _depth,
  14658. stencil: _stencil,
  14659. antialias: _antialias,
  14660. premultipliedAlpha: _premultipliedAlpha,
  14661. preserveDrawingBuffer: _preserveDrawingBuffer,
  14662. powerPreference: _powerPreference,
  14663. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  14664. xrCompatible: true
  14665. }; // event listeners must be registered before WebGL context is created, see #12753
  14666. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14667. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14668. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  14669. if (_gl === null) {
  14670. if (_canvas.getContext('webgl') !== null) {
  14671. throw new Error('Error creating WebGL context with your selected attributes.');
  14672. } else {
  14673. throw new Error('Error creating WebGL context.');
  14674. }
  14675. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14676. if (_gl.getShaderPrecisionFormat === undefined) {
  14677. _gl.getShaderPrecisionFormat = function () {
  14678. return {
  14679. 'rangeMin': 1,
  14680. 'rangeMax': 1,
  14681. 'precision': 1
  14682. };
  14683. };
  14684. }
  14685. } catch (error) {
  14686. console.error('THREE.WebGLRenderer: ' + error.message);
  14687. throw error;
  14688. }
  14689. var extensions, capabilities, state, info;
  14690. var properties, textures, attributes, geometries, objects;
  14691. var programCache, renderLists, renderStates;
  14692. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14693. var utils;
  14694. function initGLContext() {
  14695. extensions = new WebGLExtensions(_gl);
  14696. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14697. if (capabilities.isWebGL2 === false) {
  14698. extensions.get('WEBGL_depth_texture');
  14699. extensions.get('OES_texture_float');
  14700. extensions.get('OES_texture_half_float');
  14701. extensions.get('OES_texture_half_float_linear');
  14702. extensions.get('OES_standard_derivatives');
  14703. extensions.get('OES_element_index_uint');
  14704. extensions.get('ANGLE_instanced_arrays');
  14705. }
  14706. extensions.get('OES_texture_float_linear');
  14707. utils = new WebGLUtils(_gl, extensions, capabilities);
  14708. state = new WebGLState(_gl, extensions, capabilities);
  14709. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14710. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14711. info = new WebGLInfo(_gl);
  14712. properties = new WebGLProperties();
  14713. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14714. attributes = new WebGLAttributes(_gl, capabilities);
  14715. geometries = new WebGLGeometries(_gl, attributes, info);
  14716. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14717. morphtargets = new WebGLMorphtargets(_gl);
  14718. programCache = new WebGLPrograms(_this, extensions, capabilities);
  14719. renderLists = new WebGLRenderLists();
  14720. renderStates = new WebGLRenderStates();
  14721. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  14722. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14723. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14724. info.programs = programCache.programs;
  14725. _this.capabilities = capabilities;
  14726. _this.extensions = extensions;
  14727. _this.properties = properties;
  14728. _this.renderLists = renderLists;
  14729. _this.state = state;
  14730. _this.info = info;
  14731. }
  14732. initGLContext(); // xr
  14733. var xr = new WebXRManager(_this, _gl);
  14734. this.xr = xr; // shadow map
  14735. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  14736. this.shadowMap = shadowMap; // API
  14737. this.getContext = function () {
  14738. return _gl;
  14739. };
  14740. this.getContextAttributes = function () {
  14741. return _gl.getContextAttributes();
  14742. };
  14743. this.forceContextLoss = function () {
  14744. var extension = extensions.get('WEBGL_lose_context');
  14745. if (extension) extension.loseContext();
  14746. };
  14747. this.forceContextRestore = function () {
  14748. var extension = extensions.get('WEBGL_lose_context');
  14749. if (extension) extension.restoreContext();
  14750. };
  14751. this.getPixelRatio = function () {
  14752. return _pixelRatio;
  14753. };
  14754. this.setPixelRatio = function (value) {
  14755. if (value === undefined) return;
  14756. _pixelRatio = value;
  14757. this.setSize(_width, _height, false);
  14758. };
  14759. this.getSize = function (target) {
  14760. if (target === undefined) {
  14761. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14762. target = new Vector2();
  14763. }
  14764. return target.set(_width, _height);
  14765. };
  14766. this.setSize = function (width, height, updateStyle) {
  14767. if (xr.isPresenting) {
  14768. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14769. return;
  14770. }
  14771. _width = width;
  14772. _height = height;
  14773. _canvas.width = Math.floor(width * _pixelRatio);
  14774. _canvas.height = Math.floor(height * _pixelRatio);
  14775. if (updateStyle !== false) {
  14776. _canvas.style.width = width + 'px';
  14777. _canvas.style.height = height + 'px';
  14778. }
  14779. this.setViewport(0, 0, width, height);
  14780. };
  14781. this.getDrawingBufferSize = function (target) {
  14782. if (target === undefined) {
  14783. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14784. target = new Vector2();
  14785. }
  14786. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14787. };
  14788. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14789. _width = width;
  14790. _height = height;
  14791. _pixelRatio = pixelRatio;
  14792. _canvas.width = Math.floor(width * pixelRatio);
  14793. _canvas.height = Math.floor(height * pixelRatio);
  14794. this.setViewport(0, 0, width, height);
  14795. };
  14796. this.getCurrentViewport = function (target) {
  14797. if (target === undefined) {
  14798. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14799. target = new Vector4();
  14800. }
  14801. return target.copy(_currentViewport);
  14802. };
  14803. this.getViewport = function (target) {
  14804. return target.copy(_viewport);
  14805. };
  14806. this.setViewport = function (x, y, width, height) {
  14807. if (x.isVector4) {
  14808. _viewport.set(x.x, x.y, x.z, x.w);
  14809. } else {
  14810. _viewport.set(x, y, width, height);
  14811. }
  14812. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14813. };
  14814. this.getScissor = function (target) {
  14815. return target.copy(_scissor);
  14816. };
  14817. this.setScissor = function (x, y, width, height) {
  14818. if (x.isVector4) {
  14819. _scissor.set(x.x, x.y, x.z, x.w);
  14820. } else {
  14821. _scissor.set(x, y, width, height);
  14822. }
  14823. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14824. };
  14825. this.getScissorTest = function () {
  14826. return _scissorTest;
  14827. };
  14828. this.setScissorTest = function (boolean) {
  14829. state.setScissorTest(_scissorTest = boolean);
  14830. };
  14831. this.setOpaqueSort = function (method) {
  14832. _opaqueSort = method;
  14833. };
  14834. this.setTransparentSort = function (method) {
  14835. _transparentSort = method;
  14836. }; // Clearing
  14837. this.getClearColor = function () {
  14838. return background.getClearColor();
  14839. };
  14840. this.setClearColor = function () {
  14841. background.setClearColor.apply(background, arguments);
  14842. };
  14843. this.getClearAlpha = function () {
  14844. return background.getClearAlpha();
  14845. };
  14846. this.setClearAlpha = function () {
  14847. background.setClearAlpha.apply(background, arguments);
  14848. };
  14849. this.clear = function (color, depth, stencil) {
  14850. var bits = 0;
  14851. if (color === undefined || color) bits |= 16384;
  14852. if (depth === undefined || depth) bits |= 256;
  14853. if (stencil === undefined || stencil) bits |= 1024;
  14854. _gl.clear(bits);
  14855. };
  14856. this.clearColor = function () {
  14857. this.clear(true, false, false);
  14858. };
  14859. this.clearDepth = function () {
  14860. this.clear(false, true, false);
  14861. };
  14862. this.clearStencil = function () {
  14863. this.clear(false, false, true);
  14864. }; //
  14865. this.dispose = function () {
  14866. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14867. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14868. renderLists.dispose();
  14869. renderStates.dispose();
  14870. properties.dispose();
  14871. objects.dispose();
  14872. xr.dispose();
  14873. animation.stop();
  14874. this.forceContextLoss();
  14875. }; // Events
  14876. function onContextLost(event) {
  14877. event.preventDefault();
  14878. console.log('THREE.WebGLRenderer: Context Lost.');
  14879. _isContextLost = true;
  14880. }
  14881. function onContextRestore()
  14882. /* event */
  14883. {
  14884. console.log('THREE.WebGLRenderer: Context Restored.');
  14885. _isContextLost = false;
  14886. initGLContext();
  14887. }
  14888. function onMaterialDispose(event) {
  14889. var material = event.target;
  14890. material.removeEventListener('dispose', onMaterialDispose);
  14891. deallocateMaterial(material);
  14892. } // Buffer deallocation
  14893. function deallocateMaterial(material) {
  14894. releaseMaterialProgramReference(material);
  14895. properties.remove(material);
  14896. }
  14897. function releaseMaterialProgramReference(material) {
  14898. var programInfo = properties.get(material).program;
  14899. material.program = undefined;
  14900. if (programInfo !== undefined) {
  14901. programCache.releaseProgram(programInfo);
  14902. }
  14903. } // Buffer rendering
  14904. function renderObjectImmediate(object, program) {
  14905. object.render(function (object) {
  14906. _this.renderBufferImmediate(object, program);
  14907. });
  14908. }
  14909. this.renderBufferImmediate = function (object, program) {
  14910. state.initAttributes();
  14911. var buffers = properties.get(object);
  14912. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14913. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14914. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14915. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14916. var programAttributes = program.getAttributes();
  14917. if (object.hasPositions) {
  14918. _gl.bindBuffer(34962, buffers.position);
  14919. _gl.bufferData(34962, object.positionArray, 35048);
  14920. state.enableAttribute(programAttributes.position);
  14921. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  14922. }
  14923. if (object.hasNormals) {
  14924. _gl.bindBuffer(34962, buffers.normal);
  14925. _gl.bufferData(34962, object.normalArray, 35048);
  14926. state.enableAttribute(programAttributes.normal);
  14927. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  14928. }
  14929. if (object.hasUvs) {
  14930. _gl.bindBuffer(34962, buffers.uv);
  14931. _gl.bufferData(34962, object.uvArray, 35048);
  14932. state.enableAttribute(programAttributes.uv);
  14933. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  14934. }
  14935. if (object.hasColors) {
  14936. _gl.bindBuffer(34962, buffers.color);
  14937. _gl.bufferData(34962, object.colorArray, 35048);
  14938. state.enableAttribute(programAttributes.color);
  14939. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  14940. }
  14941. state.disableUnusedAttributes();
  14942. _gl.drawArrays(4, 0, object.count);
  14943. object.count = 0;
  14944. };
  14945. var tempScene = new Scene();
  14946. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14947. if (scene === null) scene = tempScene; // renderBufferDirect second parameter used to be fog (could be null)
  14948. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14949. var program = setProgram(camera, scene, material, object);
  14950. state.setMaterial(material, frontFaceCW);
  14951. var updateBuffers = false;
  14952. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  14953. _currentGeometryProgram.geometry = geometry.id;
  14954. _currentGeometryProgram.program = program.id;
  14955. _currentGeometryProgram.wireframe = material.wireframe === true;
  14956. updateBuffers = true;
  14957. }
  14958. if (material.morphTargets || material.morphNormals) {
  14959. morphtargets.update(object, geometry, material, program);
  14960. updateBuffers = true;
  14961. } //
  14962. var index = geometry.index;
  14963. var position = geometry.attributes.position; //
  14964. if (index === null) {
  14965. if (position === undefined || position.count === 0) return;
  14966. } else if (index.count === 0) {
  14967. return;
  14968. } //
  14969. var rangeFactor = 1;
  14970. if (material.wireframe === true) {
  14971. index = geometries.getWireframeAttribute(geometry);
  14972. rangeFactor = 2;
  14973. }
  14974. var attribute;
  14975. var renderer = bufferRenderer;
  14976. if (index !== null) {
  14977. attribute = attributes.get(index);
  14978. renderer = indexedBufferRenderer;
  14979. renderer.setIndex(attribute);
  14980. }
  14981. if (updateBuffers) {
  14982. setupVertexAttributes(object, geometry, material, program);
  14983. if (index !== null) {
  14984. _gl.bindBuffer(34963, attribute.buffer);
  14985. }
  14986. } //
  14987. var dataCount = index !== null ? index.count : position.count;
  14988. var rangeStart = geometry.drawRange.start * rangeFactor;
  14989. var rangeCount = geometry.drawRange.count * rangeFactor;
  14990. var groupStart = group !== null ? group.start * rangeFactor : 0;
  14991. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14992. var drawStart = Math.max(rangeStart, groupStart);
  14993. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14994. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  14995. if (drawCount === 0) return; //
  14996. if (object.isMesh) {
  14997. if (material.wireframe === true) {
  14998. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14999. renderer.setMode(1);
  15000. } else {
  15001. renderer.setMode(4);
  15002. }
  15003. } else if (object.isLine) {
  15004. var lineWidth = material.linewidth;
  15005. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  15006. state.setLineWidth(lineWidth * getTargetPixelRatio());
  15007. if (object.isLineSegments) {
  15008. renderer.setMode(1);
  15009. } else if (object.isLineLoop) {
  15010. renderer.setMode(2);
  15011. } else {
  15012. renderer.setMode(3);
  15013. }
  15014. } else if (object.isPoints) {
  15015. renderer.setMode(0);
  15016. } else if (object.isSprite) {
  15017. renderer.setMode(4);
  15018. }
  15019. if (object.isInstancedMesh) {
  15020. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  15021. } else if (geometry.isInstancedBufferGeometry) {
  15022. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  15023. } else {
  15024. renderer.render(drawStart, drawCount);
  15025. }
  15026. };
  15027. function setupVertexAttributes(object, geometry, material, program) {
  15028. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  15029. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  15030. }
  15031. state.initAttributes();
  15032. var geometryAttributes = geometry.attributes;
  15033. var programAttributes = program.getAttributes();
  15034. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15035. for (var name in programAttributes) {
  15036. var programAttribute = programAttributes[name];
  15037. if (programAttribute >= 0) {
  15038. var geometryAttribute = geometryAttributes[name];
  15039. if (geometryAttribute !== undefined) {
  15040. var normalized = geometryAttribute.normalized;
  15041. var size = geometryAttribute.itemSize;
  15042. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  15043. if (attribute === undefined) continue;
  15044. var buffer = attribute.buffer;
  15045. var type = attribute.type;
  15046. var bytesPerElement = attribute.bytesPerElement;
  15047. if (geometryAttribute.isInterleavedBufferAttribute) {
  15048. var data = geometryAttribute.data;
  15049. var stride = data.stride;
  15050. var offset = geometryAttribute.offset;
  15051. if (data && data.isInstancedInterleavedBuffer) {
  15052. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  15053. if (geometry.maxInstancedCount === undefined) {
  15054. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  15055. }
  15056. } else {
  15057. state.enableAttribute(programAttribute);
  15058. }
  15059. _gl.bindBuffer(34962, buffer);
  15060. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  15061. } else {
  15062. if (geometryAttribute.isInstancedBufferAttribute) {
  15063. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  15064. if (geometry.maxInstancedCount === undefined) {
  15065. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15066. }
  15067. } else {
  15068. state.enableAttribute(programAttribute);
  15069. }
  15070. _gl.bindBuffer(34962, buffer);
  15071. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  15072. }
  15073. } else if (name === 'instanceMatrix') {
  15074. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  15075. if (attribute === undefined) continue;
  15076. var buffer = attribute.buffer;
  15077. var type = attribute.type;
  15078. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  15079. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  15080. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  15081. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  15082. _gl.bindBuffer(34962, buffer);
  15083. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  15084. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  15085. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  15086. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  15087. } else if (materialDefaultAttributeValues !== undefined) {
  15088. var value = materialDefaultAttributeValues[name];
  15089. if (value !== undefined) {
  15090. switch (value.length) {
  15091. case 2:
  15092. _gl.vertexAttrib2fv(programAttribute, value);
  15093. break;
  15094. case 3:
  15095. _gl.vertexAttrib3fv(programAttribute, value);
  15096. break;
  15097. case 4:
  15098. _gl.vertexAttrib4fv(programAttribute, value);
  15099. break;
  15100. default:
  15101. _gl.vertexAttrib1fv(programAttribute, value);
  15102. }
  15103. }
  15104. }
  15105. }
  15106. }
  15107. state.disableUnusedAttributes();
  15108. } // Compile
  15109. this.compile = function (scene, camera) {
  15110. currentRenderState = renderStates.get(scene, camera);
  15111. currentRenderState.init();
  15112. scene.traverse(function (object) {
  15113. if (object.isLight) {
  15114. currentRenderState.pushLight(object);
  15115. if (object.castShadow) {
  15116. currentRenderState.pushShadow(object);
  15117. }
  15118. }
  15119. });
  15120. currentRenderState.setupLights(camera);
  15121. var compiled = {};
  15122. scene.traverse(function (object) {
  15123. if (object.material) {
  15124. if (Array.isArray(object.material)) {
  15125. for (var i = 0; i < object.material.length; i++) {
  15126. if (object.material[i].uuid in compiled === false) {
  15127. initMaterial(object.material[i], scene, object);
  15128. compiled[object.material[i].uuid] = true;
  15129. }
  15130. }
  15131. } else if (object.material.uuid in compiled === false) {
  15132. initMaterial(object.material, scene, object);
  15133. compiled[object.material.uuid] = true;
  15134. }
  15135. }
  15136. });
  15137. }; // Animation Loop
  15138. var onAnimationFrameCallback = null;
  15139. function onAnimationFrame(time) {
  15140. if (xr.isPresenting) return;
  15141. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15142. }
  15143. var animation = new WebGLAnimation();
  15144. animation.setAnimationLoop(onAnimationFrame);
  15145. if (typeof window !== 'undefined') animation.setContext(window);
  15146. this.setAnimationLoop = function (callback) {
  15147. onAnimationFrameCallback = callback;
  15148. xr.setAnimationLoop(callback);
  15149. animation.start();
  15150. }; // Rendering
  15151. this.render = function (scene, camera) {
  15152. var renderTarget, forceClear;
  15153. if (arguments[2] !== undefined) {
  15154. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  15155. renderTarget = arguments[2];
  15156. }
  15157. if (arguments[3] !== undefined) {
  15158. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  15159. forceClear = arguments[3];
  15160. }
  15161. if (!(camera && camera.isCamera)) {
  15162. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15163. return;
  15164. }
  15165. if (_isContextLost) return; // reset caching for this frame
  15166. _currentGeometryProgram.geometry = null;
  15167. _currentGeometryProgram.program = null;
  15168. _currentGeometryProgram.wireframe = false;
  15169. _currentMaterialId = -1;
  15170. _currentCamera = null; // update scene graph
  15171. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15172. if (camera.parent === null) camera.updateMatrixWorld();
  15173. if (xr.enabled && xr.isPresenting) {
  15174. camera = xr.getCamera(camera);
  15175. } //
  15176. currentRenderState = renderStates.get(scene, camera);
  15177. currentRenderState.init();
  15178. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  15179. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15180. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15181. _localClippingEnabled = this.localClippingEnabled;
  15182. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15183. currentRenderList = renderLists.get(scene, camera);
  15184. currentRenderList.init();
  15185. projectObject(scene, camera, 0, _this.sortObjects);
  15186. currentRenderList.finish();
  15187. if (_this.sortObjects === true) {
  15188. currentRenderList.sort(_opaqueSort, _transparentSort);
  15189. } //
  15190. if (_clippingEnabled) _clipping.beginShadows();
  15191. var shadowsArray = currentRenderState.state.shadowsArray;
  15192. shadowMap.render(shadowsArray, scene, camera);
  15193. currentRenderState.setupLights(camera);
  15194. if (_clippingEnabled) _clipping.endShadows(); //
  15195. if (this.info.autoReset) this.info.reset();
  15196. if (renderTarget !== undefined) {
  15197. this.setRenderTarget(renderTarget);
  15198. } //
  15199. background.render(currentRenderList, scene, camera, forceClear); // render scene
  15200. var opaqueObjects = currentRenderList.opaque;
  15201. var transparentObjects = currentRenderList.transparent;
  15202. if (scene.overrideMaterial) {
  15203. var overrideMaterial = scene.overrideMaterial;
  15204. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  15205. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  15206. } else {
  15207. // opaque pass (front-to-back order)
  15208. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  15209. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  15210. } //
  15211. scene.onAfterRender(_this, scene, camera); //
  15212. if (_currentRenderTarget !== null) {
  15213. // Generate mipmap if we're using any kind of mipmap filtering
  15214. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  15215. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  15216. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  15217. state.buffers.depth.setTest(true);
  15218. state.buffers.depth.setMask(true);
  15219. state.buffers.color.setMask(true);
  15220. state.setPolygonOffset(false); // _gl.finish();
  15221. currentRenderList = null;
  15222. currentRenderState = null;
  15223. };
  15224. function projectObject(object, camera, groupOrder, sortObjects) {
  15225. if (object.visible === false) return;
  15226. var visible = object.layers.test(camera.layers);
  15227. if (visible) {
  15228. if (object.isGroup) {
  15229. groupOrder = object.renderOrder;
  15230. } else if (object.isLOD) {
  15231. if (object.autoUpdate === true) object.update(camera);
  15232. } else if (object.isLight) {
  15233. currentRenderState.pushLight(object);
  15234. if (object.castShadow) {
  15235. currentRenderState.pushShadow(object);
  15236. }
  15237. } else if (object.isSprite) {
  15238. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15239. if (sortObjects) {
  15240. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15241. }
  15242. var geometry = objects.update(object);
  15243. var material = object.material;
  15244. if (material.visible) {
  15245. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15246. }
  15247. }
  15248. } else if (object.isImmediateRenderObject) {
  15249. if (sortObjects) {
  15250. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15251. }
  15252. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15253. } else if (object.isMesh || object.isLine || object.isPoints) {
  15254. if (object.isSkinnedMesh) {
  15255. // update skeleton only once in a frame
  15256. if (object.skeleton.frame !== info.render.frame) {
  15257. object.skeleton.update();
  15258. object.skeleton.frame = info.render.frame;
  15259. }
  15260. }
  15261. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15262. if (sortObjects) {
  15263. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15264. }
  15265. var geometry = objects.update(object);
  15266. var material = object.material;
  15267. if (Array.isArray(material)) {
  15268. var groups = geometry.groups;
  15269. for (var i = 0, l = groups.length; i < l; i++) {
  15270. var group = groups[i];
  15271. var groupMaterial = material[group.materialIndex];
  15272. if (groupMaterial && groupMaterial.visible) {
  15273. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15274. }
  15275. }
  15276. } else if (material.visible) {
  15277. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15278. }
  15279. }
  15280. }
  15281. }
  15282. var children = object.children;
  15283. for (var i = 0, l = children.length; i < l; i++) {
  15284. projectObject(children[i], camera, groupOrder, sortObjects);
  15285. }
  15286. }
  15287. function renderObjects(renderList, scene, camera, overrideMaterial) {
  15288. for (var i = 0, l = renderList.length; i < l; i++) {
  15289. var renderItem = renderList[i];
  15290. var object = renderItem.object;
  15291. var geometry = renderItem.geometry;
  15292. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15293. var group = renderItem.group;
  15294. if (camera.isArrayCamera) {
  15295. _currentArrayCamera = camera;
  15296. var cameras = camera.cameras;
  15297. for (var j = 0, jl = cameras.length; j < jl; j++) {
  15298. var camera2 = cameras[j];
  15299. if (object.layers.test(camera2.layers)) {
  15300. state.viewport(_currentViewport.copy(camera2.viewport));
  15301. currentRenderState.setupLights(camera2);
  15302. renderObject(object, scene, camera2, geometry, material, group);
  15303. }
  15304. }
  15305. } else {
  15306. _currentArrayCamera = null;
  15307. renderObject(object, scene, camera, geometry, material, group);
  15308. }
  15309. }
  15310. }
  15311. function renderObject(object, scene, camera, geometry, material, group) {
  15312. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15313. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15314. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15315. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15316. if (object.isImmediateRenderObject) {
  15317. var program = setProgram(camera, scene, material, object);
  15318. state.setMaterial(material);
  15319. _currentGeometryProgram.geometry = null;
  15320. _currentGeometryProgram.program = null;
  15321. _currentGeometryProgram.wireframe = false;
  15322. renderObjectImmediate(object, program);
  15323. } else {
  15324. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15325. }
  15326. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15327. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15328. }
  15329. function initMaterial(material, scene, object) {
  15330. var materialProperties = properties.get(material);
  15331. var lights = currentRenderState.state.lights;
  15332. var shadowsArray = currentRenderState.state.shadowsArray;
  15333. var lightsStateVersion = lights.state.version;
  15334. var parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object);
  15335. var programCacheKey = programCache.getProgramCacheKey(parameters);
  15336. var program = materialProperties.program;
  15337. var programChange = true;
  15338. if (program === undefined) {
  15339. // new material
  15340. material.addEventListener('dispose', onMaterialDispose);
  15341. } else if (program.cacheKey !== programCacheKey) {
  15342. // changed glsl or parameters
  15343. releaseMaterialProgramReference(material);
  15344. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  15345. materialProperties.lightsStateVersion = lightsStateVersion;
  15346. programChange = false;
  15347. } else if (parameters.shaderID !== undefined) {
  15348. // same glsl and uniform list
  15349. return;
  15350. } else {
  15351. // only rebuild uniform list
  15352. programChange = false;
  15353. }
  15354. if (programChange) {
  15355. program = programCache.acquireProgram(parameters, programCacheKey);
  15356. materialProperties.program = program;
  15357. materialProperties.uniforms = parameters.uniforms;
  15358. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15359. materialProperties.outputEncoding = _this.outputEncoding;
  15360. material.program = program;
  15361. }
  15362. var programAttributes = program.getAttributes();
  15363. if (material.morphTargets) {
  15364. material.numSupportedMorphTargets = 0;
  15365. for (var i = 0; i < _this.maxMorphTargets; i++) {
  15366. if (programAttributes['morphTarget' + i] >= 0) {
  15367. material.numSupportedMorphTargets++;
  15368. }
  15369. }
  15370. }
  15371. if (material.morphNormals) {
  15372. material.numSupportedMorphNormals = 0;
  15373. for (var i = 0; i < _this.maxMorphNormals; i++) {
  15374. if (programAttributes['morphNormal' + i] >= 0) {
  15375. material.numSupportedMorphNormals++;
  15376. }
  15377. }
  15378. }
  15379. var uniforms = materialProperties.uniforms;
  15380. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15381. materialProperties.numClippingPlanes = _clipping.numPlanes;
  15382. materialProperties.numIntersection = _clipping.numIntersection;
  15383. uniforms.clippingPlanes = _clipping.uniform;
  15384. }
  15385. materialProperties.fog = scene.fog; // store the light setup it was created for
  15386. materialProperties.needsLights = materialNeedsLights(material);
  15387. materialProperties.lightsStateVersion = lightsStateVersion;
  15388. if (materialProperties.needsLights) {
  15389. // wire up the material to this renderer's lighting state
  15390. uniforms.ambientLightColor.value = lights.state.ambient;
  15391. uniforms.lightProbe.value = lights.state.probe;
  15392. uniforms.directionalLights.value = lights.state.directional;
  15393. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15394. uniforms.spotLights.value = lights.state.spot;
  15395. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15396. uniforms.rectAreaLights.value = lights.state.rectArea;
  15397. uniforms.pointLights.value = lights.state.point;
  15398. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15399. uniforms.hemisphereLights.value = lights.state.hemi;
  15400. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15401. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15402. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15403. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15404. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15405. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15406. }
  15407. var progUniforms = materialProperties.program.getUniforms(),
  15408. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15409. materialProperties.uniformsList = uniformsList;
  15410. }
  15411. function setProgram(camera, scene, material, object) {
  15412. textures.resetTextureUnits();
  15413. var fog = scene.fog;
  15414. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  15415. var materialProperties = properties.get(material);
  15416. var lights = currentRenderState.state.lights;
  15417. if (_clippingEnabled) {
  15418. if (_localClippingEnabled || camera !== _currentCamera) {
  15419. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15420. // object instead of the material, once it becomes feasible
  15421. // (#8465, #8379)
  15422. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  15423. }
  15424. }
  15425. if (material.version === materialProperties.__version) {
  15426. if (materialProperties.program === undefined) {
  15427. initMaterial(material, scene, object);
  15428. } else if (material.fog && materialProperties.fog !== fog) {
  15429. initMaterial(material, scene, object);
  15430. } else if (materialProperties.environment !== environment) {
  15431. initMaterial(material, scene, object);
  15432. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15433. initMaterial(material, scene, object);
  15434. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  15435. initMaterial(material, scene, object);
  15436. } else if (materialProperties.outputEncoding !== _this.outputEncoding) {
  15437. initMaterial(material, scene, object);
  15438. }
  15439. } else {
  15440. initMaterial(material, scene, object);
  15441. materialProperties.__version = material.version;
  15442. }
  15443. var refreshProgram = false;
  15444. var refreshMaterial = false;
  15445. var refreshLights = false;
  15446. var program = materialProperties.program,
  15447. p_uniforms = program.getUniforms(),
  15448. m_uniforms = materialProperties.uniforms;
  15449. if (state.useProgram(program.program)) {
  15450. refreshProgram = true;
  15451. refreshMaterial = true;
  15452. refreshLights = true;
  15453. }
  15454. if (material.id !== _currentMaterialId) {
  15455. _currentMaterialId = material.id;
  15456. refreshMaterial = true;
  15457. }
  15458. if (refreshProgram || _currentCamera !== camera) {
  15459. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15460. if (capabilities.logarithmicDepthBuffer) {
  15461. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15462. }
  15463. if (_currentCamera !== camera) {
  15464. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15465. // now, in case this material supports lights - or later, when
  15466. // the next material that does gets activated:
  15467. refreshMaterial = true; // set to true on material change
  15468. refreshLights = true; // remains set until update done
  15469. } // load material specific uniforms
  15470. // (shader material also gets them for the sake of genericity)
  15471. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  15472. var uCamPos = p_uniforms.map.cameraPosition;
  15473. if (uCamPos !== undefined) {
  15474. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15475. }
  15476. }
  15477. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  15478. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  15479. }
  15480. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  15481. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15482. }
  15483. } // skinning uniforms must be set even if material didn't change
  15484. // auto-setting of texture unit for bone texture must go before other textures
  15485. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15486. if (material.skinning) {
  15487. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15488. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15489. var skeleton = object.skeleton;
  15490. if (skeleton) {
  15491. var bones = skeleton.bones;
  15492. if (capabilities.floatVertexTextures) {
  15493. if (skeleton.boneTexture === undefined) {
  15494. // layout (1 matrix = 4 pixels)
  15495. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15496. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15497. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15498. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15499. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15500. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  15501. size = MathUtils.ceilPowerOfTwo(size);
  15502. size = Math.max(size, 4);
  15503. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  15504. boneMatrices.set(skeleton.boneMatrices); // copy current values
  15505. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  15506. skeleton.boneMatrices = boneMatrices;
  15507. skeleton.boneTexture = boneTexture;
  15508. skeleton.boneTextureSize = size;
  15509. }
  15510. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15511. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15512. } else {
  15513. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15514. }
  15515. }
  15516. }
  15517. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15518. materialProperties.receiveShadow = object.receiveShadow;
  15519. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15520. }
  15521. if (refreshMaterial) {
  15522. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15523. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  15524. if (materialProperties.needsLights) {
  15525. // the current material requires lighting info
  15526. // note: all lighting uniforms are always set correctly
  15527. // they simply reference the renderer's state for their
  15528. // values
  15529. //
  15530. // use the current material's .needsUpdate flags to set
  15531. // the GL state when required
  15532. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15533. } // refresh uniforms common to several materials
  15534. if (fog && material.fog) {
  15535. refreshUniformsFog(m_uniforms, fog);
  15536. }
  15537. if (material.isMeshBasicMaterial) {
  15538. refreshUniformsCommon(m_uniforms, material);
  15539. } else if (material.isMeshLambertMaterial) {
  15540. refreshUniformsCommon(m_uniforms, material);
  15541. refreshUniformsLambert(m_uniforms, material);
  15542. } else if (material.isMeshToonMaterial) {
  15543. refreshUniformsCommon(m_uniforms, material);
  15544. refreshUniformsToon(m_uniforms, material);
  15545. } else if (material.isMeshPhongMaterial) {
  15546. refreshUniformsCommon(m_uniforms, material);
  15547. refreshUniformsPhong(m_uniforms, material);
  15548. } else if (material.isMeshStandardMaterial) {
  15549. refreshUniformsCommon(m_uniforms, material, environment);
  15550. if (material.isMeshPhysicalMaterial) {
  15551. refreshUniformsPhysical(m_uniforms, material, environment);
  15552. } else {
  15553. refreshUniformsStandard(m_uniforms, material, environment);
  15554. }
  15555. } else if (material.isMeshMatcapMaterial) {
  15556. refreshUniformsCommon(m_uniforms, material);
  15557. refreshUniformsMatcap(m_uniforms, material);
  15558. } else if (material.isMeshDepthMaterial) {
  15559. refreshUniformsCommon(m_uniforms, material);
  15560. refreshUniformsDepth(m_uniforms, material);
  15561. } else if (material.isMeshDistanceMaterial) {
  15562. refreshUniformsCommon(m_uniforms, material);
  15563. refreshUniformsDistance(m_uniforms, material);
  15564. } else if (material.isMeshNormalMaterial) {
  15565. refreshUniformsCommon(m_uniforms, material);
  15566. refreshUniformsNormal(m_uniforms, material);
  15567. } else if (material.isLineBasicMaterial) {
  15568. refreshUniformsLine(m_uniforms, material);
  15569. if (material.isLineDashedMaterial) {
  15570. refreshUniformsDash(m_uniforms, material);
  15571. }
  15572. } else if (material.isPointsMaterial) {
  15573. refreshUniformsPoints(m_uniforms, material);
  15574. } else if (material.isSpriteMaterial) {
  15575. refreshUniformsSprites(m_uniforms, material);
  15576. } else if (material.isShadowMaterial) {
  15577. m_uniforms.color.value.copy(material.color);
  15578. m_uniforms.opacity.value = material.opacity;
  15579. } // RectAreaLight Texture
  15580. // TODO (mrdoob): Find a nicer implementation
  15581. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  15582. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  15583. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15584. if (material.isShaderMaterial) {
  15585. material.uniformsNeedUpdate = false; // #15581
  15586. }
  15587. }
  15588. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15589. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15590. material.uniformsNeedUpdate = false;
  15591. }
  15592. if (material.isSpriteMaterial) {
  15593. p_uniforms.setValue(_gl, 'center', object.center);
  15594. } // common matrices
  15595. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15596. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15597. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15598. return program;
  15599. } // Uniforms (refresh uniforms objects)
  15600. function refreshUniformsCommon(uniforms, material, environment) {
  15601. uniforms.opacity.value = material.opacity;
  15602. if (material.color) {
  15603. uniforms.diffuse.value.copy(material.color);
  15604. }
  15605. if (material.emissive) {
  15606. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15607. }
  15608. if (material.map) {
  15609. uniforms.map.value = material.map;
  15610. }
  15611. if (material.alphaMap) {
  15612. uniforms.alphaMap.value = material.alphaMap;
  15613. }
  15614. if (material.specularMap) {
  15615. uniforms.specularMap.value = material.specularMap;
  15616. }
  15617. var envMap = material.envMap || environment;
  15618. if (envMap) {
  15619. uniforms.envMap.value = envMap;
  15620. uniforms.flipEnvMap.value = envMap.isCubeTexture ? -1 : 1;
  15621. uniforms.reflectivity.value = material.reflectivity;
  15622. uniforms.refractionRatio.value = material.refractionRatio;
  15623. uniforms.maxMipLevel.value = properties.get(envMap).__maxMipLevel;
  15624. }
  15625. if (material.lightMap) {
  15626. uniforms.lightMap.value = material.lightMap;
  15627. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15628. }
  15629. if (material.aoMap) {
  15630. uniforms.aoMap.value = material.aoMap;
  15631. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15632. } // uv repeat and offset setting priorities
  15633. // 1. color map
  15634. // 2. specular map
  15635. // 3. normal map
  15636. // 4. bump map
  15637. // 5. alpha map
  15638. // 6. emissive map
  15639. var uvScaleMap;
  15640. if (material.map) {
  15641. uvScaleMap = material.map;
  15642. } else if (material.specularMap) {
  15643. uvScaleMap = material.specularMap;
  15644. } else if (material.displacementMap) {
  15645. uvScaleMap = material.displacementMap;
  15646. } else if (material.normalMap) {
  15647. uvScaleMap = material.normalMap;
  15648. } else if (material.bumpMap) {
  15649. uvScaleMap = material.bumpMap;
  15650. } else if (material.roughnessMap) {
  15651. uvScaleMap = material.roughnessMap;
  15652. } else if (material.metalnessMap) {
  15653. uvScaleMap = material.metalnessMap;
  15654. } else if (material.alphaMap) {
  15655. uvScaleMap = material.alphaMap;
  15656. } else if (material.emissiveMap) {
  15657. uvScaleMap = material.emissiveMap;
  15658. }
  15659. if (uvScaleMap !== undefined) {
  15660. // backwards compatibility
  15661. if (uvScaleMap.isWebGLRenderTarget) {
  15662. uvScaleMap = uvScaleMap.texture;
  15663. }
  15664. if (uvScaleMap.matrixAutoUpdate === true) {
  15665. uvScaleMap.updateMatrix();
  15666. }
  15667. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15668. } // uv repeat and offset setting priorities for uv2
  15669. // 1. ao map
  15670. // 2. light map
  15671. var uv2ScaleMap;
  15672. if (material.aoMap) {
  15673. uv2ScaleMap = material.aoMap;
  15674. } else if (material.lightMap) {
  15675. uv2ScaleMap = material.lightMap;
  15676. }
  15677. if (uv2ScaleMap !== undefined) {
  15678. // backwards compatibility
  15679. if (uv2ScaleMap.isWebGLRenderTarget) {
  15680. uv2ScaleMap = uv2ScaleMap.texture;
  15681. }
  15682. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15683. uv2ScaleMap.updateMatrix();
  15684. }
  15685. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  15686. }
  15687. }
  15688. function refreshUniformsLine(uniforms, material) {
  15689. uniforms.diffuse.value.copy(material.color);
  15690. uniforms.opacity.value = material.opacity;
  15691. }
  15692. function refreshUniformsDash(uniforms, material) {
  15693. uniforms.dashSize.value = material.dashSize;
  15694. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15695. uniforms.scale.value = material.scale;
  15696. }
  15697. function refreshUniformsPoints(uniforms, material) {
  15698. uniforms.diffuse.value.copy(material.color);
  15699. uniforms.opacity.value = material.opacity;
  15700. uniforms.size.value = material.size * _pixelRatio;
  15701. uniforms.scale.value = _height * 0.5;
  15702. if (material.map) {
  15703. uniforms.map.value = material.map;
  15704. }
  15705. if (material.alphaMap) {
  15706. uniforms.alphaMap.value = material.alphaMap;
  15707. } // uv repeat and offset setting priorities
  15708. // 1. color map
  15709. // 2. alpha map
  15710. var uvScaleMap;
  15711. if (material.map) {
  15712. uvScaleMap = material.map;
  15713. } else if (material.alphaMap) {
  15714. uvScaleMap = material.alphaMap;
  15715. }
  15716. if (uvScaleMap !== undefined) {
  15717. if (uvScaleMap.matrixAutoUpdate === true) {
  15718. uvScaleMap.updateMatrix();
  15719. }
  15720. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15721. }
  15722. }
  15723. function refreshUniformsSprites(uniforms, material) {
  15724. uniforms.diffuse.value.copy(material.color);
  15725. uniforms.opacity.value = material.opacity;
  15726. uniforms.rotation.value = material.rotation;
  15727. if (material.map) {
  15728. uniforms.map.value = material.map;
  15729. }
  15730. if (material.alphaMap) {
  15731. uniforms.alphaMap.value = material.alphaMap;
  15732. } // uv repeat and offset setting priorities
  15733. // 1. color map
  15734. // 2. alpha map
  15735. var uvScaleMap;
  15736. if (material.map) {
  15737. uvScaleMap = material.map;
  15738. } else if (material.alphaMap) {
  15739. uvScaleMap = material.alphaMap;
  15740. }
  15741. if (uvScaleMap !== undefined) {
  15742. if (uvScaleMap.matrixAutoUpdate === true) {
  15743. uvScaleMap.updateMatrix();
  15744. }
  15745. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15746. }
  15747. }
  15748. function refreshUniformsFog(uniforms, fog) {
  15749. uniforms.fogColor.value.copy(fog.color);
  15750. if (fog.isFog) {
  15751. uniforms.fogNear.value = fog.near;
  15752. uniforms.fogFar.value = fog.far;
  15753. } else if (fog.isFogExp2) {
  15754. uniforms.fogDensity.value = fog.density;
  15755. }
  15756. }
  15757. function refreshUniformsLambert(uniforms, material) {
  15758. if (material.emissiveMap) {
  15759. uniforms.emissiveMap.value = material.emissiveMap;
  15760. }
  15761. }
  15762. function refreshUniformsPhong(uniforms, material) {
  15763. uniforms.specular.value.copy(material.specular);
  15764. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15765. if (material.emissiveMap) {
  15766. uniforms.emissiveMap.value = material.emissiveMap;
  15767. }
  15768. if (material.bumpMap) {
  15769. uniforms.bumpMap.value = material.bumpMap;
  15770. uniforms.bumpScale.value = material.bumpScale;
  15771. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15772. }
  15773. if (material.normalMap) {
  15774. uniforms.normalMap.value = material.normalMap;
  15775. uniforms.normalScale.value.copy(material.normalScale);
  15776. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15777. }
  15778. if (material.displacementMap) {
  15779. uniforms.displacementMap.value = material.displacementMap;
  15780. uniforms.displacementScale.value = material.displacementScale;
  15781. uniforms.displacementBias.value = material.displacementBias;
  15782. }
  15783. }
  15784. function refreshUniformsToon(uniforms, material) {
  15785. uniforms.specular.value.copy(material.specular);
  15786. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15787. if (material.gradientMap) {
  15788. uniforms.gradientMap.value = material.gradientMap;
  15789. }
  15790. if (material.emissiveMap) {
  15791. uniforms.emissiveMap.value = material.emissiveMap;
  15792. }
  15793. if (material.bumpMap) {
  15794. uniforms.bumpMap.value = material.bumpMap;
  15795. uniforms.bumpScale.value = material.bumpScale;
  15796. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15797. }
  15798. if (material.normalMap) {
  15799. uniforms.normalMap.value = material.normalMap;
  15800. uniforms.normalScale.value.copy(material.normalScale);
  15801. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15802. }
  15803. if (material.displacementMap) {
  15804. uniforms.displacementMap.value = material.displacementMap;
  15805. uniforms.displacementScale.value = material.displacementScale;
  15806. uniforms.displacementBias.value = material.displacementBias;
  15807. }
  15808. }
  15809. function refreshUniformsStandard(uniforms, material, environment) {
  15810. uniforms.roughness.value = material.roughness;
  15811. uniforms.metalness.value = material.metalness;
  15812. if (material.roughnessMap) {
  15813. uniforms.roughnessMap.value = material.roughnessMap;
  15814. }
  15815. if (material.metalnessMap) {
  15816. uniforms.metalnessMap.value = material.metalnessMap;
  15817. }
  15818. if (material.emissiveMap) {
  15819. uniforms.emissiveMap.value = material.emissiveMap;
  15820. }
  15821. if (material.bumpMap) {
  15822. uniforms.bumpMap.value = material.bumpMap;
  15823. uniforms.bumpScale.value = material.bumpScale;
  15824. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15825. }
  15826. if (material.normalMap) {
  15827. uniforms.normalMap.value = material.normalMap;
  15828. uniforms.normalScale.value.copy(material.normalScale);
  15829. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15830. }
  15831. if (material.displacementMap) {
  15832. uniforms.displacementMap.value = material.displacementMap;
  15833. uniforms.displacementScale.value = material.displacementScale;
  15834. uniforms.displacementBias.value = material.displacementBias;
  15835. }
  15836. if (material.envMap || environment) {
  15837. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15838. uniforms.envMapIntensity.value = material.envMapIntensity;
  15839. }
  15840. }
  15841. function refreshUniformsPhysical(uniforms, material, environment) {
  15842. refreshUniformsStandard(uniforms, material, environment);
  15843. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  15844. uniforms.clearcoat.value = material.clearcoat;
  15845. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15846. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  15847. if (material.clearcoatMap) {
  15848. uniforms.clearcoatMap.value = material.clearcoatMap;
  15849. }
  15850. if (material.clearcoatRoughnessMap) {
  15851. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15852. }
  15853. if (material.clearcoatNormalMap) {
  15854. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15855. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15856. if (material.side === BackSide) {
  15857. uniforms.clearcoatNormalScale.value.negate();
  15858. }
  15859. }
  15860. uniforms.transparency.value = material.transparency;
  15861. }
  15862. function refreshUniformsMatcap(uniforms, material) {
  15863. if (material.matcap) {
  15864. uniforms.matcap.value = material.matcap;
  15865. }
  15866. if (material.bumpMap) {
  15867. uniforms.bumpMap.value = material.bumpMap;
  15868. uniforms.bumpScale.value = material.bumpScale;
  15869. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15870. }
  15871. if (material.normalMap) {
  15872. uniforms.normalMap.value = material.normalMap;
  15873. uniforms.normalScale.value.copy(material.normalScale);
  15874. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15875. }
  15876. if (material.displacementMap) {
  15877. uniforms.displacementMap.value = material.displacementMap;
  15878. uniforms.displacementScale.value = material.displacementScale;
  15879. uniforms.displacementBias.value = material.displacementBias;
  15880. }
  15881. }
  15882. function refreshUniformsDepth(uniforms, material) {
  15883. if (material.displacementMap) {
  15884. uniforms.displacementMap.value = material.displacementMap;
  15885. uniforms.displacementScale.value = material.displacementScale;
  15886. uniforms.displacementBias.value = material.displacementBias;
  15887. }
  15888. }
  15889. function refreshUniformsDistance(uniforms, material) {
  15890. if (material.displacementMap) {
  15891. uniforms.displacementMap.value = material.displacementMap;
  15892. uniforms.displacementScale.value = material.displacementScale;
  15893. uniforms.displacementBias.value = material.displacementBias;
  15894. }
  15895. uniforms.referencePosition.value.copy(material.referencePosition);
  15896. uniforms.nearDistance.value = material.nearDistance;
  15897. uniforms.farDistance.value = material.farDistance;
  15898. }
  15899. function refreshUniformsNormal(uniforms, material) {
  15900. if (material.bumpMap) {
  15901. uniforms.bumpMap.value = material.bumpMap;
  15902. uniforms.bumpScale.value = material.bumpScale;
  15903. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15904. }
  15905. if (material.normalMap) {
  15906. uniforms.normalMap.value = material.normalMap;
  15907. uniforms.normalScale.value.copy(material.normalScale);
  15908. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15909. }
  15910. if (material.displacementMap) {
  15911. uniforms.displacementMap.value = material.displacementMap;
  15912. uniforms.displacementScale.value = material.displacementScale;
  15913. uniforms.displacementBias.value = material.displacementBias;
  15914. }
  15915. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15916. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15917. uniforms.ambientLightColor.needsUpdate = value;
  15918. uniforms.lightProbe.needsUpdate = value;
  15919. uniforms.directionalLights.needsUpdate = value;
  15920. uniforms.directionalLightShadows.needsUpdate = value;
  15921. uniforms.pointLights.needsUpdate = value;
  15922. uniforms.pointLightShadows.needsUpdate = value;
  15923. uniforms.spotLights.needsUpdate = value;
  15924. uniforms.spotLightShadows.needsUpdate = value;
  15925. uniforms.rectAreaLights.needsUpdate = value;
  15926. uniforms.hemisphereLights.needsUpdate = value;
  15927. }
  15928. function materialNeedsLights(material) {
  15929. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15930. } //
  15931. this.setFramebuffer = function (value) {
  15932. if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
  15933. _framebuffer = value;
  15934. };
  15935. this.getActiveCubeFace = function () {
  15936. return _currentActiveCubeFace;
  15937. };
  15938. this.getActiveMipmapLevel = function () {
  15939. return _currentActiveMipmapLevel;
  15940. };
  15941. this.getRenderTarget = function () {
  15942. return _currentRenderTarget;
  15943. };
  15944. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  15945. _currentRenderTarget = renderTarget;
  15946. _currentActiveCubeFace = activeCubeFace;
  15947. _currentActiveMipmapLevel = activeMipmapLevel;
  15948. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15949. textures.setupRenderTarget(renderTarget);
  15950. }
  15951. var framebuffer = _framebuffer;
  15952. var isCube = false;
  15953. if (renderTarget) {
  15954. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15955. if (renderTarget.isWebGLCubeRenderTarget) {
  15956. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  15957. isCube = true;
  15958. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15959. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15960. } else {
  15961. framebuffer = __webglFramebuffer;
  15962. }
  15963. _currentViewport.copy(renderTarget.viewport);
  15964. _currentScissor.copy(renderTarget.scissor);
  15965. _currentScissorTest = renderTarget.scissorTest;
  15966. } else {
  15967. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15968. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15969. _currentScissorTest = _scissorTest;
  15970. }
  15971. if (_currentFramebuffer !== framebuffer) {
  15972. _gl.bindFramebuffer(36160, framebuffer);
  15973. _currentFramebuffer = framebuffer;
  15974. }
  15975. state.viewport(_currentViewport);
  15976. state.scissor(_currentScissor);
  15977. state.setScissorTest(_currentScissorTest);
  15978. if (isCube) {
  15979. var textureProperties = properties.get(renderTarget.texture);
  15980. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  15981. }
  15982. };
  15983. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15984. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15985. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15986. return;
  15987. }
  15988. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15989. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15990. framebuffer = framebuffer[activeCubeFaceIndex];
  15991. }
  15992. if (framebuffer) {
  15993. var restore = false;
  15994. if (framebuffer !== _currentFramebuffer) {
  15995. _gl.bindFramebuffer(36160, framebuffer);
  15996. restore = true;
  15997. }
  15998. try {
  15999. var texture = renderTarget.texture;
  16000. var textureFormat = texture.format;
  16001. var textureType = texture.type;
  16002. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  16003. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16004. return;
  16005. }
  16006. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  16007. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16008. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  16009. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16010. return;
  16011. }
  16012. if (_gl.checkFramebufferStatus(36160) === 36053) {
  16013. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16014. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16015. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16016. }
  16017. } else {
  16018. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16019. }
  16020. } finally {
  16021. if (restore) {
  16022. _gl.bindFramebuffer(36160, _currentFramebuffer);
  16023. }
  16024. }
  16025. }
  16026. };
  16027. this.copyFramebufferToTexture = function (position, texture, level) {
  16028. if (level === undefined) level = 0;
  16029. var levelScale = Math.pow(2, -level);
  16030. var width = Math.floor(texture.image.width * levelScale);
  16031. var height = Math.floor(texture.image.height * levelScale);
  16032. var glFormat = utils.convert(texture.format);
  16033. textures.setTexture2D(texture, 0);
  16034. _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
  16035. state.unbindTexture();
  16036. };
  16037. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  16038. var width = srcTexture.image.width;
  16039. var height = srcTexture.image.height;
  16040. var glFormat = utils.convert(dstTexture.format);
  16041. var glType = utils.convert(dstTexture.type);
  16042. textures.setTexture2D(dstTexture, 0);
  16043. if (srcTexture.isDataTexture) {
  16044. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16045. } else {
  16046. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  16047. }
  16048. state.unbindTexture();
  16049. };
  16050. this.initTexture = function (texture) {
  16051. textures.setTexture2D(texture, 0);
  16052. state.unbindTexture();
  16053. };
  16054. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16055. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16056. detail: this
  16057. })); // eslint-disable-line no-undef
  16058. }
  16059. }
  16060. /**
  16061. * @author mrdoob / http://mrdoob.com/
  16062. * @author alteredq / http://alteredqualia.com/
  16063. */
  16064. function FogExp2(color, density) {
  16065. this.name = '';
  16066. this.color = new Color(color);
  16067. this.density = density !== undefined ? density : 0.00025;
  16068. }
  16069. Object.assign(FogExp2.prototype, {
  16070. isFogExp2: true,
  16071. clone: function () {
  16072. return new FogExp2(this.color, this.density);
  16073. },
  16074. toJSON: function ()
  16075. /* meta */
  16076. {
  16077. return {
  16078. type: 'FogExp2',
  16079. color: this.color.getHex(),
  16080. density: this.density
  16081. };
  16082. }
  16083. });
  16084. /**
  16085. * @author mrdoob / http://mrdoob.com/
  16086. * @author alteredq / http://alteredqualia.com/
  16087. */
  16088. function Fog(color, near, far) {
  16089. this.name = '';
  16090. this.color = new Color(color);
  16091. this.near = near !== undefined ? near : 1;
  16092. this.far = far !== undefined ? far : 1000;
  16093. }
  16094. Object.assign(Fog.prototype, {
  16095. isFog: true,
  16096. clone: function () {
  16097. return new Fog(this.color, this.near, this.far);
  16098. },
  16099. toJSON: function ()
  16100. /* meta */
  16101. {
  16102. return {
  16103. type: 'Fog',
  16104. color: this.color.getHex(),
  16105. near: this.near,
  16106. far: this.far
  16107. };
  16108. }
  16109. });
  16110. /**
  16111. * @author benaadams / https://twitter.com/ben_a_adams
  16112. */
  16113. function InterleavedBuffer(array, stride) {
  16114. this.array = array;
  16115. this.stride = stride;
  16116. this.count = array !== undefined ? array.length / stride : 0;
  16117. this.usage = StaticDrawUsage;
  16118. this.updateRange = {
  16119. offset: 0,
  16120. count: -1
  16121. };
  16122. this.version = 0;
  16123. }
  16124. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  16125. set: function (value) {
  16126. if (value === true) this.version++;
  16127. }
  16128. });
  16129. Object.assign(InterleavedBuffer.prototype, {
  16130. isInterleavedBuffer: true,
  16131. onUploadCallback: function () {},
  16132. setUsage: function (value) {
  16133. this.usage = value;
  16134. return this;
  16135. },
  16136. copy: function (source) {
  16137. this.array = new source.array.constructor(source.array);
  16138. this.count = source.count;
  16139. this.stride = source.stride;
  16140. this.usage = source.usage;
  16141. return this;
  16142. },
  16143. copyAt: function (index1, attribute, index2) {
  16144. index1 *= this.stride;
  16145. index2 *= attribute.stride;
  16146. for (var i = 0, l = this.stride; i < l; i++) {
  16147. this.array[index1 + i] = attribute.array[index2 + i];
  16148. }
  16149. return this;
  16150. },
  16151. set: function (value, offset) {
  16152. if (offset === undefined) offset = 0;
  16153. this.array.set(value, offset);
  16154. return this;
  16155. },
  16156. clone: function () {
  16157. return new this.constructor().copy(this);
  16158. },
  16159. onUpload: function (callback) {
  16160. this.onUploadCallback = callback;
  16161. return this;
  16162. }
  16163. });
  16164. /**
  16165. * @author benaadams / https://twitter.com/ben_a_adams
  16166. */
  16167. var _vector$6 = new Vector3();
  16168. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  16169. this.data = interleavedBuffer;
  16170. this.itemSize = itemSize;
  16171. this.offset = offset;
  16172. this.normalized = normalized === true;
  16173. }
  16174. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  16175. count: {
  16176. get: function () {
  16177. return this.data.count;
  16178. }
  16179. },
  16180. array: {
  16181. get: function () {
  16182. return this.data.array;
  16183. }
  16184. }
  16185. });
  16186. Object.assign(InterleavedBufferAttribute.prototype, {
  16187. isInterleavedBufferAttribute: true,
  16188. applyMatrix4: function (m) {
  16189. for (var i = 0, l = this.data.count; i < l; i++) {
  16190. _vector$6.x = this.getX(i);
  16191. _vector$6.y = this.getY(i);
  16192. _vector$6.z = this.getZ(i);
  16193. _vector$6.applyMatrix4(m);
  16194. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16195. }
  16196. return this;
  16197. },
  16198. setX: function (index, x) {
  16199. this.data.array[index * this.data.stride + this.offset] = x;
  16200. return this;
  16201. },
  16202. setY: function (index, y) {
  16203. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16204. return this;
  16205. },
  16206. setZ: function (index, z) {
  16207. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16208. return this;
  16209. },
  16210. setW: function (index, w) {
  16211. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16212. return this;
  16213. },
  16214. getX: function (index) {
  16215. return this.data.array[index * this.data.stride + this.offset];
  16216. },
  16217. getY: function (index) {
  16218. return this.data.array[index * this.data.stride + this.offset + 1];
  16219. },
  16220. getZ: function (index) {
  16221. return this.data.array[index * this.data.stride + this.offset + 2];
  16222. },
  16223. getW: function (index) {
  16224. return this.data.array[index * this.data.stride + this.offset + 3];
  16225. },
  16226. setXY: function (index, x, y) {
  16227. index = index * this.data.stride + this.offset;
  16228. this.data.array[index + 0] = x;
  16229. this.data.array[index + 1] = y;
  16230. return this;
  16231. },
  16232. setXYZ: function (index, x, y, z) {
  16233. index = index * this.data.stride + this.offset;
  16234. this.data.array[index + 0] = x;
  16235. this.data.array[index + 1] = y;
  16236. this.data.array[index + 2] = z;
  16237. return this;
  16238. },
  16239. setXYZW: function (index, x, y, z, w) {
  16240. index = index * this.data.stride + this.offset;
  16241. this.data.array[index + 0] = x;
  16242. this.data.array[index + 1] = y;
  16243. this.data.array[index + 2] = z;
  16244. this.data.array[index + 3] = w;
  16245. return this;
  16246. }
  16247. });
  16248. /**
  16249. * @author alteredq / http://alteredqualia.com/
  16250. *
  16251. * parameters = {
  16252. * color: <hex>,
  16253. * map: new THREE.Texture( <Image> ),
  16254. * alphaMap: new THREE.Texture( <Image> ),
  16255. * rotation: <float>,
  16256. * sizeAttenuation: <bool>
  16257. * }
  16258. */
  16259. function SpriteMaterial(parameters) {
  16260. Material.call(this);
  16261. this.type = 'SpriteMaterial';
  16262. this.color = new Color(0xffffff);
  16263. this.map = null;
  16264. this.alphaMap = null;
  16265. this.rotation = 0;
  16266. this.sizeAttenuation = true;
  16267. this.transparent = true;
  16268. this.setValues(parameters);
  16269. }
  16270. SpriteMaterial.prototype = Object.create(Material.prototype);
  16271. SpriteMaterial.prototype.constructor = SpriteMaterial;
  16272. SpriteMaterial.prototype.isSpriteMaterial = true;
  16273. SpriteMaterial.prototype.copy = function (source) {
  16274. Material.prototype.copy.call(this, source);
  16275. this.color.copy(source.color);
  16276. this.map = source.map;
  16277. this.alphaMap = source.alphaMap;
  16278. this.rotation = source.rotation;
  16279. this.sizeAttenuation = source.sizeAttenuation;
  16280. return this;
  16281. };
  16282. /**
  16283. * @author mikael emtinger / http://gomo.se/
  16284. * @author alteredq / http://alteredqualia.com/
  16285. */
  16286. var _geometry;
  16287. var _intersectPoint = new Vector3();
  16288. var _worldScale = new Vector3();
  16289. var _mvPosition = new Vector3();
  16290. var _alignedPosition = new Vector2();
  16291. var _rotatedPosition = new Vector2();
  16292. var _viewWorldMatrix = new Matrix4();
  16293. var _vA$1 = new Vector3();
  16294. var _vB$1 = new Vector3();
  16295. var _vC$1 = new Vector3();
  16296. var _uvA$1 = new Vector2();
  16297. var _uvB$1 = new Vector2();
  16298. var _uvC$1 = new Vector2();
  16299. function Sprite(material) {
  16300. Object3D.call(this);
  16301. this.type = 'Sprite';
  16302. if (_geometry === undefined) {
  16303. _geometry = new BufferGeometry();
  16304. 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]);
  16305. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  16306. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  16307. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  16308. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  16309. }
  16310. this.geometry = _geometry;
  16311. this.material = material !== undefined ? material : new SpriteMaterial();
  16312. this.center = new Vector2(0.5, 0.5);
  16313. }
  16314. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  16315. constructor: Sprite,
  16316. isSprite: true,
  16317. raycast: function (raycaster, intersects) {
  16318. if (raycaster.camera === null) {
  16319. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  16320. }
  16321. _worldScale.setFromMatrixScale(this.matrixWorld);
  16322. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  16323. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  16324. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  16325. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  16326. _worldScale.multiplyScalar(-_mvPosition.z);
  16327. }
  16328. var rotation = this.material.rotation;
  16329. var sin, cos;
  16330. if (rotation !== 0) {
  16331. cos = Math.cos(rotation);
  16332. sin = Math.sin(rotation);
  16333. }
  16334. var center = this.center;
  16335. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16336. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16337. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16338. _uvA$1.set(0, 0);
  16339. _uvB$1.set(1, 0);
  16340. _uvC$1.set(1, 1); // check first triangle
  16341. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  16342. if (intersect === null) {
  16343. // check second triangle
  16344. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16345. _uvB$1.set(0, 1);
  16346. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  16347. if (intersect === null) {
  16348. return;
  16349. }
  16350. }
  16351. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16352. if (distance < raycaster.near || distance > raycaster.far) return;
  16353. intersects.push({
  16354. distance: distance,
  16355. point: _intersectPoint.clone(),
  16356. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  16357. face: null,
  16358. object: this
  16359. });
  16360. },
  16361. clone: function () {
  16362. return new this.constructor(this.material).copy(this);
  16363. },
  16364. copy: function (source) {
  16365. Object3D.prototype.copy.call(this, source);
  16366. if (source.center !== undefined) this.center.copy(source.center);
  16367. return this;
  16368. }
  16369. });
  16370. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16371. // compute position in camera space
  16372. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16373. if (sin !== undefined) {
  16374. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16375. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16376. } else {
  16377. _rotatedPosition.copy(_alignedPosition);
  16378. }
  16379. vertexPosition.copy(mvPosition);
  16380. vertexPosition.x += _rotatedPosition.x;
  16381. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16382. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16383. }
  16384. /**
  16385. * @author mikael emtinger / http://gomo.se/
  16386. * @author alteredq / http://alteredqualia.com/
  16387. * @author mrdoob / http://mrdoob.com/
  16388. */
  16389. var _v1$4 = new Vector3();
  16390. var _v2$2 = new Vector3();
  16391. function LOD() {
  16392. Object3D.call(this);
  16393. this._currentLevel = 0;
  16394. this.type = 'LOD';
  16395. Object.defineProperties(this, {
  16396. levels: {
  16397. enumerable: true,
  16398. value: []
  16399. }
  16400. });
  16401. this.autoUpdate = true;
  16402. }
  16403. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  16404. constructor: LOD,
  16405. isLOD: true,
  16406. copy: function (source) {
  16407. Object3D.prototype.copy.call(this, source, false);
  16408. var levels = source.levels;
  16409. for (var i = 0, l = levels.length; i < l; i++) {
  16410. var level = levels[i];
  16411. this.addLevel(level.object.clone(), level.distance);
  16412. }
  16413. this.autoUpdate = source.autoUpdate;
  16414. return this;
  16415. },
  16416. addLevel: function (object, distance) {
  16417. if (distance === undefined) distance = 0;
  16418. distance = Math.abs(distance);
  16419. var levels = this.levels;
  16420. for (var l = 0; l < levels.length; l++) {
  16421. if (distance < levels[l].distance) {
  16422. break;
  16423. }
  16424. }
  16425. levels.splice(l, 0, {
  16426. distance: distance,
  16427. object: object
  16428. });
  16429. this.add(object);
  16430. return this;
  16431. },
  16432. getCurrentLevel: function () {
  16433. return this._currentLevel;
  16434. },
  16435. getObjectForDistance: function (distance) {
  16436. var levels = this.levels;
  16437. if (levels.length > 0) {
  16438. for (var i = 1, l = levels.length; i < l; i++) {
  16439. if (distance < levels[i].distance) {
  16440. break;
  16441. }
  16442. }
  16443. return levels[i - 1].object;
  16444. }
  16445. return null;
  16446. },
  16447. raycast: function (raycaster, intersects) {
  16448. var levels = this.levels;
  16449. if (levels.length > 0) {
  16450. _v1$4.setFromMatrixPosition(this.matrixWorld);
  16451. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  16452. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16453. }
  16454. },
  16455. update: function (camera) {
  16456. var levels = this.levels;
  16457. if (levels.length > 1) {
  16458. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  16459. _v2$2.setFromMatrixPosition(this.matrixWorld);
  16460. var distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
  16461. levels[0].object.visible = true;
  16462. for (var i = 1, l = levels.length; i < l; i++) {
  16463. if (distance >= levels[i].distance) {
  16464. levels[i - 1].object.visible = false;
  16465. levels[i].object.visible = true;
  16466. } else {
  16467. break;
  16468. }
  16469. }
  16470. this._currentLevel = i - 1;
  16471. for (; i < l; i++) {
  16472. levels[i].object.visible = false;
  16473. }
  16474. }
  16475. },
  16476. toJSON: function (meta) {
  16477. var data = Object3D.prototype.toJSON.call(this, meta);
  16478. if (this.autoUpdate === false) data.object.autoUpdate = false;
  16479. data.object.levels = [];
  16480. var levels = this.levels;
  16481. for (var i = 0, l = levels.length; i < l; i++) {
  16482. var level = levels[i];
  16483. data.object.levels.push({
  16484. object: level.object.uuid,
  16485. distance: level.distance
  16486. });
  16487. }
  16488. return data;
  16489. }
  16490. });
  16491. /**
  16492. * @author mikael emtinger / http://gomo.se/
  16493. * @author alteredq / http://alteredqualia.com/
  16494. * @author ikerr / http://verold.com
  16495. */
  16496. function SkinnedMesh(geometry, material) {
  16497. if (geometry && geometry.isGeometry) {
  16498. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16499. }
  16500. Mesh.call(this, geometry, material);
  16501. this.type = 'SkinnedMesh';
  16502. this.bindMode = 'attached';
  16503. this.bindMatrix = new Matrix4();
  16504. this.bindMatrixInverse = new Matrix4();
  16505. }
  16506. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16507. constructor: SkinnedMesh,
  16508. isSkinnedMesh: true,
  16509. bind: function (skeleton, bindMatrix) {
  16510. this.skeleton = skeleton;
  16511. if (bindMatrix === undefined) {
  16512. this.updateMatrixWorld(true);
  16513. this.skeleton.calculateInverses();
  16514. bindMatrix = this.matrixWorld;
  16515. }
  16516. this.bindMatrix.copy(bindMatrix);
  16517. this.bindMatrixInverse.getInverse(bindMatrix);
  16518. },
  16519. pose: function () {
  16520. this.skeleton.pose();
  16521. },
  16522. normalizeSkinWeights: function () {
  16523. var vector = new Vector4();
  16524. var skinWeight = this.geometry.attributes.skinWeight;
  16525. for (var i = 0, l = skinWeight.count; i < l; i++) {
  16526. vector.x = skinWeight.getX(i);
  16527. vector.y = skinWeight.getY(i);
  16528. vector.z = skinWeight.getZ(i);
  16529. vector.w = skinWeight.getW(i);
  16530. var scale = 1.0 / vector.manhattanLength();
  16531. if (scale !== Infinity) {
  16532. vector.multiplyScalar(scale);
  16533. } else {
  16534. vector.set(1, 0, 0, 0); // do something reasonable
  16535. }
  16536. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16537. }
  16538. },
  16539. updateMatrixWorld: function (force) {
  16540. Mesh.prototype.updateMatrixWorld.call(this, force);
  16541. if (this.bindMode === 'attached') {
  16542. this.bindMatrixInverse.getInverse(this.matrixWorld);
  16543. } else if (this.bindMode === 'detached') {
  16544. this.bindMatrixInverse.getInverse(this.bindMatrix);
  16545. } else {
  16546. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16547. }
  16548. },
  16549. clone: function () {
  16550. return new this.constructor(this.geometry, this.material).copy(this);
  16551. }
  16552. });
  16553. /**
  16554. * @author mikael emtinger / http://gomo.se/
  16555. * @author alteredq / http://alteredqualia.com/
  16556. * @author michael guerrero / http://realitymeltdown.com
  16557. * @author ikerr / http://verold.com
  16558. */
  16559. var _offsetMatrix = new Matrix4();
  16560. var _identityMatrix = new Matrix4();
  16561. function Skeleton(bones, boneInverses) {
  16562. // copy the bone array
  16563. bones = bones || [];
  16564. this.bones = bones.slice(0);
  16565. this.boneMatrices = new Float32Array(this.bones.length * 16);
  16566. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  16567. if (boneInverses === undefined) {
  16568. this.calculateInverses();
  16569. } else {
  16570. if (this.bones.length === boneInverses.length) {
  16571. this.boneInverses = boneInverses.slice(0);
  16572. } else {
  16573. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  16574. this.boneInverses = [];
  16575. for (var i = 0, il = this.bones.length; i < il; i++) {
  16576. this.boneInverses.push(new Matrix4());
  16577. }
  16578. }
  16579. }
  16580. }
  16581. Object.assign(Skeleton.prototype, {
  16582. calculateInverses: function () {
  16583. this.boneInverses = [];
  16584. for (var i = 0, il = this.bones.length; i < il; i++) {
  16585. var inverse = new Matrix4();
  16586. if (this.bones[i]) {
  16587. inverse.getInverse(this.bones[i].matrixWorld);
  16588. }
  16589. this.boneInverses.push(inverse);
  16590. }
  16591. },
  16592. pose: function () {
  16593. var bone, i, il; // recover the bind-time world matrices
  16594. for (i = 0, il = this.bones.length; i < il; i++) {
  16595. bone = this.bones[i];
  16596. if (bone) {
  16597. bone.matrixWorld.getInverse(this.boneInverses[i]);
  16598. }
  16599. } // compute the local matrices, positions, rotations and scales
  16600. for (i = 0, il = this.bones.length; i < il; i++) {
  16601. bone = this.bones[i];
  16602. if (bone) {
  16603. if (bone.parent && bone.parent.isBone) {
  16604. bone.matrix.getInverse(bone.parent.matrixWorld);
  16605. bone.matrix.multiply(bone.matrixWorld);
  16606. } else {
  16607. bone.matrix.copy(bone.matrixWorld);
  16608. }
  16609. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16610. }
  16611. }
  16612. },
  16613. update: function () {
  16614. var bones = this.bones;
  16615. var boneInverses = this.boneInverses;
  16616. var boneMatrices = this.boneMatrices;
  16617. var boneTexture = this.boneTexture; // flatten bone matrices to array
  16618. for (var i = 0, il = bones.length; i < il; i++) {
  16619. // compute the offset between the current and the original transform
  16620. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16621. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16622. _offsetMatrix.toArray(boneMatrices, i * 16);
  16623. }
  16624. if (boneTexture !== undefined) {
  16625. boneTexture.needsUpdate = true;
  16626. }
  16627. },
  16628. clone: function () {
  16629. return new Skeleton(this.bones, this.boneInverses);
  16630. },
  16631. getBoneByName: function (name) {
  16632. for (var i = 0, il = this.bones.length; i < il; i++) {
  16633. var bone = this.bones[i];
  16634. if (bone.name === name) {
  16635. return bone;
  16636. }
  16637. }
  16638. return undefined;
  16639. },
  16640. dispose: function () {
  16641. if (this.boneTexture) {
  16642. this.boneTexture.dispose();
  16643. this.boneTexture = undefined;
  16644. }
  16645. }
  16646. });
  16647. /**
  16648. * @author mikael emtinger / http://gomo.se/
  16649. * @author alteredq / http://alteredqualia.com/
  16650. * @author ikerr / http://verold.com
  16651. */
  16652. function Bone() {
  16653. Object3D.call(this);
  16654. this.type = 'Bone';
  16655. }
  16656. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  16657. constructor: Bone,
  16658. isBone: true
  16659. });
  16660. /**
  16661. * @author mrdoob / http://mrdoob.com/
  16662. */
  16663. var _instanceLocalMatrix = new Matrix4();
  16664. var _instanceWorldMatrix = new Matrix4();
  16665. var _instanceIntersects = [];
  16666. var _mesh = new Mesh();
  16667. function InstancedMesh(geometry, material, count) {
  16668. Mesh.call(this, geometry, material);
  16669. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16670. this.count = count;
  16671. this.frustumCulled = false;
  16672. }
  16673. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16674. constructor: InstancedMesh,
  16675. isInstancedMesh: true,
  16676. getMatrixAt: function (index, matrix) {
  16677. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16678. },
  16679. raycast: function (raycaster, intersects) {
  16680. var matrixWorld = this.matrixWorld;
  16681. var raycastTimes = this.count;
  16682. _mesh.geometry = this.geometry;
  16683. _mesh.material = this.material;
  16684. if (_mesh.material === undefined) return;
  16685. for (var instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16686. // calculate the world matrix for each instance
  16687. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16688. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16689. _mesh.matrixWorld = _instanceWorldMatrix;
  16690. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16691. if (_instanceIntersects.length > 0) {
  16692. _instanceIntersects[0].instanceId = instanceId;
  16693. _instanceIntersects[0].object = this;
  16694. intersects.push(_instanceIntersects[0]);
  16695. _instanceIntersects.length = 0;
  16696. }
  16697. }
  16698. },
  16699. setMatrixAt: function (index, matrix) {
  16700. matrix.toArray(this.instanceMatrix.array, index * 16);
  16701. },
  16702. updateMorphTargets: function () {}
  16703. });
  16704. /**
  16705. * @author mrdoob / http://mrdoob.com/
  16706. * @author alteredq / http://alteredqualia.com/
  16707. *
  16708. * parameters = {
  16709. * color: <hex>,
  16710. * opacity: <float>,
  16711. *
  16712. * linewidth: <float>,
  16713. * linecap: "round",
  16714. * linejoin: "round"
  16715. * }
  16716. */
  16717. function LineBasicMaterial(parameters) {
  16718. Material.call(this);
  16719. this.type = 'LineBasicMaterial';
  16720. this.color = new Color(0xffffff);
  16721. this.linewidth = 1;
  16722. this.linecap = 'round';
  16723. this.linejoin = 'round';
  16724. this.setValues(parameters);
  16725. }
  16726. LineBasicMaterial.prototype = Object.create(Material.prototype);
  16727. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16728. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16729. LineBasicMaterial.prototype.copy = function (source) {
  16730. Material.prototype.copy.call(this, source);
  16731. this.color.copy(source.color);
  16732. this.linewidth = source.linewidth;
  16733. this.linecap = source.linecap;
  16734. this.linejoin = source.linejoin;
  16735. return this;
  16736. };
  16737. /**
  16738. * @author mrdoob / http://mrdoob.com/
  16739. */
  16740. var _start = new Vector3();
  16741. var _end = new Vector3();
  16742. var _inverseMatrix$1 = new Matrix4();
  16743. var _ray$1 = new Ray();
  16744. var _sphere$2 = new Sphere();
  16745. function Line(geometry, material, mode) {
  16746. if (mode === 1) {
  16747. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  16748. }
  16749. Object3D.call(this);
  16750. this.type = 'Line';
  16751. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16752. this.material = material !== undefined ? material : new LineBasicMaterial();
  16753. }
  16754. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  16755. constructor: Line,
  16756. isLine: true,
  16757. computeLineDistances: function () {
  16758. var geometry = this.geometry;
  16759. if (geometry.isBufferGeometry) {
  16760. // we assume non-indexed geometry
  16761. if (geometry.index === null) {
  16762. var positionAttribute = geometry.attributes.position;
  16763. var lineDistances = [0];
  16764. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  16765. _start.fromBufferAttribute(positionAttribute, i - 1);
  16766. _end.fromBufferAttribute(positionAttribute, i);
  16767. lineDistances[i] = lineDistances[i - 1];
  16768. lineDistances[i] += _start.distanceTo(_end);
  16769. }
  16770. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16771. } else {
  16772. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16773. }
  16774. } else if (geometry.isGeometry) {
  16775. var vertices = geometry.vertices;
  16776. var lineDistances = geometry.lineDistances;
  16777. lineDistances[0] = 0;
  16778. for (var i = 1, l = vertices.length; i < l; i++) {
  16779. lineDistances[i] = lineDistances[i - 1];
  16780. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  16781. }
  16782. }
  16783. return this;
  16784. },
  16785. raycast: function (raycaster, intersects) {
  16786. var geometry = this.geometry;
  16787. var matrixWorld = this.matrixWorld;
  16788. var threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
  16789. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16790. _sphere$2.copy(geometry.boundingSphere);
  16791. _sphere$2.applyMatrix4(matrixWorld);
  16792. _sphere$2.radius += threshold;
  16793. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  16794. _inverseMatrix$1.getInverse(matrixWorld);
  16795. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16796. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16797. var localThresholdSq = localThreshold * localThreshold;
  16798. var vStart = new Vector3();
  16799. var vEnd = new Vector3();
  16800. var interSegment = new Vector3();
  16801. var interRay = new Vector3();
  16802. var step = this && this.isLineSegments ? 2 : 1;
  16803. if (geometry.isBufferGeometry) {
  16804. var index = geometry.index;
  16805. var attributes = geometry.attributes;
  16806. var positions = attributes.position.array;
  16807. if (index !== null) {
  16808. var indices = index.array;
  16809. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  16810. var a = indices[i];
  16811. var b = indices[i + 1];
  16812. vStart.fromArray(positions, a * 3);
  16813. vEnd.fromArray(positions, b * 3);
  16814. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16815. if (distSq > localThresholdSq) continue;
  16816. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16817. var distance = raycaster.ray.origin.distanceTo(interRay);
  16818. if (distance < raycaster.near || distance > raycaster.far) continue;
  16819. intersects.push({
  16820. distance: distance,
  16821. // What do we want? intersection point on the ray or on the segment??
  16822. // point: raycaster.ray.at( distance ),
  16823. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16824. index: i,
  16825. face: null,
  16826. faceIndex: null,
  16827. object: this
  16828. });
  16829. }
  16830. } else {
  16831. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  16832. vStart.fromArray(positions, 3 * i);
  16833. vEnd.fromArray(positions, 3 * i + 3);
  16834. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16835. if (distSq > localThresholdSq) continue;
  16836. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16837. var distance = raycaster.ray.origin.distanceTo(interRay);
  16838. if (distance < raycaster.near || distance > raycaster.far) continue;
  16839. intersects.push({
  16840. distance: distance,
  16841. // What do we want? intersection point on the ray or on the segment??
  16842. // point: raycaster.ray.at( distance ),
  16843. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16844. index: i,
  16845. face: null,
  16846. faceIndex: null,
  16847. object: this
  16848. });
  16849. }
  16850. }
  16851. } else if (geometry.isGeometry) {
  16852. var vertices = geometry.vertices;
  16853. var nbVertices = vertices.length;
  16854. for (var i = 0; i < nbVertices - 1; i += step) {
  16855. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  16856. if (distSq > localThresholdSq) continue;
  16857. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16858. var distance = raycaster.ray.origin.distanceTo(interRay);
  16859. if (distance < raycaster.near || distance > raycaster.far) continue;
  16860. intersects.push({
  16861. distance: distance,
  16862. // What do we want? intersection point on the ray or on the segment??
  16863. // point: raycaster.ray.at( distance ),
  16864. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16865. index: i,
  16866. face: null,
  16867. faceIndex: null,
  16868. object: this
  16869. });
  16870. }
  16871. }
  16872. },
  16873. clone: function () {
  16874. return new this.constructor(this.geometry, this.material).copy(this);
  16875. }
  16876. });
  16877. /**
  16878. * @author mrdoob / http://mrdoob.com/
  16879. */
  16880. var _start$1 = new Vector3();
  16881. var _end$1 = new Vector3();
  16882. function LineSegments(geometry, material) {
  16883. Line.call(this, geometry, material);
  16884. this.type = 'LineSegments';
  16885. }
  16886. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  16887. constructor: LineSegments,
  16888. isLineSegments: true,
  16889. computeLineDistances: function () {
  16890. var geometry = this.geometry;
  16891. if (geometry.isBufferGeometry) {
  16892. // we assume non-indexed geometry
  16893. if (geometry.index === null) {
  16894. var positionAttribute = geometry.attributes.position;
  16895. var lineDistances = [];
  16896. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  16897. _start$1.fromBufferAttribute(positionAttribute, i);
  16898. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  16899. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16900. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16901. }
  16902. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16903. } else {
  16904. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16905. }
  16906. } else if (geometry.isGeometry) {
  16907. var vertices = geometry.vertices;
  16908. var lineDistances = geometry.lineDistances;
  16909. for (var i = 0, l = vertices.length; i < l; i += 2) {
  16910. _start$1.copy(vertices[i]);
  16911. _end$1.copy(vertices[i + 1]);
  16912. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16913. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16914. }
  16915. }
  16916. return this;
  16917. }
  16918. });
  16919. /**
  16920. * @author mgreter / http://github.com/mgreter
  16921. */
  16922. function LineLoop(geometry, material) {
  16923. Line.call(this, geometry, material);
  16924. this.type = 'LineLoop';
  16925. }
  16926. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  16927. constructor: LineLoop,
  16928. isLineLoop: true
  16929. });
  16930. /**
  16931. * @author mrdoob / http://mrdoob.com/
  16932. * @author alteredq / http://alteredqualia.com/
  16933. *
  16934. * parameters = {
  16935. * color: <hex>,
  16936. * opacity: <float>,
  16937. * map: new THREE.Texture( <Image> ),
  16938. * alphaMap: new THREE.Texture( <Image> ),
  16939. *
  16940. * size: <float>,
  16941. * sizeAttenuation: <bool>
  16942. *
  16943. * morphTargets: <bool>
  16944. * }
  16945. */
  16946. function PointsMaterial(parameters) {
  16947. Material.call(this);
  16948. this.type = 'PointsMaterial';
  16949. this.color = new Color(0xffffff);
  16950. this.map = null;
  16951. this.alphaMap = null;
  16952. this.size = 1;
  16953. this.sizeAttenuation = true;
  16954. this.morphTargets = false;
  16955. this.setValues(parameters);
  16956. }
  16957. PointsMaterial.prototype = Object.create(Material.prototype);
  16958. PointsMaterial.prototype.constructor = PointsMaterial;
  16959. PointsMaterial.prototype.isPointsMaterial = true;
  16960. PointsMaterial.prototype.copy = function (source) {
  16961. Material.prototype.copy.call(this, source);
  16962. this.color.copy(source.color);
  16963. this.map = source.map;
  16964. this.alphaMap = source.alphaMap;
  16965. this.size = source.size;
  16966. this.sizeAttenuation = source.sizeAttenuation;
  16967. this.morphTargets = source.morphTargets;
  16968. return this;
  16969. };
  16970. /**
  16971. * @author alteredq / http://alteredqualia.com/
  16972. */
  16973. var _inverseMatrix$2 = new Matrix4();
  16974. var _ray$2 = new Ray();
  16975. var _sphere$3 = new Sphere();
  16976. var _position$1 = new Vector3();
  16977. function Points(geometry, material) {
  16978. Object3D.call(this);
  16979. this.type = 'Points';
  16980. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16981. this.material = material !== undefined ? material : new PointsMaterial();
  16982. this.updateMorphTargets();
  16983. }
  16984. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  16985. constructor: Points,
  16986. isPoints: true,
  16987. raycast: function (raycaster, intersects) {
  16988. var geometry = this.geometry;
  16989. var matrixWorld = this.matrixWorld;
  16990. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  16991. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16992. _sphere$3.copy(geometry.boundingSphere);
  16993. _sphere$3.applyMatrix4(matrixWorld);
  16994. _sphere$3.radius += threshold;
  16995. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  16996. _inverseMatrix$2.getInverse(matrixWorld);
  16997. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  16998. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16999. var localThresholdSq = localThreshold * localThreshold;
  17000. if (geometry.isBufferGeometry) {
  17001. var index = geometry.index;
  17002. var attributes = geometry.attributes;
  17003. var positions = attributes.position.array;
  17004. if (index !== null) {
  17005. var indices = index.array;
  17006. for (var i = 0, il = indices.length; i < il; i++) {
  17007. var a = indices[i];
  17008. _position$1.fromArray(positions, a * 3);
  17009. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17010. }
  17011. } else {
  17012. for (var i = 0, l = positions.length / 3; i < l; i++) {
  17013. _position$1.fromArray(positions, i * 3);
  17014. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17015. }
  17016. }
  17017. } else {
  17018. var vertices = geometry.vertices;
  17019. for (var i = 0, l = vertices.length; i < l; i++) {
  17020. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17021. }
  17022. }
  17023. },
  17024. updateMorphTargets: function () {
  17025. var geometry = this.geometry;
  17026. var m, ml, name;
  17027. if (geometry.isBufferGeometry) {
  17028. var morphAttributes = geometry.morphAttributes;
  17029. var keys = Object.keys(morphAttributes);
  17030. if (keys.length > 0) {
  17031. var morphAttribute = morphAttributes[keys[0]];
  17032. if (morphAttribute !== undefined) {
  17033. this.morphTargetInfluences = [];
  17034. this.morphTargetDictionary = {};
  17035. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  17036. name = morphAttribute[m].name || String(m);
  17037. this.morphTargetInfluences.push(0);
  17038. this.morphTargetDictionary[name] = m;
  17039. }
  17040. }
  17041. }
  17042. } else {
  17043. var morphTargets = geometry.morphTargets;
  17044. if (morphTargets !== undefined && morphTargets.length > 0) {
  17045. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17046. }
  17047. }
  17048. },
  17049. clone: function () {
  17050. return new this.constructor(this.geometry, this.material).copy(this);
  17051. }
  17052. });
  17053. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17054. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  17055. if (rayPointDistanceSq < localThresholdSq) {
  17056. var intersectPoint = new Vector3();
  17057. _ray$2.closestPointToPoint(point, intersectPoint);
  17058. intersectPoint.applyMatrix4(matrixWorld);
  17059. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17060. if (distance < raycaster.near || distance > raycaster.far) return;
  17061. intersects.push({
  17062. distance: distance,
  17063. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17064. point: intersectPoint,
  17065. index: index,
  17066. face: null,
  17067. object: object
  17068. });
  17069. }
  17070. }
  17071. /**
  17072. * @author mrdoob / http://mrdoob.com/
  17073. */
  17074. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17075. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17076. this.format = format !== undefined ? format : RGBFormat;
  17077. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17078. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17079. this.generateMipmaps = false;
  17080. }
  17081. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  17082. constructor: VideoTexture,
  17083. isVideoTexture: true,
  17084. update: function () {
  17085. var video = this.image;
  17086. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  17087. this.needsUpdate = true;
  17088. }
  17089. }
  17090. });
  17091. /**
  17092. * @author alteredq / http://alteredqualia.com/
  17093. */
  17094. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17095. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17096. this.image = {
  17097. width: width,
  17098. height: height
  17099. };
  17100. this.mipmaps = mipmaps; // no flipping for cube textures
  17101. // (also flipping doesn't work for compressed textures )
  17102. this.flipY = false; // can't generate mipmaps for compressed textures
  17103. // mips must be embedded in DDS files
  17104. this.generateMipmaps = false;
  17105. }
  17106. CompressedTexture.prototype = Object.create(Texture.prototype);
  17107. CompressedTexture.prototype.constructor = CompressedTexture;
  17108. CompressedTexture.prototype.isCompressedTexture = true;
  17109. /**
  17110. * @author mrdoob / http://mrdoob.com/
  17111. */
  17112. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17113. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17114. this.needsUpdate = true;
  17115. }
  17116. CanvasTexture.prototype = Object.create(Texture.prototype);
  17117. CanvasTexture.prototype.constructor = CanvasTexture;
  17118. CanvasTexture.prototype.isCanvasTexture = true;
  17119. /**
  17120. * @author Matt DesLauriers / @mattdesl
  17121. * @author atix / arthursilber.de
  17122. */
  17123. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  17124. format = format !== undefined ? format : DepthFormat;
  17125. if (format !== DepthFormat && format !== DepthStencilFormat) {
  17126. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  17127. }
  17128. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  17129. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  17130. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17131. this.image = {
  17132. width: width,
  17133. height: height
  17134. };
  17135. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17136. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17137. this.flipY = false;
  17138. this.generateMipmaps = false;
  17139. }
  17140. DepthTexture.prototype = Object.create(Texture.prototype);
  17141. DepthTexture.prototype.constructor = DepthTexture;
  17142. DepthTexture.prototype.isDepthTexture = true;
  17143. /**
  17144. * @author mrdoob / http://mrdoob.com/
  17145. * @author Mugen87 / https://github.com/Mugen87
  17146. */
  17147. function WireframeGeometry(geometry) {
  17148. BufferGeometry.call(this);
  17149. this.type = 'WireframeGeometry'; // buffer
  17150. var vertices = []; // helper variables
  17151. var i, j, l, o, ol;
  17152. var edge = [0, 0],
  17153. edges = {},
  17154. e,
  17155. edge1,
  17156. edge2;
  17157. var key,
  17158. keys = ['a', 'b', 'c'];
  17159. var vertex; // different logic for Geometry and BufferGeometry
  17160. if (geometry && geometry.isGeometry) {
  17161. // create a data structure that contains all edges without duplicates
  17162. var faces = geometry.faces;
  17163. for (i = 0, l = faces.length; i < l; i++) {
  17164. var face = faces[i];
  17165. for (j = 0; j < 3; j++) {
  17166. edge1 = face[keys[j]];
  17167. edge2 = face[keys[(j + 1) % 3]];
  17168. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  17169. edge[1] = Math.max(edge1, edge2);
  17170. key = edge[0] + ',' + edge[1];
  17171. if (edges[key] === undefined) {
  17172. edges[key] = {
  17173. index1: edge[0],
  17174. index2: edge[1]
  17175. };
  17176. }
  17177. }
  17178. } // generate vertices
  17179. for (key in edges) {
  17180. e = edges[key];
  17181. vertex = geometry.vertices[e.index1];
  17182. vertices.push(vertex.x, vertex.y, vertex.z);
  17183. vertex = geometry.vertices[e.index2];
  17184. vertices.push(vertex.x, vertex.y, vertex.z);
  17185. }
  17186. } else if (geometry && geometry.isBufferGeometry) {
  17187. var position, indices, groups;
  17188. var group, start, count;
  17189. var index1, index2;
  17190. vertex = new Vector3();
  17191. if (geometry.index !== null) {
  17192. // indexed BufferGeometry
  17193. position = geometry.attributes.position;
  17194. indices = geometry.index;
  17195. groups = geometry.groups;
  17196. if (groups.length === 0) {
  17197. groups = [{
  17198. start: 0,
  17199. count: indices.count,
  17200. materialIndex: 0
  17201. }];
  17202. } // create a data structure that contains all eges without duplicates
  17203. for (o = 0, ol = groups.length; o < ol; ++o) {
  17204. group = groups[o];
  17205. start = group.start;
  17206. count = group.count;
  17207. for (i = start, l = start + count; i < l; i += 3) {
  17208. for (j = 0; j < 3; j++) {
  17209. edge1 = indices.getX(i + j);
  17210. edge2 = indices.getX(i + (j + 1) % 3);
  17211. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  17212. edge[1] = Math.max(edge1, edge2);
  17213. key = edge[0] + ',' + edge[1];
  17214. if (edges[key] === undefined) {
  17215. edges[key] = {
  17216. index1: edge[0],
  17217. index2: edge[1]
  17218. };
  17219. }
  17220. }
  17221. }
  17222. } // generate vertices
  17223. for (key in edges) {
  17224. e = edges[key];
  17225. vertex.fromBufferAttribute(position, e.index1);
  17226. vertices.push(vertex.x, vertex.y, vertex.z);
  17227. vertex.fromBufferAttribute(position, e.index2);
  17228. vertices.push(vertex.x, vertex.y, vertex.z);
  17229. }
  17230. } else {
  17231. // non-indexed BufferGeometry
  17232. position = geometry.attributes.position;
  17233. for (i = 0, l = position.count / 3; i < l; i++) {
  17234. for (j = 0; j < 3; j++) {
  17235. // three edges per triangle, an edge is represented as (index1, index2)
  17236. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  17237. index1 = 3 * i + j;
  17238. vertex.fromBufferAttribute(position, index1);
  17239. vertices.push(vertex.x, vertex.y, vertex.z);
  17240. index2 = 3 * i + (j + 1) % 3;
  17241. vertex.fromBufferAttribute(position, index2);
  17242. vertices.push(vertex.x, vertex.y, vertex.z);
  17243. }
  17244. }
  17245. }
  17246. } // build geometry
  17247. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17248. }
  17249. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  17250. WireframeGeometry.prototype.constructor = WireframeGeometry;
  17251. /**
  17252. * @author zz85 / https://github.com/zz85
  17253. * @author Mugen87 / https://github.com/Mugen87
  17254. *
  17255. * Parametric Surfaces Geometry
  17256. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  17257. */
  17258. // ParametricGeometry
  17259. function ParametricGeometry(func, slices, stacks) {
  17260. Geometry.call(this);
  17261. this.type = 'ParametricGeometry';
  17262. this.parameters = {
  17263. func: func,
  17264. slices: slices,
  17265. stacks: stacks
  17266. };
  17267. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  17268. this.mergeVertices();
  17269. }
  17270. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  17271. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  17272. function ParametricBufferGeometry(func, slices, stacks) {
  17273. BufferGeometry.call(this);
  17274. this.type = 'ParametricBufferGeometry';
  17275. this.parameters = {
  17276. func: func,
  17277. slices: slices,
  17278. stacks: stacks
  17279. }; // buffers
  17280. var indices = [];
  17281. var vertices = [];
  17282. var normals = [];
  17283. var uvs = [];
  17284. var EPS = 0.00001;
  17285. var normal = new Vector3();
  17286. var p0 = new Vector3(),
  17287. p1 = new Vector3();
  17288. var pu = new Vector3(),
  17289. pv = new Vector3();
  17290. var i, j;
  17291. if (func.length < 3) {
  17292. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  17293. } // generate vertices, normals and uvs
  17294. var sliceCount = slices + 1;
  17295. for (i = 0; i <= stacks; i++) {
  17296. var v = i / stacks;
  17297. for (j = 0; j <= slices; j++) {
  17298. var u = j / slices; // vertex
  17299. func(u, v, p0);
  17300. vertices.push(p0.x, p0.y, p0.z); // normal
  17301. // approximate tangent vectors via finite differences
  17302. if (u - EPS >= 0) {
  17303. func(u - EPS, v, p1);
  17304. pu.subVectors(p0, p1);
  17305. } else {
  17306. func(u + EPS, v, p1);
  17307. pu.subVectors(p1, p0);
  17308. }
  17309. if (v - EPS >= 0) {
  17310. func(u, v - EPS, p1);
  17311. pv.subVectors(p0, p1);
  17312. } else {
  17313. func(u, v + EPS, p1);
  17314. pv.subVectors(p1, p0);
  17315. } // cross product of tangent vectors returns surface normal
  17316. normal.crossVectors(pu, pv).normalize();
  17317. normals.push(normal.x, normal.y, normal.z); // uv
  17318. uvs.push(u, v);
  17319. }
  17320. } // generate indices
  17321. for (i = 0; i < stacks; i++) {
  17322. for (j = 0; j < slices; j++) {
  17323. var a = i * sliceCount + j;
  17324. var b = i * sliceCount + j + 1;
  17325. var c = (i + 1) * sliceCount + j + 1;
  17326. var d = (i + 1) * sliceCount + j; // faces one and two
  17327. indices.push(a, b, d);
  17328. indices.push(b, c, d);
  17329. }
  17330. } // build geometry
  17331. this.setIndex(indices);
  17332. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17333. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17334. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17335. }
  17336. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17337. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  17338. /**
  17339. * @author clockworkgeek / https://github.com/clockworkgeek
  17340. * @author timothypratley / https://github.com/timothypratley
  17341. * @author WestLangley / http://github.com/WestLangley
  17342. * @author Mugen87 / https://github.com/Mugen87
  17343. */
  17344. // PolyhedronGeometry
  17345. function PolyhedronGeometry(vertices, indices, radius, detail) {
  17346. Geometry.call(this);
  17347. this.type = 'PolyhedronGeometry';
  17348. this.parameters = {
  17349. vertices: vertices,
  17350. indices: indices,
  17351. radius: radius,
  17352. detail: detail
  17353. };
  17354. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  17355. this.mergeVertices();
  17356. }
  17357. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  17358. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  17359. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  17360. BufferGeometry.call(this);
  17361. this.type = 'PolyhedronBufferGeometry';
  17362. this.parameters = {
  17363. vertices: vertices,
  17364. indices: indices,
  17365. radius: radius,
  17366. detail: detail
  17367. };
  17368. radius = radius || 1;
  17369. detail = detail || 0; // default buffer data
  17370. var vertexBuffer = [];
  17371. var uvBuffer = []; // the subdivision creates the vertex buffer data
  17372. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17373. applyRadius(radius); // finally, create the uv data
  17374. generateUVs(); // build non-indexed geometry
  17375. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17376. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17377. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17378. if (detail === 0) {
  17379. this.computeVertexNormals(); // flat normals
  17380. } else {
  17381. this.normalizeNormals(); // smooth normals
  17382. } // helper functions
  17383. function subdivide(detail) {
  17384. var a = new Vector3();
  17385. var b = new Vector3();
  17386. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17387. for (var i = 0; i < indices.length; i += 3) {
  17388. // get the vertices of the face
  17389. getVertexByIndex(indices[i + 0], a);
  17390. getVertexByIndex(indices[i + 1], b);
  17391. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17392. subdivideFace(a, b, c, detail);
  17393. }
  17394. }
  17395. function subdivideFace(a, b, c, detail) {
  17396. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  17397. var v = [];
  17398. var i, j; // construct all of the vertices for this subdivision
  17399. for (i = 0; i <= cols; i++) {
  17400. v[i] = [];
  17401. var aj = a.clone().lerp(c, i / cols);
  17402. var bj = b.clone().lerp(c, i / cols);
  17403. var rows = cols - i;
  17404. for (j = 0; j <= rows; j++) {
  17405. if (j === 0 && i === cols) {
  17406. v[i][j] = aj;
  17407. } else {
  17408. v[i][j] = aj.clone().lerp(bj, j / rows);
  17409. }
  17410. }
  17411. } // construct all of the faces
  17412. for (i = 0; i < cols; i++) {
  17413. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  17414. var k = Math.floor(j / 2);
  17415. if (j % 2 === 0) {
  17416. pushVertex(v[i][k + 1]);
  17417. pushVertex(v[i + 1][k]);
  17418. pushVertex(v[i][k]);
  17419. } else {
  17420. pushVertex(v[i][k + 1]);
  17421. pushVertex(v[i + 1][k + 1]);
  17422. pushVertex(v[i + 1][k]);
  17423. }
  17424. }
  17425. }
  17426. }
  17427. function applyRadius(radius) {
  17428. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17429. for (var i = 0; i < vertexBuffer.length; i += 3) {
  17430. vertex.x = vertexBuffer[i + 0];
  17431. vertex.y = vertexBuffer[i + 1];
  17432. vertex.z = vertexBuffer[i + 2];
  17433. vertex.normalize().multiplyScalar(radius);
  17434. vertexBuffer[i + 0] = vertex.x;
  17435. vertexBuffer[i + 1] = vertex.y;
  17436. vertexBuffer[i + 2] = vertex.z;
  17437. }
  17438. }
  17439. function generateUVs() {
  17440. var vertex = new Vector3();
  17441. for (var i = 0; i < vertexBuffer.length; i += 3) {
  17442. vertex.x = vertexBuffer[i + 0];
  17443. vertex.y = vertexBuffer[i + 1];
  17444. vertex.z = vertexBuffer[i + 2];
  17445. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17446. var v = inclination(vertex) / Math.PI + 0.5;
  17447. uvBuffer.push(u, 1 - v);
  17448. }
  17449. correctUVs();
  17450. correctSeam();
  17451. }
  17452. function correctSeam() {
  17453. // handle case when face straddles the seam, see #3269
  17454. for (var i = 0; i < uvBuffer.length; i += 6) {
  17455. // uv data of a single face
  17456. var x0 = uvBuffer[i + 0];
  17457. var x1 = uvBuffer[i + 2];
  17458. var x2 = uvBuffer[i + 4];
  17459. var max = Math.max(x0, x1, x2);
  17460. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17461. if (max > 0.9 && min < 0.1) {
  17462. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17463. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17464. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17465. }
  17466. }
  17467. }
  17468. function pushVertex(vertex) {
  17469. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17470. }
  17471. function getVertexByIndex(index, vertex) {
  17472. var stride = index * 3;
  17473. vertex.x = vertices[stride + 0];
  17474. vertex.y = vertices[stride + 1];
  17475. vertex.z = vertices[stride + 2];
  17476. }
  17477. function correctUVs() {
  17478. var a = new Vector3();
  17479. var b = new Vector3();
  17480. var c = new Vector3();
  17481. var centroid = new Vector3();
  17482. var uvA = new Vector2();
  17483. var uvB = new Vector2();
  17484. var uvC = new Vector2();
  17485. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17486. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17487. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17488. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17489. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17490. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17491. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17492. centroid.copy(a).add(b).add(c).divideScalar(3);
  17493. var azi = azimuth(centroid);
  17494. correctUV(uvA, j + 0, a, azi);
  17495. correctUV(uvB, j + 2, b, azi);
  17496. correctUV(uvC, j + 4, c, azi);
  17497. }
  17498. }
  17499. function correctUV(uv, stride, vector, azimuth) {
  17500. if (azimuth < 0 && uv.x === 1) {
  17501. uvBuffer[stride] = uv.x - 1;
  17502. }
  17503. if (vector.x === 0 && vector.z === 0) {
  17504. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17505. }
  17506. } // Angle around the Y axis, counter-clockwise when looking from above.
  17507. function azimuth(vector) {
  17508. return Math.atan2(vector.z, -vector.x);
  17509. } // Angle above the XZ plane.
  17510. function inclination(vector) {
  17511. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17512. }
  17513. }
  17514. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17515. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  17516. /**
  17517. * @author timothypratley / https://github.com/timothypratley
  17518. * @author Mugen87 / https://github.com/Mugen87
  17519. */
  17520. // TetrahedronGeometry
  17521. function TetrahedronGeometry(radius, detail) {
  17522. Geometry.call(this);
  17523. this.type = 'TetrahedronGeometry';
  17524. this.parameters = {
  17525. radius: radius,
  17526. detail: detail
  17527. };
  17528. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  17529. this.mergeVertices();
  17530. }
  17531. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  17532. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  17533. function TetrahedronBufferGeometry(radius, detail) {
  17534. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  17535. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  17536. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17537. this.type = 'TetrahedronBufferGeometry';
  17538. this.parameters = {
  17539. radius: radius,
  17540. detail: detail
  17541. };
  17542. }
  17543. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17544. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  17545. /**
  17546. * @author timothypratley / https://github.com/timothypratley
  17547. * @author Mugen87 / https://github.com/Mugen87
  17548. */
  17549. // OctahedronGeometry
  17550. function OctahedronGeometry(radius, detail) {
  17551. Geometry.call(this);
  17552. this.type = 'OctahedronGeometry';
  17553. this.parameters = {
  17554. radius: radius,
  17555. detail: detail
  17556. };
  17557. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  17558. this.mergeVertices();
  17559. }
  17560. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  17561. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  17562. function OctahedronBufferGeometry(radius, detail) {
  17563. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  17564. 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];
  17565. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17566. this.type = 'OctahedronBufferGeometry';
  17567. this.parameters = {
  17568. radius: radius,
  17569. detail: detail
  17570. };
  17571. }
  17572. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17573. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  17574. /**
  17575. * @author timothypratley / https://github.com/timothypratley
  17576. * @author Mugen87 / https://github.com/Mugen87
  17577. */
  17578. // IcosahedronGeometry
  17579. function IcosahedronGeometry(radius, detail) {
  17580. Geometry.call(this);
  17581. this.type = 'IcosahedronGeometry';
  17582. this.parameters = {
  17583. radius: radius,
  17584. detail: detail
  17585. };
  17586. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  17587. this.mergeVertices();
  17588. }
  17589. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  17590. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  17591. function IcosahedronBufferGeometry(radius, detail) {
  17592. var t = (1 + Math.sqrt(5)) / 2;
  17593. 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];
  17594. 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];
  17595. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17596. this.type = 'IcosahedronBufferGeometry';
  17597. this.parameters = {
  17598. radius: radius,
  17599. detail: detail
  17600. };
  17601. }
  17602. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17603. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  17604. /**
  17605. * @author Abe Pazos / https://hamoid.com
  17606. * @author Mugen87 / https://github.com/Mugen87
  17607. */
  17608. // DodecahedronGeometry
  17609. function DodecahedronGeometry(radius, detail) {
  17610. Geometry.call(this);
  17611. this.type = 'DodecahedronGeometry';
  17612. this.parameters = {
  17613. radius: radius,
  17614. detail: detail
  17615. };
  17616. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  17617. this.mergeVertices();
  17618. }
  17619. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  17620. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  17621. function DodecahedronBufferGeometry(radius, detail) {
  17622. var t = (1 + Math.sqrt(5)) / 2;
  17623. var r = 1 / t;
  17624. var vertices = [// (±1, ±1, ±1)
  17625. -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/φ, ±φ)
  17626. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  17627. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  17628. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  17629. 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];
  17630. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17631. this.type = 'DodecahedronBufferGeometry';
  17632. this.parameters = {
  17633. radius: radius,
  17634. detail: detail
  17635. };
  17636. }
  17637. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17638. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  17639. /**
  17640. * @author oosmoxiecode / https://github.com/oosmoxiecode
  17641. * @author WestLangley / https://github.com/WestLangley
  17642. * @author zz85 / https://github.com/zz85
  17643. * @author miningold / https://github.com/miningold
  17644. * @author jonobr1 / https://github.com/jonobr1
  17645. * @author Mugen87 / https://github.com/Mugen87
  17646. *
  17647. */
  17648. // TubeGeometry
  17649. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  17650. Geometry.call(this);
  17651. this.type = 'TubeGeometry';
  17652. this.parameters = {
  17653. path: path,
  17654. tubularSegments: tubularSegments,
  17655. radius: radius,
  17656. radialSegments: radialSegments,
  17657. closed: closed
  17658. };
  17659. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  17660. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  17661. this.tangents = bufferGeometry.tangents;
  17662. this.normals = bufferGeometry.normals;
  17663. this.binormals = bufferGeometry.binormals; // create geometry
  17664. this.fromBufferGeometry(bufferGeometry);
  17665. this.mergeVertices();
  17666. }
  17667. TubeGeometry.prototype = Object.create(Geometry.prototype);
  17668. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  17669. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  17670. BufferGeometry.call(this);
  17671. this.type = 'TubeBufferGeometry';
  17672. this.parameters = {
  17673. path: path,
  17674. tubularSegments: tubularSegments,
  17675. radius: radius,
  17676. radialSegments: radialSegments,
  17677. closed: closed
  17678. };
  17679. tubularSegments = tubularSegments || 64;
  17680. radius = radius || 1;
  17681. radialSegments = radialSegments || 8;
  17682. closed = closed || false;
  17683. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  17684. this.tangents = frames.tangents;
  17685. this.normals = frames.normals;
  17686. this.binormals = frames.binormals; // helper variables
  17687. var vertex = new Vector3();
  17688. var normal = new Vector3();
  17689. var uv = new Vector2();
  17690. var P = new Vector3();
  17691. var i, j; // buffer
  17692. var vertices = [];
  17693. var normals = [];
  17694. var uvs = [];
  17695. var indices = []; // create buffer data
  17696. generateBufferData(); // build geometry
  17697. this.setIndex(indices);
  17698. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17699. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17700. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  17701. function generateBufferData() {
  17702. for (i = 0; i < tubularSegments; i++) {
  17703. generateSegment(i);
  17704. } // if the geometry is not closed, generate the last row of vertices and normals
  17705. // at the regular position on the given path
  17706. //
  17707. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  17708. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  17709. // this makes it easy compute correct values for closed geometries
  17710. generateUVs(); // finally create faces
  17711. generateIndices();
  17712. }
  17713. function generateSegment(i) {
  17714. // we use getPointAt to sample evenly distributed points from the given path
  17715. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  17716. var N = frames.normals[i];
  17717. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  17718. for (j = 0; j <= radialSegments; j++) {
  17719. var v = j / radialSegments * Math.PI * 2;
  17720. var sin = Math.sin(v);
  17721. var cos = -Math.cos(v); // normal
  17722. normal.x = cos * N.x + sin * B.x;
  17723. normal.y = cos * N.y + sin * B.y;
  17724. normal.z = cos * N.z + sin * B.z;
  17725. normal.normalize();
  17726. normals.push(normal.x, normal.y, normal.z); // vertex
  17727. vertex.x = P.x + radius * normal.x;
  17728. vertex.y = P.y + radius * normal.y;
  17729. vertex.z = P.z + radius * normal.z;
  17730. vertices.push(vertex.x, vertex.y, vertex.z);
  17731. }
  17732. }
  17733. function generateIndices() {
  17734. for (j = 1; j <= tubularSegments; j++) {
  17735. for (i = 1; i <= radialSegments; i++) {
  17736. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  17737. var b = (radialSegments + 1) * j + (i - 1);
  17738. var c = (radialSegments + 1) * j + i;
  17739. var d = (radialSegments + 1) * (j - 1) + i; // faces
  17740. indices.push(a, b, d);
  17741. indices.push(b, c, d);
  17742. }
  17743. }
  17744. }
  17745. function generateUVs() {
  17746. for (i = 0; i <= tubularSegments; i++) {
  17747. for (j = 0; j <= radialSegments; j++) {
  17748. uv.x = i / tubularSegments;
  17749. uv.y = j / radialSegments;
  17750. uvs.push(uv.x, uv.y);
  17751. }
  17752. }
  17753. }
  17754. }
  17755. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17756. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  17757. TubeBufferGeometry.prototype.toJSON = function () {
  17758. var data = BufferGeometry.prototype.toJSON.call(this);
  17759. data.path = this.parameters.path.toJSON();
  17760. return data;
  17761. };
  17762. /**
  17763. * @author oosmoxiecode
  17764. * @author Mugen87 / https://github.com/Mugen87
  17765. *
  17766. * based on http://www.blackpawn.com/texts/pqtorus/
  17767. */
  17768. // TorusKnotGeometry
  17769. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  17770. Geometry.call(this);
  17771. this.type = 'TorusKnotGeometry';
  17772. this.parameters = {
  17773. radius: radius,
  17774. tube: tube,
  17775. tubularSegments: tubularSegments,
  17776. radialSegments: radialSegments,
  17777. p: p,
  17778. q: q
  17779. };
  17780. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  17781. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  17782. this.mergeVertices();
  17783. }
  17784. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  17785. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  17786. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  17787. BufferGeometry.call(this);
  17788. this.type = 'TorusKnotBufferGeometry';
  17789. this.parameters = {
  17790. radius: radius,
  17791. tube: tube,
  17792. tubularSegments: tubularSegments,
  17793. radialSegments: radialSegments,
  17794. p: p,
  17795. q: q
  17796. };
  17797. radius = radius || 1;
  17798. tube = tube || 0.4;
  17799. tubularSegments = Math.floor(tubularSegments) || 64;
  17800. radialSegments = Math.floor(radialSegments) || 8;
  17801. p = p || 2;
  17802. q = q || 3; // buffers
  17803. var indices = [];
  17804. var vertices = [];
  17805. var normals = [];
  17806. var uvs = []; // helper variables
  17807. var i, j;
  17808. var vertex = new Vector3();
  17809. var normal = new Vector3();
  17810. var P1 = new Vector3();
  17811. var P2 = new Vector3();
  17812. var B = new Vector3();
  17813. var T = new Vector3();
  17814. var N = new Vector3(); // generate vertices, normals and uvs
  17815. for (i = 0; i <= tubularSegments; ++i) {
  17816. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  17817. 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.
  17818. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  17819. calculatePositionOnCurve(u, p, q, radius, P1);
  17820. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  17821. T.subVectors(P2, P1);
  17822. N.addVectors(P2, P1);
  17823. B.crossVectors(T, N);
  17824. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  17825. B.normalize();
  17826. N.normalize();
  17827. for (j = 0; j <= radialSegments; ++j) {
  17828. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  17829. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  17830. var v = j / radialSegments * Math.PI * 2;
  17831. var cx = -tube * Math.cos(v);
  17832. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  17833. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  17834. vertex.x = P1.x + (cx * N.x + cy * B.x);
  17835. vertex.y = P1.y + (cx * N.y + cy * B.y);
  17836. vertex.z = P1.z + (cx * N.z + cy * B.z);
  17837. 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)
  17838. normal.subVectors(vertex, P1).normalize();
  17839. normals.push(normal.x, normal.y, normal.z); // uv
  17840. uvs.push(i / tubularSegments);
  17841. uvs.push(j / radialSegments);
  17842. }
  17843. } // generate indices
  17844. for (j = 1; j <= tubularSegments; j++) {
  17845. for (i = 1; i <= radialSegments; i++) {
  17846. // indices
  17847. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  17848. var b = (radialSegments + 1) * j + (i - 1);
  17849. var c = (radialSegments + 1) * j + i;
  17850. var d = (radialSegments + 1) * (j - 1) + i; // faces
  17851. indices.push(a, b, d);
  17852. indices.push(b, c, d);
  17853. }
  17854. } // build geometry
  17855. this.setIndex(indices);
  17856. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17857. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17858. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  17859. function calculatePositionOnCurve(u, p, q, radius, position) {
  17860. var cu = Math.cos(u);
  17861. var su = Math.sin(u);
  17862. var quOverP = q / p * u;
  17863. var cs = Math.cos(quOverP);
  17864. position.x = radius * (2 + cs) * 0.5 * cu;
  17865. position.y = radius * (2 + cs) * su * 0.5;
  17866. position.z = radius * Math.sin(quOverP) * 0.5;
  17867. }
  17868. }
  17869. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17870. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  17871. /**
  17872. * @author oosmoxiecode
  17873. * @author mrdoob / http://mrdoob.com/
  17874. * @author Mugen87 / https://github.com/Mugen87
  17875. */
  17876. // TorusGeometry
  17877. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  17878. Geometry.call(this);
  17879. this.type = 'TorusGeometry';
  17880. this.parameters = {
  17881. radius: radius,
  17882. tube: tube,
  17883. radialSegments: radialSegments,
  17884. tubularSegments: tubularSegments,
  17885. arc: arc
  17886. };
  17887. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  17888. this.mergeVertices();
  17889. }
  17890. TorusGeometry.prototype = Object.create(Geometry.prototype);
  17891. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  17892. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  17893. BufferGeometry.call(this);
  17894. this.type = 'TorusBufferGeometry';
  17895. this.parameters = {
  17896. radius: radius,
  17897. tube: tube,
  17898. radialSegments: radialSegments,
  17899. tubularSegments: tubularSegments,
  17900. arc: arc
  17901. };
  17902. radius = radius || 1;
  17903. tube = tube || 0.4;
  17904. radialSegments = Math.floor(radialSegments) || 8;
  17905. tubularSegments = Math.floor(tubularSegments) || 6;
  17906. arc = arc || Math.PI * 2; // buffers
  17907. var indices = [];
  17908. var vertices = [];
  17909. var normals = [];
  17910. var uvs = []; // helper variables
  17911. var center = new Vector3();
  17912. var vertex = new Vector3();
  17913. var normal = new Vector3();
  17914. var j, i; // generate vertices, normals and uvs
  17915. for (j = 0; j <= radialSegments; j++) {
  17916. for (i = 0; i <= tubularSegments; i++) {
  17917. var u = i / tubularSegments * arc;
  17918. var v = j / radialSegments * Math.PI * 2; // vertex
  17919. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  17920. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  17921. vertex.z = tube * Math.sin(v);
  17922. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17923. center.x = radius * Math.cos(u);
  17924. center.y = radius * Math.sin(u);
  17925. normal.subVectors(vertex, center).normalize();
  17926. normals.push(normal.x, normal.y, normal.z); // uv
  17927. uvs.push(i / tubularSegments);
  17928. uvs.push(j / radialSegments);
  17929. }
  17930. } // generate indices
  17931. for (j = 1; j <= radialSegments; j++) {
  17932. for (i = 1; i <= tubularSegments; i++) {
  17933. // indices
  17934. var a = (tubularSegments + 1) * j + i - 1;
  17935. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  17936. var c = (tubularSegments + 1) * (j - 1) + i;
  17937. var d = (tubularSegments + 1) * j + i; // faces
  17938. indices.push(a, b, d);
  17939. indices.push(b, c, d);
  17940. }
  17941. } // build geometry
  17942. this.setIndex(indices);
  17943. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17944. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17945. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17946. }
  17947. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17948. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  17949. /**
  17950. * @author Mugen87 / https://github.com/Mugen87
  17951. * Port from https://github.com/mapbox/earcut (v2.1.5)
  17952. */
  17953. var Earcut = {
  17954. triangulate: function (data, holeIndices, dim) {
  17955. dim = dim || 2;
  17956. var hasHoles = holeIndices && holeIndices.length,
  17957. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  17958. outerNode = linkedList(data, 0, outerLen, dim, true),
  17959. triangles = [];
  17960. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  17961. var minX, minY, maxX, maxY, x, y, invSize;
  17962. 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
  17963. if (data.length > 80 * dim) {
  17964. minX = maxX = data[0];
  17965. minY = maxY = data[1];
  17966. for (var i = dim; i < outerLen; i += dim) {
  17967. x = data[i];
  17968. y = data[i + 1];
  17969. if (x < minX) minX = x;
  17970. if (y < minY) minY = y;
  17971. if (x > maxX) maxX = x;
  17972. if (y > maxY) maxY = y;
  17973. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17974. invSize = Math.max(maxX - minX, maxY - minY);
  17975. invSize = invSize !== 0 ? 1 / invSize : 0;
  17976. }
  17977. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  17978. return triangles;
  17979. }
  17980. }; // create a circular doubly linked list from polygon points in the specified winding order
  17981. function linkedList(data, start, end, dim, clockwise) {
  17982. var i, last;
  17983. if (clockwise === signedArea(data, start, end, dim) > 0) {
  17984. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17985. } else {
  17986. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17987. }
  17988. if (last && equals(last, last.next)) {
  17989. removeNode(last);
  17990. last = last.next;
  17991. }
  17992. return last;
  17993. } // eliminate colinear or duplicate points
  17994. function filterPoints(start, end) {
  17995. if (!start) return start;
  17996. if (!end) end = start;
  17997. var p = start,
  17998. again;
  17999. do {
  18000. again = false;
  18001. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18002. removeNode(p);
  18003. p = end = p.prev;
  18004. if (p === p.next) break;
  18005. again = true;
  18006. } else {
  18007. p = p.next;
  18008. }
  18009. } while (again || p !== end);
  18010. return end;
  18011. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18012. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18013. if (!ear) return; // interlink polygon nodes in z-order
  18014. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18015. var stop = ear,
  18016. prev,
  18017. next; // iterate through ears, slicing them one by one
  18018. while (ear.prev !== ear.next) {
  18019. prev = ear.prev;
  18020. next = ear.next;
  18021. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18022. // cut off the triangle
  18023. triangles.push(prev.i / dim);
  18024. triangles.push(ear.i / dim);
  18025. triangles.push(next.i / dim);
  18026. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18027. ear = next.next;
  18028. stop = next.next;
  18029. continue;
  18030. }
  18031. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18032. if (ear === stop) {
  18033. // try filtering points and slicing again
  18034. if (!pass) {
  18035. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18036. } else if (pass === 1) {
  18037. ear = cureLocalIntersections(ear, triangles, dim);
  18038. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18039. } else if (pass === 2) {
  18040. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18041. }
  18042. break;
  18043. }
  18044. }
  18045. } // check whether a polygon node forms a valid ear with adjacent nodes
  18046. function isEar(ear) {
  18047. var a = ear.prev,
  18048. b = ear,
  18049. c = ear.next;
  18050. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18051. // now make sure we don't have other points inside the potential ear
  18052. var p = ear.next.next;
  18053. while (p !== ear.prev) {
  18054. 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;
  18055. p = p.next;
  18056. }
  18057. return true;
  18058. }
  18059. function isEarHashed(ear, minX, minY, invSize) {
  18060. var a = ear.prev,
  18061. b = ear,
  18062. c = ear.next;
  18063. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18064. // triangle bbox; min & max are calculated like this for speed
  18065. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18066. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18067. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18068. 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;
  18069. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18070. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18071. var p = ear.prevZ,
  18072. n = ear.nextZ; // look for points inside the triangle in both directions
  18073. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18074. 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;
  18075. p = p.prevZ;
  18076. 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;
  18077. n = n.nextZ;
  18078. } // look for remaining points in decreasing z-order
  18079. while (p && p.z >= minZ) {
  18080. 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;
  18081. p = p.prevZ;
  18082. } // look for remaining points in increasing z-order
  18083. while (n && n.z <= maxZ) {
  18084. 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;
  18085. n = n.nextZ;
  18086. }
  18087. return true;
  18088. } // go through all polygon nodes and cure small local self-intersections
  18089. function cureLocalIntersections(start, triangles, dim) {
  18090. var p = start;
  18091. do {
  18092. var a = p.prev,
  18093. b = p.next.next;
  18094. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18095. triangles.push(a.i / dim);
  18096. triangles.push(p.i / dim);
  18097. triangles.push(b.i / dim); // remove two nodes involved
  18098. removeNode(p);
  18099. removeNode(p.next);
  18100. p = start = b;
  18101. }
  18102. p = p.next;
  18103. } while (p !== start);
  18104. return p;
  18105. } // try splitting polygon into two and triangulate them independently
  18106. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18107. // look for a valid diagonal that divides the polygon into two
  18108. var a = start;
  18109. do {
  18110. var b = a.next.next;
  18111. while (b !== a.prev) {
  18112. if (a.i !== b.i && isValidDiagonal(a, b)) {
  18113. // split the polygon in two by the diagonal
  18114. var c = splitPolygon(a, b); // filter colinear points around the cuts
  18115. a = filterPoints(a, a.next);
  18116. c = filterPoints(c, c.next); // run earcut on each half
  18117. earcutLinked(a, triangles, dim, minX, minY, invSize);
  18118. earcutLinked(c, triangles, dim, minX, minY, invSize);
  18119. return;
  18120. }
  18121. b = b.next;
  18122. }
  18123. a = a.next;
  18124. } while (a !== start);
  18125. } // link every hole into the outer loop, producing a single-ring polygon without holes
  18126. function eliminateHoles(data, holeIndices, outerNode, dim) {
  18127. var queue = [],
  18128. i,
  18129. len,
  18130. start,
  18131. end,
  18132. list;
  18133. for (i = 0, len = holeIndices.length; i < len; i++) {
  18134. start = holeIndices[i] * dim;
  18135. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  18136. list = linkedList(data, start, end, dim, false);
  18137. if (list === list.next) list.steiner = true;
  18138. queue.push(getLeftmost(list));
  18139. }
  18140. queue.sort(compareX); // process holes from left to right
  18141. for (i = 0; i < queue.length; i++) {
  18142. eliminateHole(queue[i], outerNode);
  18143. outerNode = filterPoints(outerNode, outerNode.next);
  18144. }
  18145. return outerNode;
  18146. }
  18147. function compareX(a, b) {
  18148. return a.x - b.x;
  18149. } // find a bridge between vertices that connects hole with an outer ring and and link it
  18150. function eliminateHole(hole, outerNode) {
  18151. outerNode = findHoleBridge(hole, outerNode);
  18152. if (outerNode) {
  18153. var b = splitPolygon(outerNode, hole);
  18154. filterPoints(b, b.next);
  18155. }
  18156. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18157. function findHoleBridge(hole, outerNode) {
  18158. var p = outerNode,
  18159. hx = hole.x,
  18160. hy = hole.y,
  18161. qx = -Infinity,
  18162. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  18163. // segment's endpoint with lesser x will be potential connection point
  18164. do {
  18165. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  18166. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  18167. if (x <= hx && x > qx) {
  18168. qx = x;
  18169. if (x === hx) {
  18170. if (hy === p.y) return p;
  18171. if (hy === p.next.y) return p.next;
  18172. }
  18173. m = p.x < p.next.x ? p : p.next;
  18174. }
  18175. }
  18176. p = p.next;
  18177. } while (p !== outerNode);
  18178. if (!m) return null;
  18179. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  18180. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18181. // if there are no points found, we have a valid connection;
  18182. // otherwise choose the point of the minimum angle with the ray as connection point
  18183. var stop = m,
  18184. mx = m.x,
  18185. my = m.y,
  18186. tanMin = Infinity,
  18187. tan;
  18188. p = m.next;
  18189. while (p !== stop) {
  18190. 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)) {
  18191. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  18192. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  18193. m = p;
  18194. tanMin = tan;
  18195. }
  18196. }
  18197. p = p.next;
  18198. }
  18199. return m;
  18200. } // interlink polygon nodes in z-order
  18201. function indexCurve(start, minX, minY, invSize) {
  18202. var p = start;
  18203. do {
  18204. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  18205. p.prevZ = p.prev;
  18206. p.nextZ = p.next;
  18207. p = p.next;
  18208. } while (p !== start);
  18209. p.prevZ.nextZ = null;
  18210. p.prevZ = null;
  18211. sortLinked(p);
  18212. } // Simon Tatham's linked list merge sort algorithm
  18213. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18214. function sortLinked(list) {
  18215. var i,
  18216. p,
  18217. q,
  18218. e,
  18219. tail,
  18220. numMerges,
  18221. pSize,
  18222. qSize,
  18223. inSize = 1;
  18224. do {
  18225. p = list;
  18226. list = null;
  18227. tail = null;
  18228. numMerges = 0;
  18229. while (p) {
  18230. numMerges++;
  18231. q = p;
  18232. pSize = 0;
  18233. for (i = 0; i < inSize; i++) {
  18234. pSize++;
  18235. q = q.nextZ;
  18236. if (!q) break;
  18237. }
  18238. qSize = inSize;
  18239. while (pSize > 0 || qSize > 0 && q) {
  18240. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  18241. e = p;
  18242. p = p.nextZ;
  18243. pSize--;
  18244. } else {
  18245. e = q;
  18246. q = q.nextZ;
  18247. qSize--;
  18248. }
  18249. if (tail) tail.nextZ = e;else list = e;
  18250. e.prevZ = tail;
  18251. tail = e;
  18252. }
  18253. p = q;
  18254. }
  18255. tail.nextZ = null;
  18256. inSize *= 2;
  18257. } while (numMerges > 1);
  18258. return list;
  18259. } // z-order of a point given coords and inverse of the longer side of data bbox
  18260. function zOrder(x, y, minX, minY, invSize) {
  18261. // coords are transformed into non-negative 15-bit integer range
  18262. x = 32767 * (x - minX) * invSize;
  18263. y = 32767 * (y - minY) * invSize;
  18264. x = (x | x << 8) & 0x00FF00FF;
  18265. x = (x | x << 4) & 0x0F0F0F0F;
  18266. x = (x | x << 2) & 0x33333333;
  18267. x = (x | x << 1) & 0x55555555;
  18268. y = (y | y << 8) & 0x00FF00FF;
  18269. y = (y | y << 4) & 0x0F0F0F0F;
  18270. y = (y | y << 2) & 0x33333333;
  18271. y = (y | y << 1) & 0x55555555;
  18272. return x | y << 1;
  18273. } // find the leftmost node of a polygon ring
  18274. function getLeftmost(start) {
  18275. var p = start,
  18276. leftmost = start;
  18277. do {
  18278. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  18279. p = p.next;
  18280. } while (p !== start);
  18281. return leftmost;
  18282. } // check if a point lies within a convex triangle
  18283. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  18284. 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;
  18285. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18286. function isValidDiagonal(a, b) {
  18287. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  18288. } // signed area of a triangle
  18289. function area(p, q, r) {
  18290. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  18291. } // check if two points are equal
  18292. function equals(p1, p2) {
  18293. return p1.x === p2.x && p1.y === p2.y;
  18294. } // check if two segments intersect
  18295. function intersects(p1, q1, p2, q2) {
  18296. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  18297. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  18298. } // check if a polygon diagonal intersects any polygon segments
  18299. function intersectsPolygon(a, b) {
  18300. var p = a;
  18301. do {
  18302. 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;
  18303. p = p.next;
  18304. } while (p !== a);
  18305. return false;
  18306. } // check if a polygon diagonal is locally inside the polygon
  18307. function locallyInside(a, b) {
  18308. 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;
  18309. } // check if the middle point of a polygon diagonal is inside the polygon
  18310. function middleInside(a, b) {
  18311. var p = a,
  18312. inside = false,
  18313. px = (a.x + b.x) / 2,
  18314. py = (a.y + b.y) / 2;
  18315. do {
  18316. 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;
  18317. p = p.next;
  18318. } while (p !== a);
  18319. return inside;
  18320. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18321. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18322. function splitPolygon(a, b) {
  18323. var a2 = new Node(a.i, a.x, a.y),
  18324. b2 = new Node(b.i, b.x, b.y),
  18325. an = a.next,
  18326. bp = b.prev;
  18327. a.next = b;
  18328. b.prev = a;
  18329. a2.next = an;
  18330. an.prev = a2;
  18331. b2.next = a2;
  18332. a2.prev = b2;
  18333. bp.next = b2;
  18334. b2.prev = bp;
  18335. return b2;
  18336. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  18337. function insertNode(i, x, y, last) {
  18338. var p = new Node(i, x, y);
  18339. if (!last) {
  18340. p.prev = p;
  18341. p.next = p;
  18342. } else {
  18343. p.next = last.next;
  18344. p.prev = last;
  18345. last.next.prev = p;
  18346. last.next = p;
  18347. }
  18348. return p;
  18349. }
  18350. function removeNode(p) {
  18351. p.next.prev = p.prev;
  18352. p.prev.next = p.next;
  18353. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  18354. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  18355. }
  18356. function Node(i, x, y) {
  18357. // vertex index in coordinates array
  18358. this.i = i; // vertex coordinates
  18359. this.x = x;
  18360. this.y = y; // previous and next vertex nodes in a polygon ring
  18361. this.prev = null;
  18362. this.next = null; // z-order curve value
  18363. this.z = null; // previous and next nodes in z-order
  18364. this.prevZ = null;
  18365. this.nextZ = null; // indicates whether this is a steiner point
  18366. this.steiner = false;
  18367. }
  18368. function signedArea(data, start, end, dim) {
  18369. var sum = 0;
  18370. for (var i = start, j = end - dim; i < end; i += dim) {
  18371. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18372. j = i;
  18373. }
  18374. return sum;
  18375. }
  18376. /**
  18377. * @author zz85 / http://www.lab4games.net/zz85/blog
  18378. */
  18379. var ShapeUtils = {
  18380. // calculate area of the contour polygon
  18381. area: function (contour) {
  18382. var n = contour.length;
  18383. var a = 0.0;
  18384. for (var p = n - 1, q = 0; q < n; p = q++) {
  18385. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  18386. }
  18387. return a * 0.5;
  18388. },
  18389. isClockWise: function (pts) {
  18390. return ShapeUtils.area(pts) < 0;
  18391. },
  18392. triangulateShape: function (contour, holes) {
  18393. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18394. var holeIndices = []; // array of hole indices
  18395. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18396. removeDupEndPts(contour);
  18397. addContour(vertices, contour); //
  18398. var holeIndex = contour.length;
  18399. holes.forEach(removeDupEndPts);
  18400. for (var i = 0; i < holes.length; i++) {
  18401. holeIndices.push(holeIndex);
  18402. holeIndex += holes[i].length;
  18403. addContour(vertices, holes[i]);
  18404. } //
  18405. var triangles = Earcut.triangulate(vertices, holeIndices); //
  18406. for (var i = 0; i < triangles.length; i += 3) {
  18407. faces.push(triangles.slice(i, i + 3));
  18408. }
  18409. return faces;
  18410. }
  18411. };
  18412. exports.ShapeUtils = ShapeUtils;
  18413. function removeDupEndPts(points) {
  18414. var l = points.length;
  18415. if (l > 2 && points[l - 1].equals(points[0])) {
  18416. points.pop();
  18417. }
  18418. }
  18419. function addContour(vertices, contour) {
  18420. for (var i = 0; i < contour.length; i++) {
  18421. vertices.push(contour[i].x);
  18422. vertices.push(contour[i].y);
  18423. }
  18424. }
  18425. /**
  18426. * @author zz85 / http://www.lab4games.net/zz85/blog
  18427. *
  18428. * Creates extruded geometry from a path shape.
  18429. *
  18430. * parameters = {
  18431. *
  18432. * curveSegments: <int>, // number of points on the curves
  18433. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18434. * depth: <float>, // Depth to extrude the shape
  18435. *
  18436. * bevelEnabled: <bool>, // turn on bevel
  18437. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18438. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18439. * bevelOffset: <float>, // how far from shape outline does bevel start
  18440. * bevelSegments: <int>, // number of bevel layers
  18441. *
  18442. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18443. *
  18444. * UVGenerator: <Object> // object that provides UV generator functions
  18445. *
  18446. * }
  18447. */
  18448. // ExtrudeGeometry
  18449. function ExtrudeGeometry(shapes, options) {
  18450. Geometry.call(this);
  18451. this.type = 'ExtrudeGeometry';
  18452. this.parameters = {
  18453. shapes: shapes,
  18454. options: options
  18455. };
  18456. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  18457. this.mergeVertices();
  18458. }
  18459. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  18460. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  18461. ExtrudeGeometry.prototype.toJSON = function () {
  18462. var data = Geometry.prototype.toJSON.call(this);
  18463. var shapes = this.parameters.shapes;
  18464. var options = this.parameters.options;
  18465. return toJSON(shapes, options, data);
  18466. }; // ExtrudeBufferGeometry
  18467. function ExtrudeBufferGeometry(shapes, options) {
  18468. BufferGeometry.call(this);
  18469. this.type = 'ExtrudeBufferGeometry';
  18470. this.parameters = {
  18471. shapes: shapes,
  18472. options: options
  18473. };
  18474. shapes = Array.isArray(shapes) ? shapes : [shapes];
  18475. var scope = this;
  18476. var verticesArray = [];
  18477. var uvArray = [];
  18478. for (var i = 0, l = shapes.length; i < l; i++) {
  18479. var shape = shapes[i];
  18480. addShape(shape);
  18481. } // build geometry
  18482. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  18483. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  18484. this.computeVertexNormals(); // functions
  18485. function addShape(shape) {
  18486. var placeholder = []; // options
  18487. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18488. var steps = options.steps !== undefined ? options.steps : 1;
  18489. var depth = options.depth !== undefined ? options.depth : 100;
  18490. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18491. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18492. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18493. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18494. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18495. var extrudePath = options.extrudePath;
  18496. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  18497. if (options.amount !== undefined) {
  18498. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  18499. depth = options.amount;
  18500. } //
  18501. var extrudePts,
  18502. extrudeByPath = false;
  18503. var splineTube, binormal, normal, position2;
  18504. if (extrudePath) {
  18505. extrudePts = extrudePath.getSpacedPoints(steps);
  18506. extrudeByPath = true;
  18507. bevelEnabled = false; // bevels not supported for path extrusion
  18508. // SETUP TNB variables
  18509. // TODO1 - have a .isClosed in spline?
  18510. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18511. binormal = new Vector3();
  18512. normal = new Vector3();
  18513. position2 = new Vector3();
  18514. } // Safeguards if bevels are not enabled
  18515. if (!bevelEnabled) {
  18516. bevelSegments = 0;
  18517. bevelThickness = 0;
  18518. bevelSize = 0;
  18519. bevelOffset = 0;
  18520. } // Variables initialization
  18521. var ahole, h, hl; // looping of holes
  18522. var shapePoints = shape.extractPoints(curveSegments);
  18523. var vertices = shapePoints.shape;
  18524. var holes = shapePoints.holes;
  18525. var reverse = !ShapeUtils.isClockWise(vertices);
  18526. if (reverse) {
  18527. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18528. for (h = 0, hl = holes.length; h < hl; h++) {
  18529. ahole = holes[h];
  18530. if (ShapeUtils.isClockWise(ahole)) {
  18531. holes[h] = ahole.reverse();
  18532. }
  18533. }
  18534. }
  18535. var faces = ShapeUtils.triangulateShape(vertices, holes);
  18536. /* Vertices */
  18537. var contour = vertices; // vertices has all points but contour has only points of circumference
  18538. for (h = 0, hl = holes.length; h < hl; h++) {
  18539. ahole = holes[h];
  18540. vertices = vertices.concat(ahole);
  18541. }
  18542. function scalePt2(pt, vec, size) {
  18543. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  18544. return vec.clone().multiplyScalar(size).add(pt);
  18545. }
  18546. var b,
  18547. bs,
  18548. t,
  18549. z,
  18550. vert,
  18551. vlen = vertices.length,
  18552. face,
  18553. flen = faces.length; // Find directions for point movement
  18554. function getBevelVec(inPt, inPrev, inNext) {
  18555. // computes for inPt the corresponding point inPt' on a new contour
  18556. // shifted by 1 unit (length of normalized vector) to the left
  18557. // if we walk along contour clockwise, this new contour is outside the old one
  18558. //
  18559. // inPt' is the intersection of the two lines parallel to the two
  18560. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18561. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18562. // good reading for geometry algorithms (here: line-line intersection)
  18563. // http://geomalgorithms.com/a05-_intersect-1.html
  18564. var v_prev_x = inPt.x - inPrev.x,
  18565. v_prev_y = inPt.y - inPrev.y;
  18566. var v_next_x = inNext.x - inPt.x,
  18567. v_next_y = inNext.y - inPt.y;
  18568. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  18569. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  18570. if (Math.abs(collinear0) > Number.EPSILON) {
  18571. // not collinear
  18572. // length of vectors for normalizing
  18573. var v_prev_len = Math.sqrt(v_prev_lensq);
  18574. 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
  18575. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  18576. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  18577. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  18578. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  18579. 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
  18580. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  18581. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  18582. // but prevent crazy spikes
  18583. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  18584. if (v_trans_lensq <= 2) {
  18585. return new Vector2(v_trans_x, v_trans_y);
  18586. } else {
  18587. shrink_by = Math.sqrt(v_trans_lensq / 2);
  18588. }
  18589. } else {
  18590. // handle special case of collinear edges
  18591. var direction_eq = false; // assumes: opposite
  18592. if (v_prev_x > Number.EPSILON) {
  18593. if (v_next_x > Number.EPSILON) {
  18594. direction_eq = true;
  18595. }
  18596. } else {
  18597. if (v_prev_x < -Number.EPSILON) {
  18598. if (v_next_x < -Number.EPSILON) {
  18599. direction_eq = true;
  18600. }
  18601. } else {
  18602. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  18603. direction_eq = true;
  18604. }
  18605. }
  18606. }
  18607. if (direction_eq) {
  18608. // console.log("Warning: lines are a straight sequence");
  18609. v_trans_x = -v_prev_y;
  18610. v_trans_y = v_prev_x;
  18611. shrink_by = Math.sqrt(v_prev_lensq);
  18612. } else {
  18613. // console.log("Warning: lines are a straight spike");
  18614. v_trans_x = v_prev_x;
  18615. v_trans_y = v_prev_y;
  18616. shrink_by = Math.sqrt(v_prev_lensq / 2);
  18617. }
  18618. }
  18619. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  18620. }
  18621. var contourMovements = [];
  18622. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18623. if (j === il) j = 0;
  18624. if (k === il) k = 0; // (j)---(i)---(k)
  18625. // console.log('i,j,k', i, j , k)
  18626. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  18627. }
  18628. var holesMovements = [],
  18629. oneHoleMovements,
  18630. verticesMovements = contourMovements.concat();
  18631. for (h = 0, hl = holes.length; h < hl; h++) {
  18632. ahole = holes[h];
  18633. oneHoleMovements = [];
  18634. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18635. if (j === il) j = 0;
  18636. if (k === il) k = 0; // (j)---(i)---(k)
  18637. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  18638. }
  18639. holesMovements.push(oneHoleMovements);
  18640. verticesMovements = verticesMovements.concat(oneHoleMovements);
  18641. } // Loop bevelSegments, 1 for the front, 1 for the back
  18642. for (b = 0; b < bevelSegments; b++) {
  18643. //for ( b = bevelSegments; b > 0; b -- ) {
  18644. t = b / bevelSegments;
  18645. z = bevelThickness * Math.cos(t * Math.PI / 2);
  18646. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18647. for (i = 0, il = contour.length; i < il; i++) {
  18648. vert = scalePt2(contour[i], contourMovements[i], bs);
  18649. v(vert.x, vert.y, -z);
  18650. } // expand holes
  18651. for (h = 0, hl = holes.length; h < hl; h++) {
  18652. ahole = holes[h];
  18653. oneHoleMovements = holesMovements[h];
  18654. for (i = 0, il = ahole.length; i < il; i++) {
  18655. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18656. v(vert.x, vert.y, -z);
  18657. }
  18658. }
  18659. }
  18660. bs = bevelSize + bevelOffset; // Back facing vertices
  18661. for (i = 0; i < vlen; i++) {
  18662. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18663. if (!extrudeByPath) {
  18664. v(vert.x, vert.y, 0);
  18665. } else {
  18666. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18667. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  18668. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  18669. position2.copy(extrudePts[0]).add(normal).add(binormal);
  18670. v(position2.x, position2.y, position2.z);
  18671. }
  18672. } // Add stepped vertices...
  18673. // Including front facing vertices
  18674. var s;
  18675. for (s = 1; s <= steps; s++) {
  18676. for (i = 0; i < vlen; i++) {
  18677. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18678. if (!extrudeByPath) {
  18679. v(vert.x, vert.y, depth / steps * s);
  18680. } else {
  18681. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18682. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  18683. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  18684. position2.copy(extrudePts[s]).add(normal).add(binormal);
  18685. v(position2.x, position2.y, position2.z);
  18686. }
  18687. }
  18688. } // Add bevel segments planes
  18689. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18690. for (b = bevelSegments - 1; b >= 0; b--) {
  18691. t = b / bevelSegments;
  18692. z = bevelThickness * Math.cos(t * Math.PI / 2);
  18693. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18694. for (i = 0, il = contour.length; i < il; i++) {
  18695. vert = scalePt2(contour[i], contourMovements[i], bs);
  18696. v(vert.x, vert.y, depth + z);
  18697. } // expand holes
  18698. for (h = 0, hl = holes.length; h < hl; h++) {
  18699. ahole = holes[h];
  18700. oneHoleMovements = holesMovements[h];
  18701. for (i = 0, il = ahole.length; i < il; i++) {
  18702. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18703. if (!extrudeByPath) {
  18704. v(vert.x, vert.y, depth + z);
  18705. } else {
  18706. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  18707. }
  18708. }
  18709. }
  18710. }
  18711. /* Faces */
  18712. // Top and bottom faces
  18713. buildLidFaces(); // Sides faces
  18714. buildSideFaces(); ///// Internal functions
  18715. function buildLidFaces() {
  18716. var start = verticesArray.length / 3;
  18717. if (bevelEnabled) {
  18718. var layer = 0; // steps + 1
  18719. var offset = vlen * layer; // Bottom faces
  18720. for (i = 0; i < flen; i++) {
  18721. face = faces[i];
  18722. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  18723. }
  18724. layer = steps + bevelSegments * 2;
  18725. offset = vlen * layer; // Top faces
  18726. for (i = 0; i < flen; i++) {
  18727. face = faces[i];
  18728. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  18729. }
  18730. } else {
  18731. // Bottom faces
  18732. for (i = 0; i < flen; i++) {
  18733. face = faces[i];
  18734. f3(face[2], face[1], face[0]);
  18735. } // Top faces
  18736. for (i = 0; i < flen; i++) {
  18737. face = faces[i];
  18738. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  18739. }
  18740. }
  18741. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  18742. } // Create faces for the z-sides of the shape
  18743. function buildSideFaces() {
  18744. var start = verticesArray.length / 3;
  18745. var layeroffset = 0;
  18746. sidewalls(contour, layeroffset);
  18747. layeroffset += contour.length;
  18748. for (h = 0, hl = holes.length; h < hl; h++) {
  18749. ahole = holes[h];
  18750. sidewalls(ahole, layeroffset); //, true
  18751. layeroffset += ahole.length;
  18752. }
  18753. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  18754. }
  18755. function sidewalls(contour, layeroffset) {
  18756. var j, k;
  18757. i = contour.length;
  18758. while (--i >= 0) {
  18759. j = i;
  18760. k = i - 1;
  18761. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  18762. var s = 0,
  18763. sl = steps + bevelSegments * 2;
  18764. for (s = 0; s < sl; s++) {
  18765. var slen1 = vlen * s;
  18766. var slen2 = vlen * (s + 1);
  18767. var a = layeroffset + j + slen1,
  18768. b = layeroffset + k + slen1,
  18769. c = layeroffset + k + slen2,
  18770. d = layeroffset + j + slen2;
  18771. f4(a, b, c, d);
  18772. }
  18773. }
  18774. }
  18775. function v(x, y, z) {
  18776. placeholder.push(x);
  18777. placeholder.push(y);
  18778. placeholder.push(z);
  18779. }
  18780. function f3(a, b, c) {
  18781. addVertex(a);
  18782. addVertex(b);
  18783. addVertex(c);
  18784. var nextIndex = verticesArray.length / 3;
  18785. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18786. addUV(uvs[0]);
  18787. addUV(uvs[1]);
  18788. addUV(uvs[2]);
  18789. }
  18790. function f4(a, b, c, d) {
  18791. addVertex(a);
  18792. addVertex(b);
  18793. addVertex(d);
  18794. addVertex(b);
  18795. addVertex(c);
  18796. addVertex(d);
  18797. var nextIndex = verticesArray.length / 3;
  18798. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18799. addUV(uvs[0]);
  18800. addUV(uvs[1]);
  18801. addUV(uvs[3]);
  18802. addUV(uvs[1]);
  18803. addUV(uvs[2]);
  18804. addUV(uvs[3]);
  18805. }
  18806. function addVertex(index) {
  18807. verticesArray.push(placeholder[index * 3 + 0]);
  18808. verticesArray.push(placeholder[index * 3 + 1]);
  18809. verticesArray.push(placeholder[index * 3 + 2]);
  18810. }
  18811. function addUV(vector2) {
  18812. uvArray.push(vector2.x);
  18813. uvArray.push(vector2.y);
  18814. }
  18815. }
  18816. }
  18817. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18818. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  18819. ExtrudeBufferGeometry.prototype.toJSON = function () {
  18820. var data = BufferGeometry.prototype.toJSON.call(this);
  18821. var shapes = this.parameters.shapes;
  18822. var options = this.parameters.options;
  18823. return toJSON(shapes, options, data);
  18824. }; //
  18825. var WorldUVGenerator = {
  18826. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  18827. var a_x = vertices[indexA * 3];
  18828. var a_y = vertices[indexA * 3 + 1];
  18829. var b_x = vertices[indexB * 3];
  18830. var b_y = vertices[indexB * 3 + 1];
  18831. var c_x = vertices[indexC * 3];
  18832. var c_y = vertices[indexC * 3 + 1];
  18833. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  18834. },
  18835. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  18836. var a_x = vertices[indexA * 3];
  18837. var a_y = vertices[indexA * 3 + 1];
  18838. var a_z = vertices[indexA * 3 + 2];
  18839. var b_x = vertices[indexB * 3];
  18840. var b_y = vertices[indexB * 3 + 1];
  18841. var b_z = vertices[indexB * 3 + 2];
  18842. var c_x = vertices[indexC * 3];
  18843. var c_y = vertices[indexC * 3 + 1];
  18844. var c_z = vertices[indexC * 3 + 2];
  18845. var d_x = vertices[indexD * 3];
  18846. var d_y = vertices[indexD * 3 + 1];
  18847. var d_z = vertices[indexD * 3 + 2];
  18848. if (Math.abs(a_y - b_y) < 0.01) {
  18849. 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)];
  18850. } else {
  18851. 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)];
  18852. }
  18853. }
  18854. };
  18855. function toJSON(shapes, options, data) {
  18856. //
  18857. data.shapes = [];
  18858. if (Array.isArray(shapes)) {
  18859. for (var i = 0, l = shapes.length; i < l; i++) {
  18860. var shape = shapes[i];
  18861. data.shapes.push(shape.uuid);
  18862. }
  18863. } else {
  18864. data.shapes.push(shapes.uuid);
  18865. } //
  18866. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  18867. return data;
  18868. }
  18869. /**
  18870. * @author zz85 / http://www.lab4games.net/zz85/blog
  18871. * @author alteredq / http://alteredqualia.com/
  18872. *
  18873. * Text = 3D Text
  18874. *
  18875. * parameters = {
  18876. * font: <THREE.Font>, // font
  18877. *
  18878. * size: <float>, // size of the text
  18879. * height: <float>, // thickness to extrude text
  18880. * curveSegments: <int>, // number of points on the curves
  18881. *
  18882. * bevelEnabled: <bool>, // turn on bevel
  18883. * bevelThickness: <float>, // how deep into text bevel goes
  18884. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18885. * bevelOffset: <float> // how far from text outline does bevel start
  18886. * }
  18887. */
  18888. // TextGeometry
  18889. function TextGeometry(text, parameters) {
  18890. Geometry.call(this);
  18891. this.type = 'TextGeometry';
  18892. this.parameters = {
  18893. text: text,
  18894. parameters: parameters
  18895. };
  18896. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  18897. this.mergeVertices();
  18898. }
  18899. TextGeometry.prototype = Object.create(Geometry.prototype);
  18900. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  18901. function TextBufferGeometry(text, parameters) {
  18902. parameters = parameters || {};
  18903. var font = parameters.font;
  18904. if (!(font && font.isFont)) {
  18905. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  18906. return new Geometry();
  18907. }
  18908. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  18909. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  18910. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  18911. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  18912. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  18913. ExtrudeBufferGeometry.call(this, shapes, parameters);
  18914. this.type = 'TextBufferGeometry';
  18915. }
  18916. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  18917. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  18918. /**
  18919. * @author mrdoob / http://mrdoob.com/
  18920. * @author benaadams / https://twitter.com/ben_a_adams
  18921. * @author Mugen87 / https://github.com/Mugen87
  18922. */
  18923. // SphereGeometry
  18924. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  18925. Geometry.call(this);
  18926. this.type = 'SphereGeometry';
  18927. this.parameters = {
  18928. radius: radius,
  18929. widthSegments: widthSegments,
  18930. heightSegments: heightSegments,
  18931. phiStart: phiStart,
  18932. phiLength: phiLength,
  18933. thetaStart: thetaStart,
  18934. thetaLength: thetaLength
  18935. };
  18936. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  18937. this.mergeVertices();
  18938. }
  18939. SphereGeometry.prototype = Object.create(Geometry.prototype);
  18940. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  18941. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  18942. BufferGeometry.call(this);
  18943. this.type = 'SphereBufferGeometry';
  18944. this.parameters = {
  18945. radius: radius,
  18946. widthSegments: widthSegments,
  18947. heightSegments: heightSegments,
  18948. phiStart: phiStart,
  18949. phiLength: phiLength,
  18950. thetaStart: thetaStart,
  18951. thetaLength: thetaLength
  18952. };
  18953. radius = radius || 1;
  18954. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  18955. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  18956. phiStart = phiStart !== undefined ? phiStart : 0;
  18957. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18958. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18959. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18960. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  18961. var ix, iy;
  18962. var index = 0;
  18963. var grid = [];
  18964. var vertex = new Vector3();
  18965. var normal = new Vector3(); // buffers
  18966. var indices = [];
  18967. var vertices = [];
  18968. var normals = [];
  18969. var uvs = []; // generate vertices, normals and uvs
  18970. for (iy = 0; iy <= heightSegments; iy++) {
  18971. var verticesRow = [];
  18972. var v = iy / heightSegments; // special case for the poles
  18973. var uOffset = 0;
  18974. if (iy == 0 && thetaStart == 0) {
  18975. uOffset = 0.5 / widthSegments;
  18976. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  18977. uOffset = -0.5 / widthSegments;
  18978. }
  18979. for (ix = 0; ix <= widthSegments; ix++) {
  18980. var u = ix / widthSegments; // vertex
  18981. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18982. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  18983. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18984. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18985. normal.copy(vertex).normalize();
  18986. normals.push(normal.x, normal.y, normal.z); // uv
  18987. uvs.push(u + uOffset, 1 - v);
  18988. verticesRow.push(index++);
  18989. }
  18990. grid.push(verticesRow);
  18991. } // indices
  18992. for (iy = 0; iy < heightSegments; iy++) {
  18993. for (ix = 0; ix < widthSegments; ix++) {
  18994. var a = grid[iy][ix + 1];
  18995. var b = grid[iy][ix];
  18996. var c = grid[iy + 1][ix];
  18997. var d = grid[iy + 1][ix + 1];
  18998. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  18999. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19000. }
  19001. } // build geometry
  19002. this.setIndex(indices);
  19003. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19004. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19005. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19006. }
  19007. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19008. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  19009. /**
  19010. * @author Kaleb Murphy
  19011. * @author Mugen87 / https://github.com/Mugen87
  19012. */
  19013. // RingGeometry
  19014. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19015. Geometry.call(this);
  19016. this.type = 'RingGeometry';
  19017. this.parameters = {
  19018. innerRadius: innerRadius,
  19019. outerRadius: outerRadius,
  19020. thetaSegments: thetaSegments,
  19021. phiSegments: phiSegments,
  19022. thetaStart: thetaStart,
  19023. thetaLength: thetaLength
  19024. };
  19025. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19026. this.mergeVertices();
  19027. }
  19028. RingGeometry.prototype = Object.create(Geometry.prototype);
  19029. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  19030. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19031. BufferGeometry.call(this);
  19032. this.type = 'RingBufferGeometry';
  19033. this.parameters = {
  19034. innerRadius: innerRadius,
  19035. outerRadius: outerRadius,
  19036. thetaSegments: thetaSegments,
  19037. phiSegments: phiSegments,
  19038. thetaStart: thetaStart,
  19039. thetaLength: thetaLength
  19040. };
  19041. innerRadius = innerRadius || 0.5;
  19042. outerRadius = outerRadius || 1;
  19043. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19044. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19045. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  19046. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  19047. var indices = [];
  19048. var vertices = [];
  19049. var normals = [];
  19050. var uvs = []; // some helper variables
  19051. var segment;
  19052. var radius = innerRadius;
  19053. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  19054. var vertex = new Vector3();
  19055. var uv = new Vector2();
  19056. var j, i; // generate vertices, normals and uvs
  19057. for (j = 0; j <= phiSegments; j++) {
  19058. for (i = 0; i <= thetaSegments; i++) {
  19059. // values are generate from the inside of the ring to the outside
  19060. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19061. vertex.x = radius * Math.cos(segment);
  19062. vertex.y = radius * Math.sin(segment);
  19063. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19064. normals.push(0, 0, 1); // uv
  19065. uv.x = (vertex.x / outerRadius + 1) / 2;
  19066. uv.y = (vertex.y / outerRadius + 1) / 2;
  19067. uvs.push(uv.x, uv.y);
  19068. } // increase the radius for next row of vertices
  19069. radius += radiusStep;
  19070. } // indices
  19071. for (j = 0; j < phiSegments; j++) {
  19072. var thetaSegmentLevel = j * (thetaSegments + 1);
  19073. for (i = 0; i < thetaSegments; i++) {
  19074. segment = i + thetaSegmentLevel;
  19075. var a = segment;
  19076. var b = segment + thetaSegments + 1;
  19077. var c = segment + thetaSegments + 2;
  19078. var d = segment + 1; // faces
  19079. indices.push(a, b, d);
  19080. indices.push(b, c, d);
  19081. }
  19082. } // build geometry
  19083. this.setIndex(indices);
  19084. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19085. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19086. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19087. }
  19088. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19089. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  19090. /**
  19091. * @author zz85 / https://github.com/zz85
  19092. * @author bhouston / http://clara.io
  19093. * @author Mugen87 / https://github.com/Mugen87
  19094. */
  19095. // LatheGeometry
  19096. function LatheGeometry(points, segments, phiStart, phiLength) {
  19097. Geometry.call(this);
  19098. this.type = 'LatheGeometry';
  19099. this.parameters = {
  19100. points: points,
  19101. segments: segments,
  19102. phiStart: phiStart,
  19103. phiLength: phiLength
  19104. };
  19105. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19106. this.mergeVertices();
  19107. }
  19108. LatheGeometry.prototype = Object.create(Geometry.prototype);
  19109. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  19110. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  19111. BufferGeometry.call(this);
  19112. this.type = 'LatheBufferGeometry';
  19113. this.parameters = {
  19114. points: points,
  19115. segments: segments,
  19116. phiStart: phiStart,
  19117. phiLength: phiLength
  19118. };
  19119. segments = Math.floor(segments) || 12;
  19120. phiStart = phiStart || 0;
  19121. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  19122. phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
  19123. var indices = [];
  19124. var vertices = [];
  19125. var uvs = []; // helper variables
  19126. var base;
  19127. var inverseSegments = 1.0 / segments;
  19128. var vertex = new Vector3();
  19129. var uv = new Vector2();
  19130. var i, j; // generate vertices and uvs
  19131. for (i = 0; i <= segments; i++) {
  19132. var phi = phiStart + i * inverseSegments * phiLength;
  19133. var sin = Math.sin(phi);
  19134. var cos = Math.cos(phi);
  19135. for (j = 0; j <= points.length - 1; j++) {
  19136. // vertex
  19137. vertex.x = points[j].x * sin;
  19138. vertex.y = points[j].y;
  19139. vertex.z = points[j].x * cos;
  19140. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19141. uv.x = i / segments;
  19142. uv.y = j / (points.length - 1);
  19143. uvs.push(uv.x, uv.y);
  19144. }
  19145. } // indices
  19146. for (i = 0; i < segments; i++) {
  19147. for (j = 0; j < points.length - 1; j++) {
  19148. base = j + i * points.length;
  19149. var a = base;
  19150. var b = base + points.length;
  19151. var c = base + points.length + 1;
  19152. var d = base + 1; // faces
  19153. indices.push(a, b, d);
  19154. indices.push(b, c, d);
  19155. }
  19156. } // build geometry
  19157. this.setIndex(indices);
  19158. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19159. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  19160. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  19161. // because the corresponding vertices are identical (but still have different UVs).
  19162. if (phiLength === Math.PI * 2) {
  19163. var normals = this.attributes.normal.array;
  19164. var n1 = new Vector3();
  19165. var n2 = new Vector3();
  19166. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  19167. base = segments * points.length * 3;
  19168. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  19169. // select the normal of the vertex in the first line
  19170. n1.x = normals[j + 0];
  19171. n1.y = normals[j + 1];
  19172. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  19173. n2.x = normals[base + j + 0];
  19174. n2.y = normals[base + j + 1];
  19175. n2.z = normals[base + j + 2]; // average normals
  19176. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  19177. normals[j + 0] = normals[base + j + 0] = n.x;
  19178. normals[j + 1] = normals[base + j + 1] = n.y;
  19179. normals[j + 2] = normals[base + j + 2] = n.z;
  19180. }
  19181. }
  19182. }
  19183. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19184. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  19185. /**
  19186. * @author jonobr1 / http://jonobr1.com
  19187. * @author Mugen87 / https://github.com/Mugen87
  19188. */
  19189. // ShapeGeometry
  19190. function ShapeGeometry(shapes, curveSegments) {
  19191. Geometry.call(this);
  19192. this.type = 'ShapeGeometry';
  19193. if (typeof curveSegments === 'object') {
  19194. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  19195. curveSegments = curveSegments.curveSegments;
  19196. }
  19197. this.parameters = {
  19198. shapes: shapes,
  19199. curveSegments: curveSegments
  19200. };
  19201. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  19202. this.mergeVertices();
  19203. }
  19204. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  19205. ShapeGeometry.prototype.constructor = ShapeGeometry;
  19206. ShapeGeometry.prototype.toJSON = function () {
  19207. var data = Geometry.prototype.toJSON.call(this);
  19208. var shapes = this.parameters.shapes;
  19209. return toJSON$1(shapes, data);
  19210. }; // ShapeBufferGeometry
  19211. function ShapeBufferGeometry(shapes, curveSegments) {
  19212. BufferGeometry.call(this);
  19213. this.type = 'ShapeBufferGeometry';
  19214. this.parameters = {
  19215. shapes: shapes,
  19216. curveSegments: curveSegments
  19217. };
  19218. curveSegments = curveSegments || 12; // buffers
  19219. var indices = [];
  19220. var vertices = [];
  19221. var normals = [];
  19222. var uvs = []; // helper variables
  19223. var groupStart = 0;
  19224. var groupCount = 0; // allow single and array values for "shapes" parameter
  19225. if (Array.isArray(shapes) === false) {
  19226. addShape(shapes);
  19227. } else {
  19228. for (var i = 0; i < shapes.length; i++) {
  19229. addShape(shapes[i]);
  19230. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19231. groupStart += groupCount;
  19232. groupCount = 0;
  19233. }
  19234. } // build geometry
  19235. this.setIndex(indices);
  19236. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19237. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19238. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19239. function addShape(shape) {
  19240. var i, l, shapeHole;
  19241. var indexOffset = vertices.length / 3;
  19242. var points = shape.extractPoints(curveSegments);
  19243. var shapeVertices = points.shape;
  19244. var shapeHoles = points.holes; // check direction of vertices
  19245. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19246. shapeVertices = shapeVertices.reverse();
  19247. }
  19248. for (i = 0, l = shapeHoles.length; i < l; i++) {
  19249. shapeHole = shapeHoles[i];
  19250. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19251. shapeHoles[i] = shapeHole.reverse();
  19252. }
  19253. }
  19254. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19255. for (i = 0, l = shapeHoles.length; i < l; i++) {
  19256. shapeHole = shapeHoles[i];
  19257. shapeVertices = shapeVertices.concat(shapeHole);
  19258. } // vertices, normals, uvs
  19259. for (i = 0, l = shapeVertices.length; i < l; i++) {
  19260. var vertex = shapeVertices[i];
  19261. vertices.push(vertex.x, vertex.y, 0);
  19262. normals.push(0, 0, 1);
  19263. uvs.push(vertex.x, vertex.y); // world uvs
  19264. } // incides
  19265. for (i = 0, l = faces.length; i < l; i++) {
  19266. var face = faces[i];
  19267. var a = face[0] + indexOffset;
  19268. var b = face[1] + indexOffset;
  19269. var c = face[2] + indexOffset;
  19270. indices.push(a, b, c);
  19271. groupCount += 3;
  19272. }
  19273. }
  19274. }
  19275. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19276. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  19277. ShapeBufferGeometry.prototype.toJSON = function () {
  19278. var data = BufferGeometry.prototype.toJSON.call(this);
  19279. var shapes = this.parameters.shapes;
  19280. return toJSON$1(shapes, data);
  19281. }; //
  19282. function toJSON$1(shapes, data) {
  19283. data.shapes = [];
  19284. if (Array.isArray(shapes)) {
  19285. for (var i = 0, l = shapes.length; i < l; i++) {
  19286. var shape = shapes[i];
  19287. data.shapes.push(shape.uuid);
  19288. }
  19289. } else {
  19290. data.shapes.push(shapes.uuid);
  19291. }
  19292. return data;
  19293. }
  19294. /**
  19295. * @author WestLangley / http://github.com/WestLangley
  19296. * @author Mugen87 / https://github.com/Mugen87
  19297. */
  19298. function EdgesGeometry(geometry, thresholdAngle) {
  19299. BufferGeometry.call(this);
  19300. this.type = 'EdgesGeometry';
  19301. this.parameters = {
  19302. thresholdAngle: thresholdAngle
  19303. };
  19304. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  19305. var vertices = []; // helper variables
  19306. var thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
  19307. var edge = [0, 0],
  19308. edges = {},
  19309. edge1,
  19310. edge2;
  19311. var key,
  19312. keys = ['a', 'b', 'c']; // prepare source geometry
  19313. var geometry2;
  19314. if (geometry.isBufferGeometry) {
  19315. geometry2 = new Geometry();
  19316. geometry2.fromBufferGeometry(geometry);
  19317. } else {
  19318. geometry2 = geometry.clone();
  19319. }
  19320. geometry2.mergeVertices();
  19321. geometry2.computeFaceNormals();
  19322. var sourceVertices = geometry2.vertices;
  19323. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  19324. for (var i = 0, l = faces.length; i < l; i++) {
  19325. var face = faces[i];
  19326. for (var j = 0; j < 3; j++) {
  19327. edge1 = face[keys[j]];
  19328. edge2 = face[keys[(j + 1) % 3]];
  19329. edge[0] = Math.min(edge1, edge2);
  19330. edge[1] = Math.max(edge1, edge2);
  19331. key = edge[0] + ',' + edge[1];
  19332. if (edges[key] === undefined) {
  19333. edges[key] = {
  19334. index1: edge[0],
  19335. index2: edge[1],
  19336. face1: i,
  19337. face2: undefined
  19338. };
  19339. } else {
  19340. edges[key].face2 = i;
  19341. }
  19342. }
  19343. } // generate vertices
  19344. for (key in edges) {
  19345. 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.
  19346. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  19347. var vertex = sourceVertices[e.index1];
  19348. vertices.push(vertex.x, vertex.y, vertex.z);
  19349. vertex = sourceVertices[e.index2];
  19350. vertices.push(vertex.x, vertex.y, vertex.z);
  19351. }
  19352. } // build geometry
  19353. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19354. }
  19355. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  19356. EdgesGeometry.prototype.constructor = EdgesGeometry;
  19357. /**
  19358. * @author mrdoob / http://mrdoob.com/
  19359. * @author Mugen87 / https://github.com/Mugen87
  19360. */
  19361. // CylinderGeometry
  19362. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19363. Geometry.call(this);
  19364. this.type = 'CylinderGeometry';
  19365. this.parameters = {
  19366. radiusTop: radiusTop,
  19367. radiusBottom: radiusBottom,
  19368. height: height,
  19369. radialSegments: radialSegments,
  19370. heightSegments: heightSegments,
  19371. openEnded: openEnded,
  19372. thetaStart: thetaStart,
  19373. thetaLength: thetaLength
  19374. };
  19375. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  19376. this.mergeVertices();
  19377. }
  19378. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  19379. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  19380. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19381. BufferGeometry.call(this);
  19382. this.type = 'CylinderBufferGeometry';
  19383. this.parameters = {
  19384. radiusTop: radiusTop,
  19385. radiusBottom: radiusBottom,
  19386. height: height,
  19387. radialSegments: radialSegments,
  19388. heightSegments: heightSegments,
  19389. openEnded: openEnded,
  19390. thetaStart: thetaStart,
  19391. thetaLength: thetaLength
  19392. };
  19393. var scope = this;
  19394. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  19395. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  19396. height = height || 1;
  19397. radialSegments = Math.floor(radialSegments) || 8;
  19398. heightSegments = Math.floor(heightSegments) || 1;
  19399. openEnded = openEnded !== undefined ? openEnded : false;
  19400. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  19401. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  19402. var indices = [];
  19403. var vertices = [];
  19404. var normals = [];
  19405. var uvs = []; // helper variables
  19406. var index = 0;
  19407. var indexArray = [];
  19408. var halfHeight = height / 2;
  19409. var groupStart = 0; // generate geometry
  19410. generateTorso();
  19411. if (openEnded === false) {
  19412. if (radiusTop > 0) generateCap(true);
  19413. if (radiusBottom > 0) generateCap(false);
  19414. } // build geometry
  19415. this.setIndex(indices);
  19416. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19417. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19418. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19419. function generateTorso() {
  19420. var x, y;
  19421. var normal = new Vector3();
  19422. var vertex = new Vector3();
  19423. var groupCount = 0; // this will be used to calculate the normal
  19424. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  19425. for (y = 0; y <= heightSegments; y++) {
  19426. var indexRow = [];
  19427. var v = y / heightSegments; // calculate the radius of the current row
  19428. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  19429. for (x = 0; x <= radialSegments; x++) {
  19430. var u = x / radialSegments;
  19431. var theta = u * thetaLength + thetaStart;
  19432. var sinTheta = Math.sin(theta);
  19433. var cosTheta = Math.cos(theta); // vertex
  19434. vertex.x = radius * sinTheta;
  19435. vertex.y = -v * height + halfHeight;
  19436. vertex.z = radius * cosTheta;
  19437. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19438. normal.set(sinTheta, slope, cosTheta).normalize();
  19439. normals.push(normal.x, normal.y, normal.z); // uv
  19440. uvs.push(u, 1 - v); // save index of vertex in respective row
  19441. indexRow.push(index++);
  19442. } // now save vertices of the row in our index array
  19443. indexArray.push(indexRow);
  19444. } // generate indices
  19445. for (x = 0; x < radialSegments; x++) {
  19446. for (y = 0; y < heightSegments; y++) {
  19447. // we use the index array to access the correct indices
  19448. var a = indexArray[y][x];
  19449. var b = indexArray[y + 1][x];
  19450. var c = indexArray[y + 1][x + 1];
  19451. var d = indexArray[y][x + 1]; // faces
  19452. indices.push(a, b, d);
  19453. indices.push(b, c, d); // update group counter
  19454. groupCount += 6;
  19455. }
  19456. } // add a group to the geometry. this will ensure multi material support
  19457. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  19458. groupStart += groupCount;
  19459. }
  19460. function generateCap(top) {
  19461. var x, centerIndexStart, centerIndexEnd;
  19462. var uv = new Vector2();
  19463. var vertex = new Vector3();
  19464. var groupCount = 0;
  19465. var radius = top === true ? radiusTop : radiusBottom;
  19466. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  19467. centerIndexStart = index; // first we generate the center vertex data of the cap.
  19468. // because the geometry needs one set of uvs per face,
  19469. // we must generate a center vertex per face/segment
  19470. for (x = 1; x <= radialSegments; x++) {
  19471. // vertex
  19472. vertices.push(0, halfHeight * sign, 0); // normal
  19473. normals.push(0, sign, 0); // uv
  19474. uvs.push(0.5, 0.5); // increase index
  19475. index++;
  19476. } // save the index of the last center vertex
  19477. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  19478. for (x = 0; x <= radialSegments; x++) {
  19479. var u = x / radialSegments;
  19480. var theta = u * thetaLength + thetaStart;
  19481. var cosTheta = Math.cos(theta);
  19482. var sinTheta = Math.sin(theta); // vertex
  19483. vertex.x = radius * sinTheta;
  19484. vertex.y = halfHeight * sign;
  19485. vertex.z = radius * cosTheta;
  19486. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19487. normals.push(0, sign, 0); // uv
  19488. uv.x = cosTheta * 0.5 + 0.5;
  19489. uv.y = sinTheta * 0.5 * sign + 0.5;
  19490. uvs.push(uv.x, uv.y); // increase index
  19491. index++;
  19492. } // generate indices
  19493. for (x = 0; x < radialSegments; x++) {
  19494. var c = centerIndexStart + x;
  19495. var i = centerIndexEnd + x;
  19496. if (top === true) {
  19497. // face top
  19498. indices.push(i, i + 1, c);
  19499. } else {
  19500. // face bottom
  19501. indices.push(i + 1, i, c);
  19502. }
  19503. groupCount += 3;
  19504. } // add a group to the geometry. this will ensure multi material support
  19505. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  19506. groupStart += groupCount;
  19507. }
  19508. }
  19509. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19510. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  19511. /**
  19512. * @author abelnation / http://github.com/abelnation
  19513. */
  19514. // ConeGeometry
  19515. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19516. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19517. this.type = 'ConeGeometry';
  19518. this.parameters = {
  19519. radius: radius,
  19520. height: height,
  19521. radialSegments: radialSegments,
  19522. heightSegments: heightSegments,
  19523. openEnded: openEnded,
  19524. thetaStart: thetaStart,
  19525. thetaLength: thetaLength
  19526. };
  19527. }
  19528. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  19529. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  19530. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19531. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19532. this.type = 'ConeBufferGeometry';
  19533. this.parameters = {
  19534. radius: radius,
  19535. height: height,
  19536. radialSegments: radialSegments,
  19537. heightSegments: heightSegments,
  19538. openEnded: openEnded,
  19539. thetaStart: thetaStart,
  19540. thetaLength: thetaLength
  19541. };
  19542. }
  19543. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  19544. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  19545. /**
  19546. * @author benaadams / https://twitter.com/ben_a_adams
  19547. * @author Mugen87 / https://github.com/Mugen87
  19548. * @author hughes
  19549. */
  19550. // CircleGeometry
  19551. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  19552. Geometry.call(this);
  19553. this.type = 'CircleGeometry';
  19554. this.parameters = {
  19555. radius: radius,
  19556. segments: segments,
  19557. thetaStart: thetaStart,
  19558. thetaLength: thetaLength
  19559. };
  19560. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  19561. this.mergeVertices();
  19562. }
  19563. CircleGeometry.prototype = Object.create(Geometry.prototype);
  19564. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  19565. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  19566. BufferGeometry.call(this);
  19567. this.type = 'CircleBufferGeometry';
  19568. this.parameters = {
  19569. radius: radius,
  19570. segments: segments,
  19571. thetaStart: thetaStart,
  19572. thetaLength: thetaLength
  19573. };
  19574. radius = radius || 1;
  19575. segments = segments !== undefined ? Math.max(3, segments) : 8;
  19576. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19577. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  19578. var indices = [];
  19579. var vertices = [];
  19580. var normals = [];
  19581. var uvs = []; // helper variables
  19582. var i, s;
  19583. var vertex = new Vector3();
  19584. var uv = new Vector2(); // center point
  19585. vertices.push(0, 0, 0);
  19586. normals.push(0, 0, 1);
  19587. uvs.push(0.5, 0.5);
  19588. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  19589. var segment = thetaStart + s / segments * thetaLength; // vertex
  19590. vertex.x = radius * Math.cos(segment);
  19591. vertex.y = radius * Math.sin(segment);
  19592. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19593. normals.push(0, 0, 1); // uvs
  19594. uv.x = (vertices[i] / radius + 1) / 2;
  19595. uv.y = (vertices[i + 1] / radius + 1) / 2;
  19596. uvs.push(uv.x, uv.y);
  19597. } // indices
  19598. for (i = 1; i <= segments; i++) {
  19599. indices.push(i, i + 1, 0);
  19600. } // build geometry
  19601. this.setIndex(indices);
  19602. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19603. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19604. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19605. }
  19606. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19607. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  19608. var Geometries =
  19609. /*#__PURE__*/
  19610. Object.freeze({
  19611. __proto__: null,
  19612. WireframeGeometry: WireframeGeometry,
  19613. ParametricGeometry: ParametricGeometry,
  19614. ParametricBufferGeometry: ParametricBufferGeometry,
  19615. TetrahedronGeometry: TetrahedronGeometry,
  19616. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  19617. OctahedronGeometry: OctahedronGeometry,
  19618. OctahedronBufferGeometry: OctahedronBufferGeometry,
  19619. IcosahedronGeometry: IcosahedronGeometry,
  19620. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  19621. DodecahedronGeometry: DodecahedronGeometry,
  19622. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  19623. PolyhedronGeometry: PolyhedronGeometry,
  19624. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  19625. TubeGeometry: TubeGeometry,
  19626. TubeBufferGeometry: TubeBufferGeometry,
  19627. TorusKnotGeometry: TorusKnotGeometry,
  19628. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  19629. TorusGeometry: TorusGeometry,
  19630. TorusBufferGeometry: TorusBufferGeometry,
  19631. TextGeometry: TextGeometry,
  19632. TextBufferGeometry: TextBufferGeometry,
  19633. SphereGeometry: SphereGeometry,
  19634. SphereBufferGeometry: SphereBufferGeometry,
  19635. RingGeometry: RingGeometry,
  19636. RingBufferGeometry: RingBufferGeometry,
  19637. PlaneGeometry: PlaneGeometry,
  19638. PlaneBufferGeometry: PlaneBufferGeometry,
  19639. LatheGeometry: LatheGeometry,
  19640. LatheBufferGeometry: LatheBufferGeometry,
  19641. ShapeGeometry: ShapeGeometry,
  19642. ShapeBufferGeometry: ShapeBufferGeometry,
  19643. ExtrudeGeometry: ExtrudeGeometry,
  19644. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  19645. EdgesGeometry: EdgesGeometry,
  19646. ConeGeometry: ConeGeometry,
  19647. ConeBufferGeometry: ConeBufferGeometry,
  19648. CylinderGeometry: CylinderGeometry,
  19649. CylinderBufferGeometry: CylinderBufferGeometry,
  19650. CircleGeometry: CircleGeometry,
  19651. CircleBufferGeometry: CircleBufferGeometry,
  19652. BoxGeometry: BoxGeometry,
  19653. BoxBufferGeometry: BoxBufferGeometry
  19654. });
  19655. /**
  19656. * @author mrdoob / http://mrdoob.com/
  19657. *
  19658. * parameters = {
  19659. * color: <THREE.Color>
  19660. * }
  19661. */
  19662. function ShadowMaterial(parameters) {
  19663. Material.call(this);
  19664. this.type = 'ShadowMaterial';
  19665. this.color = new Color(0x000000);
  19666. this.transparent = true;
  19667. this.setValues(parameters);
  19668. }
  19669. ShadowMaterial.prototype = Object.create(Material.prototype);
  19670. ShadowMaterial.prototype.constructor = ShadowMaterial;
  19671. ShadowMaterial.prototype.isShadowMaterial = true;
  19672. ShadowMaterial.prototype.copy = function (source) {
  19673. Material.prototype.copy.call(this, source);
  19674. this.color.copy(source.color);
  19675. return this;
  19676. };
  19677. /**
  19678. * @author mrdoob / http://mrdoob.com/
  19679. */
  19680. function RawShaderMaterial(parameters) {
  19681. ShaderMaterial.call(this, parameters);
  19682. this.type = 'RawShaderMaterial';
  19683. }
  19684. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  19685. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  19686. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  19687. /**
  19688. * @author WestLangley / http://github.com/WestLangley
  19689. *
  19690. * parameters = {
  19691. * color: <hex>,
  19692. * roughness: <float>,
  19693. * metalness: <float>,
  19694. * opacity: <float>,
  19695. *
  19696. * map: new THREE.Texture( <Image> ),
  19697. *
  19698. * lightMap: new THREE.Texture( <Image> ),
  19699. * lightMapIntensity: <float>
  19700. *
  19701. * aoMap: new THREE.Texture( <Image> ),
  19702. * aoMapIntensity: <float>
  19703. *
  19704. * emissive: <hex>,
  19705. * emissiveIntensity: <float>
  19706. * emissiveMap: new THREE.Texture( <Image> ),
  19707. *
  19708. * bumpMap: new THREE.Texture( <Image> ),
  19709. * bumpScale: <float>,
  19710. *
  19711. * normalMap: new THREE.Texture( <Image> ),
  19712. * normalMapType: THREE.TangentSpaceNormalMap,
  19713. * normalScale: <Vector2>,
  19714. *
  19715. * displacementMap: new THREE.Texture( <Image> ),
  19716. * displacementScale: <float>,
  19717. * displacementBias: <float>,
  19718. *
  19719. * roughnessMap: new THREE.Texture( <Image> ),
  19720. *
  19721. * metalnessMap: new THREE.Texture( <Image> ),
  19722. *
  19723. * alphaMap: new THREE.Texture( <Image> ),
  19724. *
  19725. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19726. * envMapIntensity: <float>
  19727. *
  19728. * refractionRatio: <float>,
  19729. *
  19730. * wireframe: <boolean>,
  19731. * wireframeLinewidth: <float>,
  19732. *
  19733. * skinning: <bool>,
  19734. * morphTargets: <bool>,
  19735. * morphNormals: <bool>
  19736. * }
  19737. */
  19738. function MeshStandardMaterial(parameters) {
  19739. Material.call(this);
  19740. this.defines = {
  19741. 'STANDARD': ''
  19742. };
  19743. this.type = 'MeshStandardMaterial';
  19744. this.color = new Color(0xffffff); // diffuse
  19745. this.roughness = 1.0;
  19746. this.metalness = 0.0;
  19747. this.map = null;
  19748. this.lightMap = null;
  19749. this.lightMapIntensity = 1.0;
  19750. this.aoMap = null;
  19751. this.aoMapIntensity = 1.0;
  19752. this.emissive = new Color(0x000000);
  19753. this.emissiveIntensity = 1.0;
  19754. this.emissiveMap = null;
  19755. this.bumpMap = null;
  19756. this.bumpScale = 1;
  19757. this.normalMap = null;
  19758. this.normalMapType = TangentSpaceNormalMap;
  19759. this.normalScale = new Vector2(1, 1);
  19760. this.displacementMap = null;
  19761. this.displacementScale = 1;
  19762. this.displacementBias = 0;
  19763. this.roughnessMap = null;
  19764. this.metalnessMap = null;
  19765. this.alphaMap = null;
  19766. this.envMap = null;
  19767. this.envMapIntensity = 1.0;
  19768. this.refractionRatio = 0.98;
  19769. this.wireframe = false;
  19770. this.wireframeLinewidth = 1;
  19771. this.wireframeLinecap = 'round';
  19772. this.wireframeLinejoin = 'round';
  19773. this.skinning = false;
  19774. this.morphTargets = false;
  19775. this.morphNormals = false;
  19776. this.vertexTangents = false;
  19777. this.setValues(parameters);
  19778. }
  19779. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  19780. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  19781. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  19782. MeshStandardMaterial.prototype.copy = function (source) {
  19783. Material.prototype.copy.call(this, source);
  19784. this.defines = {
  19785. 'STANDARD': ''
  19786. };
  19787. this.color.copy(source.color);
  19788. this.roughness = source.roughness;
  19789. this.metalness = source.metalness;
  19790. this.map = source.map;
  19791. this.lightMap = source.lightMap;
  19792. this.lightMapIntensity = source.lightMapIntensity;
  19793. this.aoMap = source.aoMap;
  19794. this.aoMapIntensity = source.aoMapIntensity;
  19795. this.emissive.copy(source.emissive);
  19796. this.emissiveMap = source.emissiveMap;
  19797. this.emissiveIntensity = source.emissiveIntensity;
  19798. this.bumpMap = source.bumpMap;
  19799. this.bumpScale = source.bumpScale;
  19800. this.normalMap = source.normalMap;
  19801. this.normalMapType = source.normalMapType;
  19802. this.normalScale.copy(source.normalScale);
  19803. this.displacementMap = source.displacementMap;
  19804. this.displacementScale = source.displacementScale;
  19805. this.displacementBias = source.displacementBias;
  19806. this.roughnessMap = source.roughnessMap;
  19807. this.metalnessMap = source.metalnessMap;
  19808. this.alphaMap = source.alphaMap;
  19809. this.envMap = source.envMap;
  19810. this.envMapIntensity = source.envMapIntensity;
  19811. this.refractionRatio = source.refractionRatio;
  19812. this.wireframe = source.wireframe;
  19813. this.wireframeLinewidth = source.wireframeLinewidth;
  19814. this.wireframeLinecap = source.wireframeLinecap;
  19815. this.wireframeLinejoin = source.wireframeLinejoin;
  19816. this.skinning = source.skinning;
  19817. this.morphTargets = source.morphTargets;
  19818. this.morphNormals = source.morphNormals;
  19819. this.vertexTangents = source.vertexTangents;
  19820. return this;
  19821. };
  19822. /**
  19823. * @author WestLangley / http://github.com/WestLangley
  19824. *
  19825. * parameters = {
  19826. * clearcoat: <float>,
  19827. * clearcoatMap: new THREE.Texture( <Image> ),
  19828. * clearcoatRoughness: <float>,
  19829. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  19830. * clearcoatNormalScale: <Vector2>,
  19831. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  19832. *
  19833. * reflectivity: <float>,
  19834. *
  19835. * sheen: <Color>,
  19836. *
  19837. * transparency: <float>
  19838. * }
  19839. */
  19840. function MeshPhysicalMaterial(parameters) {
  19841. MeshStandardMaterial.call(this);
  19842. this.defines = {
  19843. 'STANDARD': '',
  19844. 'PHYSICAL': ''
  19845. };
  19846. this.type = 'MeshPhysicalMaterial';
  19847. this.clearcoat = 0.0;
  19848. this.clearcoatMap = null;
  19849. this.clearcoatRoughness = 0.0;
  19850. this.clearcoatRoughnessMap = null;
  19851. this.clearcoatNormalScale = new Vector2(1, 1);
  19852. this.clearcoatNormalMap = null;
  19853. this.reflectivity = 0.5; // maps to F0 = 0.04
  19854. this.sheen = null; // null will disable sheen bsdf
  19855. this.transparency = 0.0;
  19856. this.setValues(parameters);
  19857. }
  19858. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  19859. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  19860. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  19861. MeshPhysicalMaterial.prototype.copy = function (source) {
  19862. MeshStandardMaterial.prototype.copy.call(this, source);
  19863. this.defines = {
  19864. 'STANDARD': '',
  19865. 'PHYSICAL': ''
  19866. };
  19867. this.clearcoat = source.clearcoat;
  19868. this.clearcoatMap = source.clearcoatMap;
  19869. this.clearcoatRoughness = source.clearcoatRoughness;
  19870. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  19871. this.clearcoatNormalMap = source.clearcoatNormalMap;
  19872. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  19873. this.reflectivity = source.reflectivity;
  19874. if (source.sheen) {
  19875. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  19876. } else {
  19877. this.sheen = null;
  19878. }
  19879. this.transparency = source.transparency;
  19880. return this;
  19881. };
  19882. /**
  19883. * @author mrdoob / http://mrdoob.com/
  19884. * @author alteredq / http://alteredqualia.com/
  19885. *
  19886. * parameters = {
  19887. * color: <hex>,
  19888. * specular: <hex>,
  19889. * shininess: <float>,
  19890. * opacity: <float>,
  19891. *
  19892. * map: new THREE.Texture( <Image> ),
  19893. *
  19894. * lightMap: new THREE.Texture( <Image> ),
  19895. * lightMapIntensity: <float>
  19896. *
  19897. * aoMap: new THREE.Texture( <Image> ),
  19898. * aoMapIntensity: <float>
  19899. *
  19900. * emissive: <hex>,
  19901. * emissiveIntensity: <float>
  19902. * emissiveMap: new THREE.Texture( <Image> ),
  19903. *
  19904. * bumpMap: new THREE.Texture( <Image> ),
  19905. * bumpScale: <float>,
  19906. *
  19907. * normalMap: new THREE.Texture( <Image> ),
  19908. * normalMapType: THREE.TangentSpaceNormalMap,
  19909. * normalScale: <Vector2>,
  19910. *
  19911. * displacementMap: new THREE.Texture( <Image> ),
  19912. * displacementScale: <float>,
  19913. * displacementBias: <float>,
  19914. *
  19915. * specularMap: new THREE.Texture( <Image> ),
  19916. *
  19917. * alphaMap: new THREE.Texture( <Image> ),
  19918. *
  19919. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19920. * combine: THREE.MultiplyOperation,
  19921. * reflectivity: <float>,
  19922. * refractionRatio: <float>,
  19923. *
  19924. * wireframe: <boolean>,
  19925. * wireframeLinewidth: <float>,
  19926. *
  19927. * skinning: <bool>,
  19928. * morphTargets: <bool>,
  19929. * morphNormals: <bool>
  19930. * }
  19931. */
  19932. function MeshPhongMaterial(parameters) {
  19933. Material.call(this);
  19934. this.type = 'MeshPhongMaterial';
  19935. this.color = new Color(0xffffff); // diffuse
  19936. this.specular = new Color(0x111111);
  19937. this.shininess = 30;
  19938. this.map = null;
  19939. this.lightMap = null;
  19940. this.lightMapIntensity = 1.0;
  19941. this.aoMap = null;
  19942. this.aoMapIntensity = 1.0;
  19943. this.emissive = new Color(0x000000);
  19944. this.emissiveIntensity = 1.0;
  19945. this.emissiveMap = null;
  19946. this.bumpMap = null;
  19947. this.bumpScale = 1;
  19948. this.normalMap = null;
  19949. this.normalMapType = TangentSpaceNormalMap;
  19950. this.normalScale = new Vector2(1, 1);
  19951. this.displacementMap = null;
  19952. this.displacementScale = 1;
  19953. this.displacementBias = 0;
  19954. this.specularMap = null;
  19955. this.alphaMap = null;
  19956. this.envMap = null;
  19957. this.combine = MultiplyOperation;
  19958. this.reflectivity = 1;
  19959. this.refractionRatio = 0.98;
  19960. this.wireframe = false;
  19961. this.wireframeLinewidth = 1;
  19962. this.wireframeLinecap = 'round';
  19963. this.wireframeLinejoin = 'round';
  19964. this.skinning = false;
  19965. this.morphTargets = false;
  19966. this.morphNormals = false;
  19967. this.setValues(parameters);
  19968. }
  19969. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  19970. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  19971. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19972. MeshPhongMaterial.prototype.copy = function (source) {
  19973. Material.prototype.copy.call(this, source);
  19974. this.color.copy(source.color);
  19975. this.specular.copy(source.specular);
  19976. this.shininess = source.shininess;
  19977. this.map = source.map;
  19978. this.lightMap = source.lightMap;
  19979. this.lightMapIntensity = source.lightMapIntensity;
  19980. this.aoMap = source.aoMap;
  19981. this.aoMapIntensity = source.aoMapIntensity;
  19982. this.emissive.copy(source.emissive);
  19983. this.emissiveMap = source.emissiveMap;
  19984. this.emissiveIntensity = source.emissiveIntensity;
  19985. this.bumpMap = source.bumpMap;
  19986. this.bumpScale = source.bumpScale;
  19987. this.normalMap = source.normalMap;
  19988. this.normalMapType = source.normalMapType;
  19989. this.normalScale.copy(source.normalScale);
  19990. this.displacementMap = source.displacementMap;
  19991. this.displacementScale = source.displacementScale;
  19992. this.displacementBias = source.displacementBias;
  19993. this.specularMap = source.specularMap;
  19994. this.alphaMap = source.alphaMap;
  19995. this.envMap = source.envMap;
  19996. this.combine = source.combine;
  19997. this.reflectivity = source.reflectivity;
  19998. this.refractionRatio = source.refractionRatio;
  19999. this.wireframe = source.wireframe;
  20000. this.wireframeLinewidth = source.wireframeLinewidth;
  20001. this.wireframeLinecap = source.wireframeLinecap;
  20002. this.wireframeLinejoin = source.wireframeLinejoin;
  20003. this.skinning = source.skinning;
  20004. this.morphTargets = source.morphTargets;
  20005. this.morphNormals = source.morphNormals;
  20006. return this;
  20007. };
  20008. /**
  20009. * @author takahirox / http://github.com/takahirox
  20010. *
  20011. * parameters = {
  20012. * color: <hex>,
  20013. * specular: <hex>,
  20014. * shininess: <float>,
  20015. *
  20016. * map: new THREE.Texture( <Image> ),
  20017. * gradientMap: new THREE.Texture( <Image> ),
  20018. *
  20019. * lightMap: new THREE.Texture( <Image> ),
  20020. * lightMapIntensity: <float>
  20021. *
  20022. * aoMap: new THREE.Texture( <Image> ),
  20023. * aoMapIntensity: <float>
  20024. *
  20025. * emissive: <hex>,
  20026. * emissiveIntensity: <float>
  20027. * emissiveMap: new THREE.Texture( <Image> ),
  20028. *
  20029. * bumpMap: new THREE.Texture( <Image> ),
  20030. * bumpScale: <float>,
  20031. *
  20032. * normalMap: new THREE.Texture( <Image> ),
  20033. * normalMapType: THREE.TangentSpaceNormalMap,
  20034. * normalScale: <Vector2>,
  20035. *
  20036. * displacementMap: new THREE.Texture( <Image> ),
  20037. * displacementScale: <float>,
  20038. * displacementBias: <float>,
  20039. *
  20040. * specularMap: new THREE.Texture( <Image> ),
  20041. *
  20042. * alphaMap: new THREE.Texture( <Image> ),
  20043. *
  20044. * wireframe: <boolean>,
  20045. * wireframeLinewidth: <float>,
  20046. *
  20047. * skinning: <bool>,
  20048. * morphTargets: <bool>,
  20049. * morphNormals: <bool>
  20050. * }
  20051. */
  20052. function MeshToonMaterial(parameters) {
  20053. Material.call(this);
  20054. this.defines = {
  20055. 'TOON': ''
  20056. };
  20057. this.type = 'MeshToonMaterial';
  20058. this.color = new Color(0xffffff);
  20059. this.specular = new Color(0x111111);
  20060. this.shininess = 30;
  20061. this.map = null;
  20062. this.gradientMap = null;
  20063. this.lightMap = null;
  20064. this.lightMapIntensity = 1.0;
  20065. this.aoMap = null;
  20066. this.aoMapIntensity = 1.0;
  20067. this.emissive = new Color(0x000000);
  20068. this.emissiveIntensity = 1.0;
  20069. this.emissiveMap = null;
  20070. this.bumpMap = null;
  20071. this.bumpScale = 1;
  20072. this.normalMap = null;
  20073. this.normalMapType = TangentSpaceNormalMap;
  20074. this.normalScale = new Vector2(1, 1);
  20075. this.displacementMap = null;
  20076. this.displacementScale = 1;
  20077. this.displacementBias = 0;
  20078. this.specularMap = null;
  20079. this.alphaMap = null;
  20080. this.wireframe = false;
  20081. this.wireframeLinewidth = 1;
  20082. this.wireframeLinecap = 'round';
  20083. this.wireframeLinejoin = 'round';
  20084. this.skinning = false;
  20085. this.morphTargets = false;
  20086. this.morphNormals = false;
  20087. this.setValues(parameters);
  20088. }
  20089. MeshToonMaterial.prototype = Object.create(Material.prototype);
  20090. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20091. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20092. MeshToonMaterial.prototype.copy = function (source) {
  20093. Material.prototype.copy.call(this, source);
  20094. this.color.copy(source.color);
  20095. this.specular.copy(source.specular);
  20096. this.shininess = source.shininess;
  20097. this.map = source.map;
  20098. this.gradientMap = source.gradientMap;
  20099. this.lightMap = source.lightMap;
  20100. this.lightMapIntensity = source.lightMapIntensity;
  20101. this.aoMap = source.aoMap;
  20102. this.aoMapIntensity = source.aoMapIntensity;
  20103. this.emissive.copy(source.emissive);
  20104. this.emissiveMap = source.emissiveMap;
  20105. this.emissiveIntensity = source.emissiveIntensity;
  20106. this.bumpMap = source.bumpMap;
  20107. this.bumpScale = source.bumpScale;
  20108. this.normalMap = source.normalMap;
  20109. this.normalMapType = source.normalMapType;
  20110. this.normalScale.copy(source.normalScale);
  20111. this.displacementMap = source.displacementMap;
  20112. this.displacementScale = source.displacementScale;
  20113. this.displacementBias = source.displacementBias;
  20114. this.specularMap = source.specularMap;
  20115. this.alphaMap = source.alphaMap;
  20116. this.wireframe = source.wireframe;
  20117. this.wireframeLinewidth = source.wireframeLinewidth;
  20118. this.wireframeLinecap = source.wireframeLinecap;
  20119. this.wireframeLinejoin = source.wireframeLinejoin;
  20120. this.skinning = source.skinning;
  20121. this.morphTargets = source.morphTargets;
  20122. this.morphNormals = source.morphNormals;
  20123. return this;
  20124. };
  20125. /**
  20126. * @author mrdoob / http://mrdoob.com/
  20127. * @author WestLangley / http://github.com/WestLangley
  20128. *
  20129. * parameters = {
  20130. * opacity: <float>,
  20131. *
  20132. * bumpMap: new THREE.Texture( <Image> ),
  20133. * bumpScale: <float>,
  20134. *
  20135. * normalMap: new THREE.Texture( <Image> ),
  20136. * normalMapType: THREE.TangentSpaceNormalMap,
  20137. * normalScale: <Vector2>,
  20138. *
  20139. * displacementMap: new THREE.Texture( <Image> ),
  20140. * displacementScale: <float>,
  20141. * displacementBias: <float>,
  20142. *
  20143. * wireframe: <boolean>,
  20144. * wireframeLinewidth: <float>
  20145. *
  20146. * skinning: <bool>,
  20147. * morphTargets: <bool>,
  20148. * morphNormals: <bool>
  20149. * }
  20150. */
  20151. function MeshNormalMaterial(parameters) {
  20152. Material.call(this);
  20153. this.type = 'MeshNormalMaterial';
  20154. this.bumpMap = null;
  20155. this.bumpScale = 1;
  20156. this.normalMap = null;
  20157. this.normalMapType = TangentSpaceNormalMap;
  20158. this.normalScale = new Vector2(1, 1);
  20159. this.displacementMap = null;
  20160. this.displacementScale = 1;
  20161. this.displacementBias = 0;
  20162. this.wireframe = false;
  20163. this.wireframeLinewidth = 1;
  20164. this.fog = false;
  20165. this.skinning = false;
  20166. this.morphTargets = false;
  20167. this.morphNormals = false;
  20168. this.setValues(parameters);
  20169. }
  20170. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20171. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20172. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20173. MeshNormalMaterial.prototype.copy = function (source) {
  20174. Material.prototype.copy.call(this, source);
  20175. this.bumpMap = source.bumpMap;
  20176. this.bumpScale = source.bumpScale;
  20177. this.normalMap = source.normalMap;
  20178. this.normalMapType = source.normalMapType;
  20179. this.normalScale.copy(source.normalScale);
  20180. this.displacementMap = source.displacementMap;
  20181. this.displacementScale = source.displacementScale;
  20182. this.displacementBias = source.displacementBias;
  20183. this.wireframe = source.wireframe;
  20184. this.wireframeLinewidth = source.wireframeLinewidth;
  20185. this.skinning = source.skinning;
  20186. this.morphTargets = source.morphTargets;
  20187. this.morphNormals = source.morphNormals;
  20188. return this;
  20189. };
  20190. /**
  20191. * @author mrdoob / http://mrdoob.com/
  20192. * @author alteredq / http://alteredqualia.com/
  20193. *
  20194. * parameters = {
  20195. * color: <hex>,
  20196. * opacity: <float>,
  20197. *
  20198. * map: new THREE.Texture( <Image> ),
  20199. *
  20200. * lightMap: new THREE.Texture( <Image> ),
  20201. * lightMapIntensity: <float>
  20202. *
  20203. * aoMap: new THREE.Texture( <Image> ),
  20204. * aoMapIntensity: <float>
  20205. *
  20206. * emissive: <hex>,
  20207. * emissiveIntensity: <float>
  20208. * emissiveMap: new THREE.Texture( <Image> ),
  20209. *
  20210. * specularMap: new THREE.Texture( <Image> ),
  20211. *
  20212. * alphaMap: new THREE.Texture( <Image> ),
  20213. *
  20214. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20215. * combine: THREE.Multiply,
  20216. * reflectivity: <float>,
  20217. * refractionRatio: <float>,
  20218. *
  20219. * wireframe: <boolean>,
  20220. * wireframeLinewidth: <float>,
  20221. *
  20222. * skinning: <bool>,
  20223. * morphTargets: <bool>,
  20224. * morphNormals: <bool>
  20225. * }
  20226. */
  20227. function MeshLambertMaterial(parameters) {
  20228. Material.call(this);
  20229. this.type = 'MeshLambertMaterial';
  20230. this.color = new Color(0xffffff); // diffuse
  20231. this.map = null;
  20232. this.lightMap = null;
  20233. this.lightMapIntensity = 1.0;
  20234. this.aoMap = null;
  20235. this.aoMapIntensity = 1.0;
  20236. this.emissive = new Color(0x000000);
  20237. this.emissiveIntensity = 1.0;
  20238. this.emissiveMap = null;
  20239. this.specularMap = null;
  20240. this.alphaMap = null;
  20241. this.envMap = null;
  20242. this.combine = MultiplyOperation;
  20243. this.reflectivity = 1;
  20244. this.refractionRatio = 0.98;
  20245. this.wireframe = false;
  20246. this.wireframeLinewidth = 1;
  20247. this.wireframeLinecap = 'round';
  20248. this.wireframeLinejoin = 'round';
  20249. this.skinning = false;
  20250. this.morphTargets = false;
  20251. this.morphNormals = false;
  20252. this.setValues(parameters);
  20253. }
  20254. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  20255. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  20256. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  20257. MeshLambertMaterial.prototype.copy = function (source) {
  20258. Material.prototype.copy.call(this, source);
  20259. this.color.copy(source.color);
  20260. this.map = source.map;
  20261. this.lightMap = source.lightMap;
  20262. this.lightMapIntensity = source.lightMapIntensity;
  20263. this.aoMap = source.aoMap;
  20264. this.aoMapIntensity = source.aoMapIntensity;
  20265. this.emissive.copy(source.emissive);
  20266. this.emissiveMap = source.emissiveMap;
  20267. this.emissiveIntensity = source.emissiveIntensity;
  20268. this.specularMap = source.specularMap;
  20269. this.alphaMap = source.alphaMap;
  20270. this.envMap = source.envMap;
  20271. this.combine = source.combine;
  20272. this.reflectivity = source.reflectivity;
  20273. this.refractionRatio = source.refractionRatio;
  20274. this.wireframe = source.wireframe;
  20275. this.wireframeLinewidth = source.wireframeLinewidth;
  20276. this.wireframeLinecap = source.wireframeLinecap;
  20277. this.wireframeLinejoin = source.wireframeLinejoin;
  20278. this.skinning = source.skinning;
  20279. this.morphTargets = source.morphTargets;
  20280. this.morphNormals = source.morphNormals;
  20281. return this;
  20282. };
  20283. /**
  20284. * @author WestLangley / http://github.com/WestLangley
  20285. *
  20286. * parameters = {
  20287. * color: <hex>,
  20288. * opacity: <float>,
  20289. *
  20290. * matcap: new THREE.Texture( <Image> ),
  20291. *
  20292. * map: new THREE.Texture( <Image> ),
  20293. *
  20294. * bumpMap: new THREE.Texture( <Image> ),
  20295. * bumpScale: <float>,
  20296. *
  20297. * normalMap: new THREE.Texture( <Image> ),
  20298. * normalMapType: THREE.TangentSpaceNormalMap,
  20299. * normalScale: <Vector2>,
  20300. *
  20301. * displacementMap: new THREE.Texture( <Image> ),
  20302. * displacementScale: <float>,
  20303. * displacementBias: <float>,
  20304. *
  20305. * alphaMap: new THREE.Texture( <Image> ),
  20306. *
  20307. * skinning: <bool>,
  20308. * morphTargets: <bool>,
  20309. * morphNormals: <bool>
  20310. * }
  20311. */
  20312. function MeshMatcapMaterial(parameters) {
  20313. Material.call(this);
  20314. this.defines = {
  20315. 'MATCAP': ''
  20316. };
  20317. this.type = 'MeshMatcapMaterial';
  20318. this.color = new Color(0xffffff); // diffuse
  20319. this.matcap = null;
  20320. this.map = null;
  20321. this.bumpMap = null;
  20322. this.bumpScale = 1;
  20323. this.normalMap = null;
  20324. this.normalMapType = TangentSpaceNormalMap;
  20325. this.normalScale = new Vector2(1, 1);
  20326. this.displacementMap = null;
  20327. this.displacementScale = 1;
  20328. this.displacementBias = 0;
  20329. this.alphaMap = null;
  20330. this.skinning = false;
  20331. this.morphTargets = false;
  20332. this.morphNormals = false;
  20333. this.setValues(parameters);
  20334. }
  20335. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  20336. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  20337. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20338. MeshMatcapMaterial.prototype.copy = function (source) {
  20339. Material.prototype.copy.call(this, source);
  20340. this.defines = {
  20341. 'MATCAP': ''
  20342. };
  20343. this.color.copy(source.color);
  20344. this.matcap = source.matcap;
  20345. this.map = source.map;
  20346. this.bumpMap = source.bumpMap;
  20347. this.bumpScale = source.bumpScale;
  20348. this.normalMap = source.normalMap;
  20349. this.normalMapType = source.normalMapType;
  20350. this.normalScale.copy(source.normalScale);
  20351. this.displacementMap = source.displacementMap;
  20352. this.displacementScale = source.displacementScale;
  20353. this.displacementBias = source.displacementBias;
  20354. this.alphaMap = source.alphaMap;
  20355. this.skinning = source.skinning;
  20356. this.morphTargets = source.morphTargets;
  20357. this.morphNormals = source.morphNormals;
  20358. return this;
  20359. };
  20360. /**
  20361. * @author alteredq / http://alteredqualia.com/
  20362. *
  20363. * parameters = {
  20364. * color: <hex>,
  20365. * opacity: <float>,
  20366. *
  20367. * linewidth: <float>,
  20368. *
  20369. * scale: <float>,
  20370. * dashSize: <float>,
  20371. * gapSize: <float>
  20372. * }
  20373. */
  20374. function LineDashedMaterial(parameters) {
  20375. LineBasicMaterial.call(this);
  20376. this.type = 'LineDashedMaterial';
  20377. this.scale = 1;
  20378. this.dashSize = 3;
  20379. this.gapSize = 1;
  20380. this.setValues(parameters);
  20381. }
  20382. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  20383. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  20384. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20385. LineDashedMaterial.prototype.copy = function (source) {
  20386. LineBasicMaterial.prototype.copy.call(this, source);
  20387. this.scale = source.scale;
  20388. this.dashSize = source.dashSize;
  20389. this.gapSize = source.gapSize;
  20390. return this;
  20391. };
  20392. var Materials =
  20393. /*#__PURE__*/
  20394. Object.freeze({
  20395. __proto__: null,
  20396. ShadowMaterial: ShadowMaterial,
  20397. SpriteMaterial: SpriteMaterial,
  20398. RawShaderMaterial: RawShaderMaterial,
  20399. ShaderMaterial: ShaderMaterial,
  20400. PointsMaterial: PointsMaterial,
  20401. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20402. MeshStandardMaterial: MeshStandardMaterial,
  20403. MeshPhongMaterial: MeshPhongMaterial,
  20404. MeshToonMaterial: MeshToonMaterial,
  20405. MeshNormalMaterial: MeshNormalMaterial,
  20406. MeshLambertMaterial: MeshLambertMaterial,
  20407. MeshDepthMaterial: MeshDepthMaterial,
  20408. MeshDistanceMaterial: MeshDistanceMaterial,
  20409. MeshBasicMaterial: MeshBasicMaterial,
  20410. MeshMatcapMaterial: MeshMatcapMaterial,
  20411. LineDashedMaterial: LineDashedMaterial,
  20412. LineBasicMaterial: LineBasicMaterial,
  20413. Material: Material
  20414. });
  20415. /**
  20416. * @author tschw
  20417. * @author Ben Houston / http://clara.io/
  20418. * @author David Sarno / http://lighthaus.us/
  20419. */
  20420. var AnimationUtils = {
  20421. // same as Array.prototype.slice, but also works on typed arrays
  20422. arraySlice: function (array, from, to) {
  20423. if (AnimationUtils.isTypedArray(array)) {
  20424. // in ios9 array.subarray(from, undefined) will return empty array
  20425. // but array.subarray(from) or array.subarray(from, len) is correct
  20426. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  20427. }
  20428. return array.slice(from, to);
  20429. },
  20430. // converts an array to a specific type
  20431. convertArray: function (array, type, forceClone) {
  20432. if (!array || // let 'undefined' and 'null' pass
  20433. !forceClone && array.constructor === type) return array;
  20434. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  20435. return new type(array); // create typed array
  20436. }
  20437. return Array.prototype.slice.call(array); // create Array
  20438. },
  20439. isTypedArray: function (object) {
  20440. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  20441. },
  20442. // returns an array by which times and values can be sorted
  20443. getKeyframeOrder: function (times) {
  20444. function compareTime(i, j) {
  20445. return times[i] - times[j];
  20446. }
  20447. var n = times.length;
  20448. var result = new Array(n);
  20449. for (var i = 0; i !== n; ++i) result[i] = i;
  20450. result.sort(compareTime);
  20451. return result;
  20452. },
  20453. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20454. sortedArray: function (values, stride, order) {
  20455. var nValues = values.length;
  20456. var result = new values.constructor(nValues);
  20457. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  20458. var srcOffset = order[i] * stride;
  20459. for (var j = 0; j !== stride; ++j) {
  20460. result[dstOffset++] = values[srcOffset + j];
  20461. }
  20462. }
  20463. return result;
  20464. },
  20465. // function for parsing AOS keyframe formats
  20466. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  20467. var i = 1,
  20468. key = jsonKeys[0];
  20469. while (key !== undefined && key[valuePropertyName] === undefined) {
  20470. key = jsonKeys[i++];
  20471. }
  20472. if (key === undefined) return; // no data
  20473. var value = key[valuePropertyName];
  20474. if (value === undefined) return; // no data
  20475. if (Array.isArray(value)) {
  20476. do {
  20477. value = key[valuePropertyName];
  20478. if (value !== undefined) {
  20479. times.push(key.time);
  20480. values.push.apply(values, value); // push all elements
  20481. }
  20482. key = jsonKeys[i++];
  20483. } while (key !== undefined);
  20484. } else if (value.toArray !== undefined) {
  20485. // ...assume THREE.Math-ish
  20486. do {
  20487. value = key[valuePropertyName];
  20488. if (value !== undefined) {
  20489. times.push(key.time);
  20490. value.toArray(values, values.length);
  20491. }
  20492. key = jsonKeys[i++];
  20493. } while (key !== undefined);
  20494. } else {
  20495. // otherwise push as-is
  20496. do {
  20497. value = key[valuePropertyName];
  20498. if (value !== undefined) {
  20499. times.push(key.time);
  20500. values.push(value);
  20501. }
  20502. key = jsonKeys[i++];
  20503. } while (key !== undefined);
  20504. }
  20505. },
  20506. subclip: function (sourceClip, name, startFrame, endFrame, fps) {
  20507. fps = fps || 30;
  20508. var clip = sourceClip.clone();
  20509. clip.name = name;
  20510. var tracks = [];
  20511. for (var i = 0; i < clip.tracks.length; ++i) {
  20512. var track = clip.tracks[i];
  20513. var valueSize = track.getValueSize();
  20514. var times = [];
  20515. var values = [];
  20516. for (var j = 0; j < track.times.length; ++j) {
  20517. var frame = track.times[j] * fps;
  20518. if (frame < startFrame || frame >= endFrame) continue;
  20519. times.push(track.times[j]);
  20520. for (var k = 0; k < valueSize; ++k) {
  20521. values.push(track.values[j * valueSize + k]);
  20522. }
  20523. }
  20524. if (times.length === 0) continue;
  20525. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  20526. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  20527. tracks.push(track);
  20528. }
  20529. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  20530. var minStartTime = Infinity;
  20531. for (var i = 0; i < clip.tracks.length; ++i) {
  20532. if (minStartTime > clip.tracks[i].times[0]) {
  20533. minStartTime = clip.tracks[i].times[0];
  20534. }
  20535. } // shift all tracks such that clip begins at t=0
  20536. for (var i = 0; i < clip.tracks.length; ++i) {
  20537. clip.tracks[i].shift(-1 * minStartTime);
  20538. }
  20539. clip.resetDuration();
  20540. return clip;
  20541. }
  20542. };
  20543. /**
  20544. * Abstract base class of interpolants over parametric samples.
  20545. *
  20546. * The parameter domain is one dimensional, typically the time or a path
  20547. * along a curve defined by the data.
  20548. *
  20549. * The sample values can have any dimensionality and derived classes may
  20550. * apply special interpretations to the data.
  20551. *
  20552. * This class provides the interval seek in a Template Method, deferring
  20553. * the actual interpolation to derived classes.
  20554. *
  20555. * Time complexity is O(1) for linear access crossing at most two points
  20556. * and O(log N) for random access, where N is the number of positions.
  20557. *
  20558. * References:
  20559. *
  20560. * http://www.oodesign.com/template-method-pattern.html
  20561. *
  20562. * @author tschw
  20563. */
  20564. exports.AnimationUtils = AnimationUtils;
  20565. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20566. this.parameterPositions = parameterPositions;
  20567. this._cachedIndex = 0;
  20568. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  20569. this.sampleValues = sampleValues;
  20570. this.valueSize = sampleSize;
  20571. }
  20572. Object.assign(Interpolant.prototype, {
  20573. evaluate: function (t) {
  20574. var pp = this.parameterPositions,
  20575. i1 = this._cachedIndex,
  20576. t1 = pp[i1],
  20577. t0 = pp[i1 - 1];
  20578. validate_interval: {
  20579. seek: {
  20580. var right;
  20581. linear_scan: {
  20582. //- See http://jsperf.com/comparison-to-undefined/3
  20583. //- slower code:
  20584. //-
  20585. //- if ( t >= t1 || t1 === undefined ) {
  20586. forward_scan: if (!(t < t1)) {
  20587. for (var giveUpAt = i1 + 2;;) {
  20588. if (t1 === undefined) {
  20589. if (t < t0) break forward_scan; // after end
  20590. i1 = pp.length;
  20591. this._cachedIndex = i1;
  20592. return this.afterEnd_(i1 - 1, t, t0);
  20593. }
  20594. if (i1 === giveUpAt) break; // this loop
  20595. t0 = t1;
  20596. t1 = pp[++i1];
  20597. if (t < t1) {
  20598. // we have arrived at the sought interval
  20599. break seek;
  20600. }
  20601. } // prepare binary search on the right side of the index
  20602. right = pp.length;
  20603. break linear_scan;
  20604. } //- slower code:
  20605. //- if ( t < t0 || t0 === undefined ) {
  20606. if (!(t >= t0)) {
  20607. // looping?
  20608. var t1global = pp[1];
  20609. if (t < t1global) {
  20610. i1 = 2; // + 1, using the scan for the details
  20611. t0 = t1global;
  20612. } // linear reverse scan
  20613. for (var giveUpAt = i1 - 2;;) {
  20614. if (t0 === undefined) {
  20615. // before start
  20616. this._cachedIndex = 0;
  20617. return this.beforeStart_(0, t, t1);
  20618. }
  20619. if (i1 === giveUpAt) break; // this loop
  20620. t1 = t0;
  20621. t0 = pp[--i1 - 1];
  20622. if (t >= t0) {
  20623. // we have arrived at the sought interval
  20624. break seek;
  20625. }
  20626. } // prepare binary search on the left side of the index
  20627. right = i1;
  20628. i1 = 0;
  20629. break linear_scan;
  20630. } // the interval is valid
  20631. break validate_interval;
  20632. } // linear scan
  20633. // binary search
  20634. while (i1 < right) {
  20635. var mid = i1 + right >>> 1;
  20636. if (t < pp[mid]) {
  20637. right = mid;
  20638. } else {
  20639. i1 = mid + 1;
  20640. }
  20641. }
  20642. t1 = pp[i1];
  20643. t0 = pp[i1 - 1]; // check boundary cases, again
  20644. if (t0 === undefined) {
  20645. this._cachedIndex = 0;
  20646. return this.beforeStart_(0, t, t1);
  20647. }
  20648. if (t1 === undefined) {
  20649. i1 = pp.length;
  20650. this._cachedIndex = i1;
  20651. return this.afterEnd_(i1 - 1, t0, t);
  20652. }
  20653. } // seek
  20654. this._cachedIndex = i1;
  20655. this.intervalChanged_(i1, t0, t1);
  20656. } // validate_interval
  20657. return this.interpolate_(i1, t0, t, t1);
  20658. },
  20659. settings: null,
  20660. // optional, subclass-specific settings structure
  20661. // Note: The indirection allows central control of many interpolants.
  20662. // --- Protected interface
  20663. DefaultSettings_: {},
  20664. getSettings_: function () {
  20665. return this.settings || this.DefaultSettings_;
  20666. },
  20667. copySampleValue_: function (index) {
  20668. // copies a sample value to the result buffer
  20669. var result = this.resultBuffer,
  20670. values = this.sampleValues,
  20671. stride = this.valueSize,
  20672. offset = index * stride;
  20673. for (var i = 0; i !== stride; ++i) {
  20674. result[i] = values[offset + i];
  20675. }
  20676. return result;
  20677. },
  20678. // Template methods for derived classes:
  20679. interpolate_: function ()
  20680. /* i1, t0, t, t1 */
  20681. {
  20682. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  20683. },
  20684. intervalChanged_: function ()
  20685. /* i1, t0, t1 */
  20686. {// empty
  20687. }
  20688. }); // DECLARE ALIAS AFTER assign prototype
  20689. Object.assign(Interpolant.prototype, {
  20690. //( 0, t, t0 ), returns this.resultBuffer
  20691. beforeStart_: Interpolant.prototype.copySampleValue_,
  20692. //( N-1, tN-1, t ), returns this.resultBuffer
  20693. afterEnd_: Interpolant.prototype.copySampleValue_
  20694. });
  20695. /**
  20696. * Fast and simple cubic spline interpolant.
  20697. *
  20698. * It was derived from a Hermitian construction setting the first derivative
  20699. * at each sample position to the linear slope between neighboring positions
  20700. * over their parameter interval.
  20701. *
  20702. * @author tschw
  20703. */
  20704. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20705. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20706. this._weightPrev = -0;
  20707. this._offsetPrev = -0;
  20708. this._weightNext = -0;
  20709. this._offsetNext = -0;
  20710. }
  20711. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20712. constructor: CubicInterpolant,
  20713. DefaultSettings_: {
  20714. endingStart: ZeroCurvatureEnding,
  20715. endingEnd: ZeroCurvatureEnding
  20716. },
  20717. intervalChanged_: function (i1, t0, t1) {
  20718. var pp = this.parameterPositions,
  20719. iPrev = i1 - 2,
  20720. iNext = i1 + 1,
  20721. tPrev = pp[iPrev],
  20722. tNext = pp[iNext];
  20723. if (tPrev === undefined) {
  20724. switch (this.getSettings_().endingStart) {
  20725. case ZeroSlopeEnding:
  20726. // f'(t0) = 0
  20727. iPrev = i1;
  20728. tPrev = 2 * t0 - t1;
  20729. break;
  20730. case WrapAroundEnding:
  20731. // use the other end of the curve
  20732. iPrev = pp.length - 2;
  20733. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  20734. break;
  20735. default:
  20736. // ZeroCurvatureEnding
  20737. // f''(t0) = 0 a.k.a. Natural Spline
  20738. iPrev = i1;
  20739. tPrev = t1;
  20740. }
  20741. }
  20742. if (tNext === undefined) {
  20743. switch (this.getSettings_().endingEnd) {
  20744. case ZeroSlopeEnding:
  20745. // f'(tN) = 0
  20746. iNext = i1;
  20747. tNext = 2 * t1 - t0;
  20748. break;
  20749. case WrapAroundEnding:
  20750. // use the other end of the curve
  20751. iNext = 1;
  20752. tNext = t1 + pp[1] - pp[0];
  20753. break;
  20754. default:
  20755. // ZeroCurvatureEnding
  20756. // f''(tN) = 0, a.k.a. Natural Spline
  20757. iNext = i1 - 1;
  20758. tNext = t0;
  20759. }
  20760. }
  20761. var halfDt = (t1 - t0) * 0.5,
  20762. stride = this.valueSize;
  20763. this._weightPrev = halfDt / (t0 - tPrev);
  20764. this._weightNext = halfDt / (tNext - t1);
  20765. this._offsetPrev = iPrev * stride;
  20766. this._offsetNext = iNext * stride;
  20767. },
  20768. interpolate_: function (i1, t0, t, t1) {
  20769. var result = this.resultBuffer,
  20770. values = this.sampleValues,
  20771. stride = this.valueSize,
  20772. o1 = i1 * stride,
  20773. o0 = o1 - stride,
  20774. oP = this._offsetPrev,
  20775. oN = this._offsetNext,
  20776. wP = this._weightPrev,
  20777. wN = this._weightNext,
  20778. p = (t - t0) / (t1 - t0),
  20779. pp = p * p,
  20780. ppp = pp * p; // evaluate polynomials
  20781. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  20782. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  20783. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  20784. var sN = wN * ppp - wN * pp; // combine data linearly
  20785. for (var i = 0; i !== stride; ++i) {
  20786. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  20787. }
  20788. return result;
  20789. }
  20790. });
  20791. /**
  20792. * @author tschw
  20793. */
  20794. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20795. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20796. }
  20797. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20798. constructor: LinearInterpolant,
  20799. interpolate_: function (i1, t0, t, t1) {
  20800. var result = this.resultBuffer,
  20801. values = this.sampleValues,
  20802. stride = this.valueSize,
  20803. offset1 = i1 * stride,
  20804. offset0 = offset1 - stride,
  20805. weight1 = (t - t0) / (t1 - t0),
  20806. weight0 = 1 - weight1;
  20807. for (var i = 0; i !== stride; ++i) {
  20808. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  20809. }
  20810. return result;
  20811. }
  20812. });
  20813. /**
  20814. *
  20815. * Interpolant that evaluates to the sample value at the position preceeding
  20816. * the parameter.
  20817. *
  20818. * @author tschw
  20819. */
  20820. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20821. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20822. }
  20823. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20824. constructor: DiscreteInterpolant,
  20825. interpolate_: function (i1
  20826. /*, t0, t, t1 */
  20827. ) {
  20828. return this.copySampleValue_(i1 - 1);
  20829. }
  20830. });
  20831. /**
  20832. *
  20833. * A timed sequence of keyframes for a specific property.
  20834. *
  20835. *
  20836. * @author Ben Houston / http://clara.io/
  20837. * @author David Sarno / http://lighthaus.us/
  20838. * @author tschw
  20839. */
  20840. function KeyframeTrack(name, times, values, interpolation) {
  20841. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  20842. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  20843. this.name = name;
  20844. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  20845. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  20846. this.setInterpolation(interpolation || this.DefaultInterpolation);
  20847. } // Static methods
  20848. Object.assign(KeyframeTrack, {
  20849. // Serialization (in static context, because of constructor invocation
  20850. // and automatic invocation of .toJSON):
  20851. toJSON: function (track) {
  20852. var trackType = track.constructor;
  20853. var json; // derived classes can define a static toJSON method
  20854. if (trackType.toJSON !== undefined) {
  20855. json = trackType.toJSON(track);
  20856. } else {
  20857. // by default, we assume the data can be serialized as-is
  20858. json = {
  20859. 'name': track.name,
  20860. 'times': AnimationUtils.convertArray(track.times, Array),
  20861. 'values': AnimationUtils.convertArray(track.values, Array)
  20862. };
  20863. var interpolation = track.getInterpolation();
  20864. if (interpolation !== track.DefaultInterpolation) {
  20865. json.interpolation = interpolation;
  20866. }
  20867. }
  20868. json.type = track.ValueTypeName; // mandatory
  20869. return json;
  20870. }
  20871. });
  20872. Object.assign(KeyframeTrack.prototype, {
  20873. constructor: KeyframeTrack,
  20874. TimeBufferType: Float32Array,
  20875. ValueBufferType: Float32Array,
  20876. DefaultInterpolation: InterpolateLinear,
  20877. InterpolantFactoryMethodDiscrete: function (result) {
  20878. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  20879. },
  20880. InterpolantFactoryMethodLinear: function (result) {
  20881. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20882. },
  20883. InterpolantFactoryMethodSmooth: function (result) {
  20884. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  20885. },
  20886. setInterpolation: function (interpolation) {
  20887. var factoryMethod;
  20888. switch (interpolation) {
  20889. case InterpolateDiscrete:
  20890. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  20891. break;
  20892. case InterpolateLinear:
  20893. factoryMethod = this.InterpolantFactoryMethodLinear;
  20894. break;
  20895. case InterpolateSmooth:
  20896. factoryMethod = this.InterpolantFactoryMethodSmooth;
  20897. break;
  20898. }
  20899. if (factoryMethod === undefined) {
  20900. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  20901. if (this.createInterpolant === undefined) {
  20902. // fall back to default, unless the default itself is messed up
  20903. if (interpolation !== this.DefaultInterpolation) {
  20904. this.setInterpolation(this.DefaultInterpolation);
  20905. } else {
  20906. throw new Error(message); // fatal, in this case
  20907. }
  20908. }
  20909. console.warn('THREE.KeyframeTrack:', message);
  20910. return this;
  20911. }
  20912. this.createInterpolant = factoryMethod;
  20913. return this;
  20914. },
  20915. getInterpolation: function () {
  20916. switch (this.createInterpolant) {
  20917. case this.InterpolantFactoryMethodDiscrete:
  20918. return InterpolateDiscrete;
  20919. case this.InterpolantFactoryMethodLinear:
  20920. return InterpolateLinear;
  20921. case this.InterpolantFactoryMethodSmooth:
  20922. return InterpolateSmooth;
  20923. }
  20924. },
  20925. getValueSize: function () {
  20926. return this.values.length / this.times.length;
  20927. },
  20928. // move all keyframes either forwards or backwards in time
  20929. shift: function (timeOffset) {
  20930. if (timeOffset !== 0.0) {
  20931. var times = this.times;
  20932. for (var i = 0, n = times.length; i !== n; ++i) {
  20933. times[i] += timeOffset;
  20934. }
  20935. }
  20936. return this;
  20937. },
  20938. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  20939. scale: function (timeScale) {
  20940. if (timeScale !== 1.0) {
  20941. var times = this.times;
  20942. for (var i = 0, n = times.length; i !== n; ++i) {
  20943. times[i] *= timeScale;
  20944. }
  20945. }
  20946. return this;
  20947. },
  20948. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  20949. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  20950. trim: function (startTime, endTime) {
  20951. var times = this.times,
  20952. nKeys = times.length,
  20953. from = 0,
  20954. to = nKeys - 1;
  20955. while (from !== nKeys && times[from] < startTime) {
  20956. ++from;
  20957. }
  20958. while (to !== -1 && times[to] > endTime) {
  20959. --to;
  20960. }
  20961. ++to; // inclusive -> exclusive bound
  20962. if (from !== 0 || to !== nKeys) {
  20963. // empty tracks are forbidden, so keep at least one keyframe
  20964. if (from >= to) {
  20965. to = Math.max(to, 1);
  20966. from = to - 1;
  20967. }
  20968. var stride = this.getValueSize();
  20969. this.times = AnimationUtils.arraySlice(times, from, to);
  20970. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  20971. }
  20972. return this;
  20973. },
  20974. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  20975. validate: function () {
  20976. var valid = true;
  20977. var valueSize = this.getValueSize();
  20978. if (valueSize - Math.floor(valueSize) !== 0) {
  20979. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  20980. valid = false;
  20981. }
  20982. var times = this.times,
  20983. values = this.values,
  20984. nKeys = times.length;
  20985. if (nKeys === 0) {
  20986. console.error('THREE.KeyframeTrack: Track is empty.', this);
  20987. valid = false;
  20988. }
  20989. var prevTime = null;
  20990. for (var i = 0; i !== nKeys; i++) {
  20991. var currTime = times[i];
  20992. if (typeof currTime === 'number' && isNaN(currTime)) {
  20993. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  20994. valid = false;
  20995. break;
  20996. }
  20997. if (prevTime !== null && prevTime > currTime) {
  20998. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  20999. valid = false;
  21000. break;
  21001. }
  21002. prevTime = currTime;
  21003. }
  21004. if (values !== undefined) {
  21005. if (AnimationUtils.isTypedArray(values)) {
  21006. for (var i = 0, n = values.length; i !== n; ++i) {
  21007. var value = values[i];
  21008. if (isNaN(value)) {
  21009. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21010. valid = false;
  21011. break;
  21012. }
  21013. }
  21014. }
  21015. }
  21016. return valid;
  21017. },
  21018. // removes equivalent sequential keys as common in morph target sequences
  21019. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21020. optimize: function () {
  21021. // times or values may be shared with other tracks, so overwriting is unsafe
  21022. var times = AnimationUtils.arraySlice(this.times),
  21023. values = AnimationUtils.arraySlice(this.values),
  21024. stride = this.getValueSize(),
  21025. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21026. writeIndex = 1,
  21027. lastIndex = times.length - 1;
  21028. for (var i = 1; i < lastIndex; ++i) {
  21029. var keep = false;
  21030. var time = times[i];
  21031. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21032. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21033. if (!smoothInterpolation) {
  21034. // remove unnecessary keyframes same as their neighbors
  21035. var offset = i * stride,
  21036. offsetP = offset - stride,
  21037. offsetN = offset + stride;
  21038. for (var j = 0; j !== stride; ++j) {
  21039. var value = values[offset + j];
  21040. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21041. keep = true;
  21042. break;
  21043. }
  21044. }
  21045. } else {
  21046. keep = true;
  21047. }
  21048. } // in-place compaction
  21049. if (keep) {
  21050. if (i !== writeIndex) {
  21051. times[writeIndex] = times[i];
  21052. var readOffset = i * stride,
  21053. writeOffset = writeIndex * stride;
  21054. for (var j = 0; j !== stride; ++j) {
  21055. values[writeOffset + j] = values[readOffset + j];
  21056. }
  21057. }
  21058. ++writeIndex;
  21059. }
  21060. } // flush last keyframe (compaction looks ahead)
  21061. if (lastIndex > 0) {
  21062. times[writeIndex] = times[lastIndex];
  21063. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21064. values[writeOffset + j] = values[readOffset + j];
  21065. }
  21066. ++writeIndex;
  21067. }
  21068. if (writeIndex !== times.length) {
  21069. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21070. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21071. } else {
  21072. this.times = times;
  21073. this.values = values;
  21074. }
  21075. return this;
  21076. },
  21077. clone: function () {
  21078. var times = AnimationUtils.arraySlice(this.times, 0);
  21079. var values = AnimationUtils.arraySlice(this.values, 0);
  21080. var TypedKeyframeTrack = this.constructor;
  21081. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21082. track.createInterpolant = this.createInterpolant;
  21083. return track;
  21084. }
  21085. });
  21086. /**
  21087. *
  21088. * A Track of Boolean keyframe values.
  21089. *
  21090. *
  21091. * @author Ben Houston / http://clara.io/
  21092. * @author David Sarno / http://lighthaus.us/
  21093. * @author tschw
  21094. */
  21095. function BooleanKeyframeTrack(name, times, values) {
  21096. KeyframeTrack.call(this, name, times, values);
  21097. }
  21098. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21099. constructor: BooleanKeyframeTrack,
  21100. ValueTypeName: 'bool',
  21101. ValueBufferType: Array,
  21102. DefaultInterpolation: InterpolateDiscrete,
  21103. InterpolantFactoryMethodLinear: undefined,
  21104. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21105. // representation of a single value and a custom interpolant that
  21106. // computes "firstValue ^ isOdd( index )".
  21107. });
  21108. /**
  21109. *
  21110. * A Track of keyframe values that represent color.
  21111. *
  21112. *
  21113. * @author Ben Houston / http://clara.io/
  21114. * @author David Sarno / http://lighthaus.us/
  21115. * @author tschw
  21116. */
  21117. function ColorKeyframeTrack(name, times, values, interpolation) {
  21118. KeyframeTrack.call(this, name, times, values, interpolation);
  21119. }
  21120. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21121. constructor: ColorKeyframeTrack,
  21122. ValueTypeName: 'color' // ValueBufferType is inherited
  21123. // DefaultInterpolation is inherited
  21124. // Note: Very basic implementation and nothing special yet.
  21125. // However, this is the place for color space parameterization.
  21126. });
  21127. /**
  21128. *
  21129. * A Track of numeric keyframe values.
  21130. *
  21131. * @author Ben Houston / http://clara.io/
  21132. * @author David Sarno / http://lighthaus.us/
  21133. * @author tschw
  21134. */
  21135. function NumberKeyframeTrack(name, times, values, interpolation) {
  21136. KeyframeTrack.call(this, name, times, values, interpolation);
  21137. }
  21138. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21139. constructor: NumberKeyframeTrack,
  21140. ValueTypeName: 'number' // ValueBufferType is inherited
  21141. // DefaultInterpolation is inherited
  21142. });
  21143. /**
  21144. * Spherical linear unit quaternion interpolant.
  21145. *
  21146. * @author tschw
  21147. */
  21148. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21149. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21150. }
  21151. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21152. constructor: QuaternionLinearInterpolant,
  21153. interpolate_: function (i1, t0, t, t1) {
  21154. var result = this.resultBuffer,
  21155. values = this.sampleValues,
  21156. stride = this.valueSize,
  21157. offset = i1 * stride,
  21158. alpha = (t - t0) / (t1 - t0);
  21159. for (var end = offset + stride; offset !== end; offset += 4) {
  21160. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21161. }
  21162. return result;
  21163. }
  21164. });
  21165. /**
  21166. *
  21167. * A Track of quaternion keyframe values.
  21168. *
  21169. * @author Ben Houston / http://clara.io/
  21170. * @author David Sarno / http://lighthaus.us/
  21171. * @author tschw
  21172. */
  21173. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21174. KeyframeTrack.call(this, name, times, values, interpolation);
  21175. }
  21176. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21177. constructor: QuaternionKeyframeTrack,
  21178. ValueTypeName: 'quaternion',
  21179. // ValueBufferType is inherited
  21180. DefaultInterpolation: InterpolateLinear,
  21181. InterpolantFactoryMethodLinear: function (result) {
  21182. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21183. },
  21184. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21185. });
  21186. /**
  21187. *
  21188. * A Track that interpolates Strings
  21189. *
  21190. *
  21191. * @author Ben Houston / http://clara.io/
  21192. * @author David Sarno / http://lighthaus.us/
  21193. * @author tschw
  21194. */
  21195. function StringKeyframeTrack(name, times, values, interpolation) {
  21196. KeyframeTrack.call(this, name, times, values, interpolation);
  21197. }
  21198. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21199. constructor: StringKeyframeTrack,
  21200. ValueTypeName: 'string',
  21201. ValueBufferType: Array,
  21202. DefaultInterpolation: InterpolateDiscrete,
  21203. InterpolantFactoryMethodLinear: undefined,
  21204. InterpolantFactoryMethodSmooth: undefined
  21205. });
  21206. /**
  21207. *
  21208. * A Track of vectored keyframe values.
  21209. *
  21210. *
  21211. * @author Ben Houston / http://clara.io/
  21212. * @author David Sarno / http://lighthaus.us/
  21213. * @author tschw
  21214. */
  21215. function VectorKeyframeTrack(name, times, values, interpolation) {
  21216. KeyframeTrack.call(this, name, times, values, interpolation);
  21217. }
  21218. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21219. constructor: VectorKeyframeTrack,
  21220. ValueTypeName: 'vector' // ValueBufferType is inherited
  21221. // DefaultInterpolation is inherited
  21222. });
  21223. /**
  21224. *
  21225. * Reusable set of Tracks that represent an animation.
  21226. *
  21227. * @author Ben Houston / http://clara.io/
  21228. * @author David Sarno / http://lighthaus.us/
  21229. */
  21230. function AnimationClip(name, duration, tracks) {
  21231. this.name = name;
  21232. this.tracks = tracks;
  21233. this.duration = duration !== undefined ? duration : -1;
  21234. this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21235. if (this.duration < 0) {
  21236. this.resetDuration();
  21237. }
  21238. }
  21239. function getTrackTypeForValueTypeName(typeName) {
  21240. switch (typeName.toLowerCase()) {
  21241. case 'scalar':
  21242. case 'double':
  21243. case 'float':
  21244. case 'number':
  21245. case 'integer':
  21246. return NumberKeyframeTrack;
  21247. case 'vector':
  21248. case 'vector2':
  21249. case 'vector3':
  21250. case 'vector4':
  21251. return VectorKeyframeTrack;
  21252. case 'color':
  21253. return ColorKeyframeTrack;
  21254. case 'quaternion':
  21255. return QuaternionKeyframeTrack;
  21256. case 'bool':
  21257. case 'boolean':
  21258. return BooleanKeyframeTrack;
  21259. case 'string':
  21260. return StringKeyframeTrack;
  21261. }
  21262. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21263. }
  21264. function parseKeyframeTrack(json) {
  21265. if (json.type === undefined) {
  21266. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  21267. }
  21268. var trackType = getTrackTypeForValueTypeName(json.type);
  21269. if (json.times === undefined) {
  21270. var times = [],
  21271. values = [];
  21272. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  21273. json.times = times;
  21274. json.values = values;
  21275. } // derived classes can define a static parse method
  21276. if (trackType.parse !== undefined) {
  21277. return trackType.parse(json);
  21278. } else {
  21279. // by default, we assume a constructor compatible with the base
  21280. return new trackType(json.name, json.times, json.values, json.interpolation);
  21281. }
  21282. }
  21283. Object.assign(AnimationClip, {
  21284. parse: function (json) {
  21285. var tracks = [],
  21286. jsonTracks = json.tracks,
  21287. frameTime = 1.0 / (json.fps || 1.0);
  21288. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  21289. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  21290. }
  21291. return new AnimationClip(json.name, json.duration, tracks);
  21292. },
  21293. toJSON: function (clip) {
  21294. var tracks = [],
  21295. clipTracks = clip.tracks;
  21296. var json = {
  21297. 'name': clip.name,
  21298. 'duration': clip.duration,
  21299. 'tracks': tracks,
  21300. 'uuid': clip.uuid
  21301. };
  21302. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  21303. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  21304. }
  21305. return json;
  21306. },
  21307. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  21308. var numMorphTargets = morphTargetSequence.length;
  21309. var tracks = [];
  21310. for (var i = 0; i < numMorphTargets; i++) {
  21311. var times = [];
  21312. var values = [];
  21313. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  21314. values.push(0, 1, 0);
  21315. var order = AnimationUtils.getKeyframeOrder(times);
  21316. times = AnimationUtils.sortedArray(times, 1, order);
  21317. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  21318. // last frame as well for perfect loop.
  21319. if (!noLoop && times[0] === 0) {
  21320. times.push(numMorphTargets);
  21321. values.push(values[0]);
  21322. }
  21323. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  21324. }
  21325. return new AnimationClip(name, -1, tracks);
  21326. },
  21327. findByName: function (objectOrClipArray, name) {
  21328. var clipArray = objectOrClipArray;
  21329. if (!Array.isArray(objectOrClipArray)) {
  21330. var o = objectOrClipArray;
  21331. clipArray = o.geometry && o.geometry.animations || o.animations;
  21332. }
  21333. for (var i = 0; i < clipArray.length; i++) {
  21334. if (clipArray[i].name === name) {
  21335. return clipArray[i];
  21336. }
  21337. }
  21338. return null;
  21339. },
  21340. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  21341. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  21342. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21343. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  21344. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21345. for (var i = 0, il = morphTargets.length; i < il; i++) {
  21346. var morphTarget = morphTargets[i];
  21347. var parts = morphTarget.name.match(pattern);
  21348. if (parts && parts.length > 1) {
  21349. var name = parts[1];
  21350. var animationMorphTargets = animationToMorphTargets[name];
  21351. if (!animationMorphTargets) {
  21352. animationToMorphTargets[name] = animationMorphTargets = [];
  21353. }
  21354. animationMorphTargets.push(morphTarget);
  21355. }
  21356. }
  21357. var clips = [];
  21358. for (var name in animationToMorphTargets) {
  21359. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21360. }
  21361. return clips;
  21362. },
  21363. // parse the animation.hierarchy format
  21364. parseAnimation: function (animation, bones) {
  21365. if (!animation) {
  21366. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21367. return null;
  21368. }
  21369. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21370. // only return track if there are actually keys.
  21371. if (animationKeys.length !== 0) {
  21372. var times = [];
  21373. var values = [];
  21374. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21375. if (times.length !== 0) {
  21376. destTracks.push(new trackType(trackName, times, values));
  21377. }
  21378. }
  21379. };
  21380. var tracks = [];
  21381. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  21382. var duration = animation.length || -1;
  21383. var fps = animation.fps || 30;
  21384. var hierarchyTracks = animation.hierarchy || [];
  21385. for (var h = 0; h < hierarchyTracks.length; h++) {
  21386. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21387. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21388. if (animationKeys[0].morphTargets) {
  21389. // figure out all morph targets used in this track
  21390. var morphTargetNames = {};
  21391. for (var k = 0; k < animationKeys.length; k++) {
  21392. if (animationKeys[k].morphTargets) {
  21393. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  21394. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  21395. }
  21396. }
  21397. } // create a track for each morph target with all zero
  21398. // morphTargetInfluences except for the keys in which
  21399. // the morphTarget is named.
  21400. for (var morphTargetName in morphTargetNames) {
  21401. var times = [];
  21402. var values = [];
  21403. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  21404. var animationKey = animationKeys[k];
  21405. times.push(animationKey.time);
  21406. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  21407. }
  21408. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  21409. }
  21410. duration = morphTargetNames.length * (fps || 1.0);
  21411. } else {
  21412. // ...assume skeletal animation
  21413. var boneName = '.bones[' + bones[h].name + ']';
  21414. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  21415. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  21416. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  21417. }
  21418. }
  21419. if (tracks.length === 0) {
  21420. return null;
  21421. }
  21422. var clip = new AnimationClip(clipName, duration, tracks);
  21423. return clip;
  21424. }
  21425. });
  21426. Object.assign(AnimationClip.prototype, {
  21427. resetDuration: function () {
  21428. var tracks = this.tracks,
  21429. duration = 0;
  21430. for (var i = 0, n = tracks.length; i !== n; ++i) {
  21431. var track = this.tracks[i];
  21432. duration = Math.max(duration, track.times[track.times.length - 1]);
  21433. }
  21434. this.duration = duration;
  21435. return this;
  21436. },
  21437. trim: function () {
  21438. for (var i = 0; i < this.tracks.length; i++) {
  21439. this.tracks[i].trim(0, this.duration);
  21440. }
  21441. return this;
  21442. },
  21443. validate: function () {
  21444. var valid = true;
  21445. for (var i = 0; i < this.tracks.length; i++) {
  21446. valid = valid && this.tracks[i].validate();
  21447. }
  21448. return valid;
  21449. },
  21450. optimize: function () {
  21451. for (var i = 0; i < this.tracks.length; i++) {
  21452. this.tracks[i].optimize();
  21453. }
  21454. return this;
  21455. },
  21456. clone: function () {
  21457. var tracks = [];
  21458. for (var i = 0; i < this.tracks.length; i++) {
  21459. tracks.push(this.tracks[i].clone());
  21460. }
  21461. return new AnimationClip(this.name, this.duration, tracks);
  21462. }
  21463. });
  21464. /**
  21465. * @author mrdoob / http://mrdoob.com/
  21466. */
  21467. var Cache = {
  21468. enabled: false,
  21469. files: {},
  21470. add: function (key, file) {
  21471. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  21472. this.files[key] = file;
  21473. },
  21474. get: function (key) {
  21475. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  21476. return this.files[key];
  21477. },
  21478. remove: function (key) {
  21479. delete this.files[key];
  21480. },
  21481. clear: function () {
  21482. this.files = {};
  21483. }
  21484. };
  21485. /**
  21486. * @author mrdoob / http://mrdoob.com/
  21487. */
  21488. exports.Cache = Cache;
  21489. function LoadingManager(onLoad, onProgress, onError) {
  21490. var scope = this;
  21491. var isLoading = false;
  21492. var itemsLoaded = 0;
  21493. var itemsTotal = 0;
  21494. var urlModifier = undefined;
  21495. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  21496. // in the constructor
  21497. this.onStart = undefined;
  21498. this.onLoad = onLoad;
  21499. this.onProgress = onProgress;
  21500. this.onError = onError;
  21501. this.itemStart = function (url) {
  21502. itemsTotal++;
  21503. if (isLoading === false) {
  21504. if (scope.onStart !== undefined) {
  21505. scope.onStart(url, itemsLoaded, itemsTotal);
  21506. }
  21507. }
  21508. isLoading = true;
  21509. };
  21510. this.itemEnd = function (url) {
  21511. itemsLoaded++;
  21512. if (scope.onProgress !== undefined) {
  21513. scope.onProgress(url, itemsLoaded, itemsTotal);
  21514. }
  21515. if (itemsLoaded === itemsTotal) {
  21516. isLoading = false;
  21517. if (scope.onLoad !== undefined) {
  21518. scope.onLoad();
  21519. }
  21520. }
  21521. };
  21522. this.itemError = function (url) {
  21523. if (scope.onError !== undefined) {
  21524. scope.onError(url);
  21525. }
  21526. };
  21527. this.resolveURL = function (url) {
  21528. if (urlModifier) {
  21529. return urlModifier(url);
  21530. }
  21531. return url;
  21532. };
  21533. this.setURLModifier = function (transform) {
  21534. urlModifier = transform;
  21535. return this;
  21536. };
  21537. this.addHandler = function (regex, loader) {
  21538. handlers.push(regex, loader);
  21539. return this;
  21540. };
  21541. this.removeHandler = function (regex) {
  21542. var index = handlers.indexOf(regex);
  21543. if (index !== -1) {
  21544. handlers.splice(index, 2);
  21545. }
  21546. return this;
  21547. };
  21548. this.getHandler = function (file) {
  21549. for (var i = 0, l = handlers.length; i < l; i += 2) {
  21550. var regex = handlers[i];
  21551. var loader = handlers[i + 1];
  21552. if (regex.global) regex.lastIndex = 0; // see #17920
  21553. if (regex.test(file)) {
  21554. return loader;
  21555. }
  21556. }
  21557. return null;
  21558. };
  21559. }
  21560. var DefaultLoadingManager = new LoadingManager();
  21561. /**
  21562. * @author alteredq / http://alteredqualia.com/
  21563. */
  21564. exports.DefaultLoadingManager = DefaultLoadingManager;
  21565. function Loader(manager) {
  21566. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  21567. this.crossOrigin = 'anonymous';
  21568. this.path = '';
  21569. this.resourcePath = '';
  21570. }
  21571. Object.assign(Loader.prototype, {
  21572. load: function ()
  21573. /* url, onLoad, onProgress, onError */
  21574. {},
  21575. parse: function ()
  21576. /* data */
  21577. {},
  21578. setCrossOrigin: function (crossOrigin) {
  21579. this.crossOrigin = crossOrigin;
  21580. return this;
  21581. },
  21582. setPath: function (path) {
  21583. this.path = path;
  21584. return this;
  21585. },
  21586. setResourcePath: function (resourcePath) {
  21587. this.resourcePath = resourcePath;
  21588. return this;
  21589. }
  21590. });
  21591. /**
  21592. * @author mrdoob / http://mrdoob.com/
  21593. */
  21594. var loading = {};
  21595. function FileLoader(manager) {
  21596. Loader.call(this, manager);
  21597. }
  21598. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21599. constructor: FileLoader,
  21600. load: function (url, onLoad, onProgress, onError) {
  21601. if (url === undefined) url = '';
  21602. if (this.path !== undefined) url = this.path + url;
  21603. url = this.manager.resolveURL(url);
  21604. var scope = this;
  21605. var cached = Cache.get(url);
  21606. if (cached !== undefined) {
  21607. scope.manager.itemStart(url);
  21608. setTimeout(function () {
  21609. if (onLoad) onLoad(cached);
  21610. scope.manager.itemEnd(url);
  21611. }, 0);
  21612. return cached;
  21613. } // Check if request is duplicate
  21614. if (loading[url] !== undefined) {
  21615. loading[url].push({
  21616. onLoad: onLoad,
  21617. onProgress: onProgress,
  21618. onError: onError
  21619. });
  21620. return;
  21621. } // Check for data: URI
  21622. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21623. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21624. if (dataUriRegexResult) {
  21625. var mimeType = dataUriRegexResult[1];
  21626. var isBase64 = !!dataUriRegexResult[2];
  21627. var data = dataUriRegexResult[3];
  21628. data = decodeURIComponent(data);
  21629. if (isBase64) data = atob(data);
  21630. try {
  21631. var response;
  21632. var responseType = (this.responseType || '').toLowerCase();
  21633. switch (responseType) {
  21634. case 'arraybuffer':
  21635. case 'blob':
  21636. var view = new Uint8Array(data.length);
  21637. for (var i = 0; i < data.length; i++) {
  21638. view[i] = data.charCodeAt(i);
  21639. }
  21640. if (responseType === 'blob') {
  21641. response = new Blob([view.buffer], {
  21642. type: mimeType
  21643. });
  21644. } else {
  21645. response = view.buffer;
  21646. }
  21647. break;
  21648. case 'document':
  21649. var parser = new DOMParser();
  21650. response = parser.parseFromString(data, mimeType);
  21651. break;
  21652. case 'json':
  21653. response = JSON.parse(data);
  21654. break;
  21655. default:
  21656. // 'text' or other
  21657. response = data;
  21658. break;
  21659. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21660. setTimeout(function () {
  21661. if (onLoad) onLoad(response);
  21662. scope.manager.itemEnd(url);
  21663. }, 0);
  21664. } catch (error) {
  21665. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21666. setTimeout(function () {
  21667. if (onError) onError(error);
  21668. scope.manager.itemError(url);
  21669. scope.manager.itemEnd(url);
  21670. }, 0);
  21671. }
  21672. } else {
  21673. // Initialise array for duplicate requests
  21674. loading[url] = [];
  21675. loading[url].push({
  21676. onLoad: onLoad,
  21677. onProgress: onProgress,
  21678. onError: onError
  21679. });
  21680. var request = new XMLHttpRequest();
  21681. request.open('GET', url, true);
  21682. request.addEventListener('load', function (event) {
  21683. var response = this.response;
  21684. var callbacks = loading[url];
  21685. delete loading[url];
  21686. if (this.status === 200 || this.status === 0) {
  21687. // Some browsers return HTTP Status 0 when using non-http protocol
  21688. // e.g. 'file://' or 'data://'. Handle as success.
  21689. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
  21690. // error response bodies as proper responses to requests.
  21691. Cache.add(url, response);
  21692. for (var i = 0, il = callbacks.length; i < il; i++) {
  21693. var callback = callbacks[i];
  21694. if (callback.onLoad) callback.onLoad(response);
  21695. }
  21696. scope.manager.itemEnd(url);
  21697. } else {
  21698. for (var i = 0, il = callbacks.length; i < il; i++) {
  21699. var callback = callbacks[i];
  21700. if (callback.onError) callback.onError(event);
  21701. }
  21702. scope.manager.itemError(url);
  21703. scope.manager.itemEnd(url);
  21704. }
  21705. }, false);
  21706. request.addEventListener('progress', function (event) {
  21707. var callbacks = loading[url];
  21708. for (var i = 0, il = callbacks.length; i < il; i++) {
  21709. var callback = callbacks[i];
  21710. if (callback.onProgress) callback.onProgress(event);
  21711. }
  21712. }, false);
  21713. request.addEventListener('error', function (event) {
  21714. var callbacks = loading[url];
  21715. delete loading[url];
  21716. for (var i = 0, il = callbacks.length; i < il; i++) {
  21717. var callback = callbacks[i];
  21718. if (callback.onError) callback.onError(event);
  21719. }
  21720. scope.manager.itemError(url);
  21721. scope.manager.itemEnd(url);
  21722. }, false);
  21723. request.addEventListener('abort', function (event) {
  21724. var callbacks = loading[url];
  21725. delete loading[url];
  21726. for (var i = 0, il = callbacks.length; i < il; i++) {
  21727. var callback = callbacks[i];
  21728. if (callback.onError) callback.onError(event);
  21729. }
  21730. scope.manager.itemError(url);
  21731. scope.manager.itemEnd(url);
  21732. }, false);
  21733. if (this.responseType !== undefined) request.responseType = this.responseType;
  21734. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  21735. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  21736. for (var header in this.requestHeader) {
  21737. request.setRequestHeader(header, this.requestHeader[header]);
  21738. }
  21739. request.send(null);
  21740. }
  21741. scope.manager.itemStart(url);
  21742. return request;
  21743. },
  21744. setResponseType: function (value) {
  21745. this.responseType = value;
  21746. return this;
  21747. },
  21748. setWithCredentials: function (value) {
  21749. this.withCredentials = value;
  21750. return this;
  21751. },
  21752. setMimeType: function (value) {
  21753. this.mimeType = value;
  21754. return this;
  21755. },
  21756. setRequestHeader: function (value) {
  21757. this.requestHeader = value;
  21758. return this;
  21759. }
  21760. });
  21761. /**
  21762. * @author bhouston / http://clara.io/
  21763. */
  21764. function AnimationLoader(manager) {
  21765. Loader.call(this, manager);
  21766. }
  21767. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21768. constructor: AnimationLoader,
  21769. load: function (url, onLoad, onProgress, onError) {
  21770. var scope = this;
  21771. var loader = new FileLoader(scope.manager);
  21772. loader.setPath(scope.path);
  21773. loader.load(url, function (text) {
  21774. onLoad(scope.parse(JSON.parse(text)));
  21775. }, onProgress, onError);
  21776. },
  21777. parse: function (json) {
  21778. var animations = [];
  21779. for (var i = 0; i < json.length; i++) {
  21780. var clip = AnimationClip.parse(json[i]);
  21781. animations.push(clip);
  21782. }
  21783. return animations;
  21784. }
  21785. });
  21786. /**
  21787. * @author mrdoob / http://mrdoob.com/
  21788. *
  21789. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21790. *
  21791. * Sub classes have to implement the parse() method which will be used in load().
  21792. */
  21793. function CompressedTextureLoader(manager) {
  21794. Loader.call(this, manager);
  21795. }
  21796. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21797. constructor: CompressedTextureLoader,
  21798. load: function (url, onLoad, onProgress, onError) {
  21799. var scope = this;
  21800. var images = [];
  21801. var texture = new CompressedTexture();
  21802. texture.image = images;
  21803. var loader = new FileLoader(this.manager);
  21804. loader.setPath(this.path);
  21805. loader.setResponseType('arraybuffer');
  21806. function loadTexture(i) {
  21807. loader.load(url[i], function (buffer) {
  21808. var texDatas = scope.parse(buffer, true);
  21809. images[i] = {
  21810. width: texDatas.width,
  21811. height: texDatas.height,
  21812. format: texDatas.format,
  21813. mipmaps: texDatas.mipmaps
  21814. };
  21815. loaded += 1;
  21816. if (loaded === 6) {
  21817. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  21818. texture.format = texDatas.format;
  21819. texture.needsUpdate = true;
  21820. if (onLoad) onLoad(texture);
  21821. }
  21822. }, onProgress, onError);
  21823. }
  21824. if (Array.isArray(url)) {
  21825. var loaded = 0;
  21826. for (var i = 0, il = url.length; i < il; ++i) {
  21827. loadTexture(i);
  21828. }
  21829. } else {
  21830. // compressed cubemap texture stored in a single DDS file
  21831. loader.load(url, function (buffer) {
  21832. var texDatas = scope.parse(buffer, true);
  21833. if (texDatas.isCubemap) {
  21834. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  21835. for (var f = 0; f < faces; f++) {
  21836. images[f] = {
  21837. mipmaps: []
  21838. };
  21839. for (var i = 0; i < texDatas.mipmapCount; i++) {
  21840. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  21841. images[f].format = texDatas.format;
  21842. images[f].width = texDatas.width;
  21843. images[f].height = texDatas.height;
  21844. }
  21845. }
  21846. } else {
  21847. texture.image.width = texDatas.width;
  21848. texture.image.height = texDatas.height;
  21849. texture.mipmaps = texDatas.mipmaps;
  21850. }
  21851. if (texDatas.mipmapCount === 1) {
  21852. texture.minFilter = LinearFilter;
  21853. }
  21854. texture.format = texDatas.format;
  21855. texture.needsUpdate = true;
  21856. if (onLoad) onLoad(texture);
  21857. }, onProgress, onError);
  21858. }
  21859. return texture;
  21860. }
  21861. });
  21862. /**
  21863. * @author Nikos M. / https://github.com/foo123/
  21864. *
  21865. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  21866. *
  21867. * Sub classes have to implement the parse() method which will be used in load().
  21868. */
  21869. function DataTextureLoader(manager) {
  21870. Loader.call(this, manager);
  21871. }
  21872. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21873. constructor: DataTextureLoader,
  21874. load: function (url, onLoad, onProgress, onError) {
  21875. var scope = this;
  21876. var texture = new DataTexture();
  21877. var loader = new FileLoader(this.manager);
  21878. loader.setResponseType('arraybuffer');
  21879. loader.setPath(this.path);
  21880. loader.load(url, function (buffer) {
  21881. var texData = scope.parse(buffer);
  21882. if (!texData) return;
  21883. if (texData.image !== undefined) {
  21884. texture.image = texData.image;
  21885. } else if (texData.data !== undefined) {
  21886. texture.image.width = texData.width;
  21887. texture.image.height = texData.height;
  21888. texture.image.data = texData.data;
  21889. }
  21890. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  21891. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  21892. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  21893. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  21894. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  21895. if (texData.format !== undefined) {
  21896. texture.format = texData.format;
  21897. }
  21898. if (texData.type !== undefined) {
  21899. texture.type = texData.type;
  21900. }
  21901. if (texData.mipmaps !== undefined) {
  21902. texture.mipmaps = texData.mipmaps;
  21903. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  21904. }
  21905. if (texData.mipmapCount === 1) {
  21906. texture.minFilter = LinearFilter;
  21907. }
  21908. texture.needsUpdate = true;
  21909. if (onLoad) onLoad(texture, texData);
  21910. }, onProgress, onError);
  21911. return texture;
  21912. }
  21913. });
  21914. /**
  21915. * @author mrdoob / http://mrdoob.com/
  21916. */
  21917. function ImageLoader(manager) {
  21918. Loader.call(this, manager);
  21919. }
  21920. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21921. constructor: ImageLoader,
  21922. load: function (url, onLoad, onProgress, onError) {
  21923. if (this.path !== undefined) url = this.path + url;
  21924. url = this.manager.resolveURL(url);
  21925. var scope = this;
  21926. var cached = Cache.get(url);
  21927. if (cached !== undefined) {
  21928. scope.manager.itemStart(url);
  21929. setTimeout(function () {
  21930. if (onLoad) onLoad(cached);
  21931. scope.manager.itemEnd(url);
  21932. }, 0);
  21933. return cached;
  21934. }
  21935. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  21936. function onImageLoad() {
  21937. image.removeEventListener('load', onImageLoad, false);
  21938. image.removeEventListener('error', onImageError, false);
  21939. Cache.add(url, this);
  21940. if (onLoad) onLoad(this);
  21941. scope.manager.itemEnd(url);
  21942. }
  21943. function onImageError(event) {
  21944. image.removeEventListener('load', onImageLoad, false);
  21945. image.removeEventListener('error', onImageError, false);
  21946. if (onError) onError(event);
  21947. scope.manager.itemError(url);
  21948. scope.manager.itemEnd(url);
  21949. }
  21950. image.addEventListener('load', onImageLoad, false);
  21951. image.addEventListener('error', onImageError, false);
  21952. if (url.substr(0, 5) !== 'data:') {
  21953. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  21954. }
  21955. scope.manager.itemStart(url);
  21956. image.src = url;
  21957. return image;
  21958. }
  21959. });
  21960. /**
  21961. * @author mrdoob / http://mrdoob.com/
  21962. */
  21963. function CubeTextureLoader(manager) {
  21964. Loader.call(this, manager);
  21965. }
  21966. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21967. constructor: CubeTextureLoader,
  21968. load: function (urls, onLoad, onProgress, onError) {
  21969. var texture = new CubeTexture();
  21970. var loader = new ImageLoader(this.manager);
  21971. loader.setCrossOrigin(this.crossOrigin);
  21972. loader.setPath(this.path);
  21973. var loaded = 0;
  21974. function loadTexture(i) {
  21975. loader.load(urls[i], function (image) {
  21976. texture.images[i] = image;
  21977. loaded++;
  21978. if (loaded === 6) {
  21979. texture.needsUpdate = true;
  21980. if (onLoad) onLoad(texture);
  21981. }
  21982. }, undefined, onError);
  21983. }
  21984. for (var i = 0; i < urls.length; ++i) {
  21985. loadTexture(i);
  21986. }
  21987. return texture;
  21988. }
  21989. });
  21990. /**
  21991. * @author mrdoob / http://mrdoob.com/
  21992. */
  21993. function TextureLoader(manager) {
  21994. Loader.call(this, manager);
  21995. }
  21996. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21997. constructor: TextureLoader,
  21998. load: function (url, onLoad, onProgress, onError) {
  21999. var texture = new Texture();
  22000. var loader = new ImageLoader(this.manager);
  22001. loader.setCrossOrigin(this.crossOrigin);
  22002. loader.setPath(this.path);
  22003. loader.load(url, function (image) {
  22004. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22005. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22006. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22007. texture.needsUpdate = true;
  22008. if (onLoad !== undefined) {
  22009. onLoad(texture);
  22010. }
  22011. }, onProgress, onError);
  22012. return texture;
  22013. }
  22014. });
  22015. /**
  22016. * @author zz85 / http://www.lab4games.net/zz85/blog
  22017. * Extensible curve object
  22018. *
  22019. * Some common of curve methods:
  22020. * .getPoint( t, optionalTarget ), .getTangent( t )
  22021. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  22022. * .getPoints(), .getSpacedPoints()
  22023. * .getLength()
  22024. * .updateArcLengths()
  22025. *
  22026. * This following curves inherit from THREE.Curve:
  22027. *
  22028. * -- 2D curves --
  22029. * THREE.ArcCurve
  22030. * THREE.CubicBezierCurve
  22031. * THREE.EllipseCurve
  22032. * THREE.LineCurve
  22033. * THREE.QuadraticBezierCurve
  22034. * THREE.SplineCurve
  22035. *
  22036. * -- 3D curves --
  22037. * THREE.CatmullRomCurve3
  22038. * THREE.CubicBezierCurve3
  22039. * THREE.LineCurve3
  22040. * THREE.QuadraticBezierCurve3
  22041. *
  22042. * A series of curves can be represented as a THREE.CurvePath.
  22043. *
  22044. **/
  22045. /**************************************************************
  22046. * Abstract Curve base class
  22047. **************************************************************/
  22048. function Curve() {
  22049. this.type = 'Curve';
  22050. this.arcLengthDivisions = 200;
  22051. }
  22052. Object.assign(Curve.prototype, {
  22053. // Virtual base class method to overwrite and implement in subclasses
  22054. // - t [0 .. 1]
  22055. getPoint: function ()
  22056. /* t, optionalTarget */
  22057. {
  22058. console.warn('THREE.Curve: .getPoint() not implemented.');
  22059. return null;
  22060. },
  22061. // Get point at relative position in curve according to arc length
  22062. // - u [0 .. 1]
  22063. getPointAt: function (u, optionalTarget) {
  22064. var t = this.getUtoTmapping(u);
  22065. return this.getPoint(t, optionalTarget);
  22066. },
  22067. // Get sequence of points using getPoint( t )
  22068. getPoints: function (divisions) {
  22069. if (divisions === undefined) divisions = 5;
  22070. var points = [];
  22071. for (var d = 0; d <= divisions; d++) {
  22072. points.push(this.getPoint(d / divisions));
  22073. }
  22074. return points;
  22075. },
  22076. // Get sequence of points using getPointAt( u )
  22077. getSpacedPoints: function (divisions) {
  22078. if (divisions === undefined) divisions = 5;
  22079. var points = [];
  22080. for (var d = 0; d <= divisions; d++) {
  22081. points.push(this.getPointAt(d / divisions));
  22082. }
  22083. return points;
  22084. },
  22085. // Get total curve arc length
  22086. getLength: function () {
  22087. var lengths = this.getLengths();
  22088. return lengths[lengths.length - 1];
  22089. },
  22090. // Get list of cumulative segment lengths
  22091. getLengths: function (divisions) {
  22092. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22093. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22094. return this.cacheArcLengths;
  22095. }
  22096. this.needsUpdate = false;
  22097. var cache = [];
  22098. var current,
  22099. last = this.getPoint(0);
  22100. var p,
  22101. sum = 0;
  22102. cache.push(0);
  22103. for (p = 1; p <= divisions; p++) {
  22104. current = this.getPoint(p / divisions);
  22105. sum += current.distanceTo(last);
  22106. cache.push(sum);
  22107. last = current;
  22108. }
  22109. this.cacheArcLengths = cache;
  22110. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22111. },
  22112. updateArcLengths: function () {
  22113. this.needsUpdate = true;
  22114. this.getLengths();
  22115. },
  22116. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22117. getUtoTmapping: function (u, distance) {
  22118. var arcLengths = this.getLengths();
  22119. var i = 0,
  22120. il = arcLengths.length;
  22121. var targetArcLength; // The targeted u distance value to get
  22122. if (distance) {
  22123. targetArcLength = distance;
  22124. } else {
  22125. targetArcLength = u * arcLengths[il - 1];
  22126. } // binary search for the index with largest value smaller than target u distance
  22127. var low = 0,
  22128. high = il - 1,
  22129. comparison;
  22130. while (low <= high) {
  22131. 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
  22132. comparison = arcLengths[i] - targetArcLength;
  22133. if (comparison < 0) {
  22134. low = i + 1;
  22135. } else if (comparison > 0) {
  22136. high = i - 1;
  22137. } else {
  22138. high = i;
  22139. break; // DONE
  22140. }
  22141. }
  22142. i = high;
  22143. if (arcLengths[i] === targetArcLength) {
  22144. return i / (il - 1);
  22145. } // we could get finer grain at lengths, or use simple interpolation between two points
  22146. var lengthBefore = arcLengths[i];
  22147. var lengthAfter = arcLengths[i + 1];
  22148. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22149. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22150. var t = (i + segmentFraction) / (il - 1);
  22151. return t;
  22152. },
  22153. // Returns a unit vector tangent at t
  22154. // In case any sub curve does not implement its tangent derivation,
  22155. // 2 points a small delta apart will be used to find its gradient
  22156. // which seems to give a reasonable approximation
  22157. getTangent: function (t) {
  22158. var delta = 0.0001;
  22159. var t1 = t - delta;
  22160. var t2 = t + delta; // Capping in case of danger
  22161. if (t1 < 0) t1 = 0;
  22162. if (t2 > 1) t2 = 1;
  22163. var pt1 = this.getPoint(t1);
  22164. var pt2 = this.getPoint(t2);
  22165. var vec = pt2.clone().sub(pt1);
  22166. return vec.normalize();
  22167. },
  22168. getTangentAt: function (u) {
  22169. var t = this.getUtoTmapping(u);
  22170. return this.getTangent(t);
  22171. },
  22172. computeFrenetFrames: function (segments, closed) {
  22173. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22174. var normal = new Vector3();
  22175. var tangents = [];
  22176. var normals = [];
  22177. var binormals = [];
  22178. var vec = new Vector3();
  22179. var mat = new Matrix4();
  22180. var i, u, theta; // compute the tangent vectors for each segment on the curve
  22181. for (i = 0; i <= segments; i++) {
  22182. u = i / segments;
  22183. tangents[i] = this.getTangentAt(u);
  22184. tangents[i].normalize();
  22185. } // select an initial normal vector perpendicular to the first tangent vector,
  22186. // and in the direction of the minimum tangent xyz component
  22187. normals[0] = new Vector3();
  22188. binormals[0] = new Vector3();
  22189. var min = Number.MAX_VALUE;
  22190. var tx = Math.abs(tangents[0].x);
  22191. var ty = Math.abs(tangents[0].y);
  22192. var tz = Math.abs(tangents[0].z);
  22193. if (tx <= min) {
  22194. min = tx;
  22195. normal.set(1, 0, 0);
  22196. }
  22197. if (ty <= min) {
  22198. min = ty;
  22199. normal.set(0, 1, 0);
  22200. }
  22201. if (tz <= min) {
  22202. normal.set(0, 0, 1);
  22203. }
  22204. vec.crossVectors(tangents[0], normal).normalize();
  22205. normals[0].crossVectors(tangents[0], vec);
  22206. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22207. for (i = 1; i <= segments; i++) {
  22208. normals[i] = normals[i - 1].clone();
  22209. binormals[i] = binormals[i - 1].clone();
  22210. vec.crossVectors(tangents[i - 1], tangents[i]);
  22211. if (vec.length() > Number.EPSILON) {
  22212. vec.normalize();
  22213. theta = Math.acos(MathUtils.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22214. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22215. }
  22216. binormals[i].crossVectors(tangents[i], normals[i]);
  22217. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22218. if (closed === true) {
  22219. theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
  22220. theta /= segments;
  22221. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22222. theta = -theta;
  22223. }
  22224. for (i = 1; i <= segments; i++) {
  22225. // twist a little...
  22226. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22227. binormals[i].crossVectors(tangents[i], normals[i]);
  22228. }
  22229. }
  22230. return {
  22231. tangents: tangents,
  22232. normals: normals,
  22233. binormals: binormals
  22234. };
  22235. },
  22236. clone: function () {
  22237. return new this.constructor().copy(this);
  22238. },
  22239. copy: function (source) {
  22240. this.arcLengthDivisions = source.arcLengthDivisions;
  22241. return this;
  22242. },
  22243. toJSON: function () {
  22244. var data = {
  22245. metadata: {
  22246. version: 4.5,
  22247. type: 'Curve',
  22248. generator: 'Curve.toJSON'
  22249. }
  22250. };
  22251. data.arcLengthDivisions = this.arcLengthDivisions;
  22252. data.type = this.type;
  22253. return data;
  22254. },
  22255. fromJSON: function (json) {
  22256. this.arcLengthDivisions = json.arcLengthDivisions;
  22257. return this;
  22258. }
  22259. });
  22260. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22261. Curve.call(this);
  22262. this.type = 'EllipseCurve';
  22263. this.aX = aX || 0;
  22264. this.aY = aY || 0;
  22265. this.xRadius = xRadius || 1;
  22266. this.yRadius = yRadius || 1;
  22267. this.aStartAngle = aStartAngle || 0;
  22268. this.aEndAngle = aEndAngle || 2 * Math.PI;
  22269. this.aClockwise = aClockwise || false;
  22270. this.aRotation = aRotation || 0;
  22271. }
  22272. EllipseCurve.prototype = Object.create(Curve.prototype);
  22273. EllipseCurve.prototype.constructor = EllipseCurve;
  22274. EllipseCurve.prototype.isEllipseCurve = true;
  22275. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  22276. var point = optionalTarget || new Vector2();
  22277. var twoPi = Math.PI * 2;
  22278. var deltaAngle = this.aEndAngle - this.aStartAngle;
  22279. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  22280. while (deltaAngle < 0) deltaAngle += twoPi;
  22281. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  22282. if (deltaAngle < Number.EPSILON) {
  22283. if (samePoints) {
  22284. deltaAngle = 0;
  22285. } else {
  22286. deltaAngle = twoPi;
  22287. }
  22288. }
  22289. if (this.aClockwise === true && !samePoints) {
  22290. if (deltaAngle === twoPi) {
  22291. deltaAngle = -twoPi;
  22292. } else {
  22293. deltaAngle = deltaAngle - twoPi;
  22294. }
  22295. }
  22296. var angle = this.aStartAngle + t * deltaAngle;
  22297. var x = this.aX + this.xRadius * Math.cos(angle);
  22298. var y = this.aY + this.yRadius * Math.sin(angle);
  22299. if (this.aRotation !== 0) {
  22300. var cos = Math.cos(this.aRotation);
  22301. var sin = Math.sin(this.aRotation);
  22302. var tx = x - this.aX;
  22303. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  22304. x = tx * cos - ty * sin + this.aX;
  22305. y = tx * sin + ty * cos + this.aY;
  22306. }
  22307. return point.set(x, y);
  22308. };
  22309. EllipseCurve.prototype.copy = function (source) {
  22310. Curve.prototype.copy.call(this, source);
  22311. this.aX = source.aX;
  22312. this.aY = source.aY;
  22313. this.xRadius = source.xRadius;
  22314. this.yRadius = source.yRadius;
  22315. this.aStartAngle = source.aStartAngle;
  22316. this.aEndAngle = source.aEndAngle;
  22317. this.aClockwise = source.aClockwise;
  22318. this.aRotation = source.aRotation;
  22319. return this;
  22320. };
  22321. EllipseCurve.prototype.toJSON = function () {
  22322. var data = Curve.prototype.toJSON.call(this);
  22323. data.aX = this.aX;
  22324. data.aY = this.aY;
  22325. data.xRadius = this.xRadius;
  22326. data.yRadius = this.yRadius;
  22327. data.aStartAngle = this.aStartAngle;
  22328. data.aEndAngle = this.aEndAngle;
  22329. data.aClockwise = this.aClockwise;
  22330. data.aRotation = this.aRotation;
  22331. return data;
  22332. };
  22333. EllipseCurve.prototype.fromJSON = function (json) {
  22334. Curve.prototype.fromJSON.call(this, json);
  22335. this.aX = json.aX;
  22336. this.aY = json.aY;
  22337. this.xRadius = json.xRadius;
  22338. this.yRadius = json.yRadius;
  22339. this.aStartAngle = json.aStartAngle;
  22340. this.aEndAngle = json.aEndAngle;
  22341. this.aClockwise = json.aClockwise;
  22342. this.aRotation = json.aRotation;
  22343. return this;
  22344. };
  22345. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22346. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22347. this.type = 'ArcCurve';
  22348. }
  22349. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  22350. ArcCurve.prototype.constructor = ArcCurve;
  22351. ArcCurve.prototype.isArcCurve = true;
  22352. /**
  22353. * @author zz85 https://github.com/zz85
  22354. *
  22355. * Centripetal CatmullRom Curve - which is useful for avoiding
  22356. * cusps and self-intersections in non-uniform catmull rom curves.
  22357. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22358. *
  22359. * curve.type accepts centripetal(default), chordal and catmullrom
  22360. * curve.tension is used for catmullrom which defaults to 0.5
  22361. */
  22362. /*
  22363. Based on an optimized c++ solution in
  22364. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22365. - http://ideone.com/NoEbVM
  22366. This CubicPoly class could be used for reusing some variables and calculations,
  22367. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22368. which can be placed in CurveUtils.
  22369. */
  22370. function CubicPoly() {
  22371. var c0 = 0,
  22372. c1 = 0,
  22373. c2 = 0,
  22374. c3 = 0;
  22375. /*
  22376. * Compute coefficients for a cubic polynomial
  22377. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22378. * such that
  22379. * p(0) = x0, p(1) = x1
  22380. * and
  22381. * p'(0) = t0, p'(1) = t1.
  22382. */
  22383. function init(x0, x1, t0, t1) {
  22384. c0 = x0;
  22385. c1 = t0;
  22386. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  22387. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22388. }
  22389. return {
  22390. initCatmullRom: function (x0, x1, x2, x3, tension) {
  22391. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  22392. },
  22393. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  22394. // compute tangents when parameterized in [t1,t2]
  22395. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  22396. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  22397. t1 *= dt1;
  22398. t2 *= dt1;
  22399. init(x1, x2, t1, t2);
  22400. },
  22401. calc: function (t) {
  22402. var t2 = t * t;
  22403. var t3 = t2 * t;
  22404. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22405. }
  22406. };
  22407. } //
  22408. var tmp = new Vector3();
  22409. var px = new CubicPoly(),
  22410. py = new CubicPoly(),
  22411. pz = new CubicPoly();
  22412. function CatmullRomCurve3(points, closed, curveType, tension) {
  22413. Curve.call(this);
  22414. this.type = 'CatmullRomCurve3';
  22415. this.points = points || [];
  22416. this.closed = closed || false;
  22417. this.curveType = curveType || 'centripetal';
  22418. this.tension = tension || 0.5;
  22419. }
  22420. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  22421. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  22422. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  22423. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  22424. var point = optionalTarget || new Vector3();
  22425. var points = this.points;
  22426. var l = points.length;
  22427. var p = (l - (this.closed ? 0 : 1)) * t;
  22428. var intPoint = Math.floor(p);
  22429. var weight = p - intPoint;
  22430. if (this.closed) {
  22431. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  22432. } else if (weight === 0 && intPoint === l - 1) {
  22433. intPoint = l - 2;
  22434. weight = 1;
  22435. }
  22436. var p0, p1, p2, p3; // 4 points
  22437. if (this.closed || intPoint > 0) {
  22438. p0 = points[(intPoint - 1) % l];
  22439. } else {
  22440. // extrapolate first point
  22441. tmp.subVectors(points[0], points[1]).add(points[0]);
  22442. p0 = tmp;
  22443. }
  22444. p1 = points[intPoint % l];
  22445. p2 = points[(intPoint + 1) % l];
  22446. if (this.closed || intPoint + 2 < l) {
  22447. p3 = points[(intPoint + 2) % l];
  22448. } else {
  22449. // extrapolate last point
  22450. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  22451. p3 = tmp;
  22452. }
  22453. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  22454. // init Centripetal / Chordal Catmull-Rom
  22455. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22456. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  22457. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  22458. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  22459. if (dt1 < 1e-4) dt1 = 1.0;
  22460. if (dt0 < 1e-4) dt0 = dt1;
  22461. if (dt2 < 1e-4) dt2 = dt1;
  22462. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  22463. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  22464. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  22465. } else if (this.curveType === 'catmullrom') {
  22466. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  22467. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  22468. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  22469. }
  22470. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  22471. return point;
  22472. };
  22473. CatmullRomCurve3.prototype.copy = function (source) {
  22474. Curve.prototype.copy.call(this, source);
  22475. this.points = [];
  22476. for (var i = 0, l = source.points.length; i < l; i++) {
  22477. var point = source.points[i];
  22478. this.points.push(point.clone());
  22479. }
  22480. this.closed = source.closed;
  22481. this.curveType = source.curveType;
  22482. this.tension = source.tension;
  22483. return this;
  22484. };
  22485. CatmullRomCurve3.prototype.toJSON = function () {
  22486. var data = Curve.prototype.toJSON.call(this);
  22487. data.points = [];
  22488. for (var i = 0, l = this.points.length; i < l; i++) {
  22489. var point = this.points[i];
  22490. data.points.push(point.toArray());
  22491. }
  22492. data.closed = this.closed;
  22493. data.curveType = this.curveType;
  22494. data.tension = this.tension;
  22495. return data;
  22496. };
  22497. CatmullRomCurve3.prototype.fromJSON = function (json) {
  22498. Curve.prototype.fromJSON.call(this, json);
  22499. this.points = [];
  22500. for (var i = 0, l = json.points.length; i < l; i++) {
  22501. var point = json.points[i];
  22502. this.points.push(new Vector3().fromArray(point));
  22503. }
  22504. this.closed = json.closed;
  22505. this.curveType = json.curveType;
  22506. this.tension = json.tension;
  22507. return this;
  22508. };
  22509. /**
  22510. * @author zz85 / http://www.lab4games.net/zz85/blog
  22511. *
  22512. * Bezier Curves formulas obtained from
  22513. * http://en.wikipedia.org/wiki/Bézier_curve
  22514. */
  22515. function CatmullRom(t, p0, p1, p2, p3) {
  22516. var v0 = (p2 - p0) * 0.5;
  22517. var v1 = (p3 - p1) * 0.5;
  22518. var t2 = t * t;
  22519. var t3 = t * t2;
  22520. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  22521. } //
  22522. function QuadraticBezierP0(t, p) {
  22523. var k = 1 - t;
  22524. return k * k * p;
  22525. }
  22526. function QuadraticBezierP1(t, p) {
  22527. return 2 * (1 - t) * t * p;
  22528. }
  22529. function QuadraticBezierP2(t, p) {
  22530. return t * t * p;
  22531. }
  22532. function QuadraticBezier(t, p0, p1, p2) {
  22533. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  22534. } //
  22535. function CubicBezierP0(t, p) {
  22536. var k = 1 - t;
  22537. return k * k * k * p;
  22538. }
  22539. function CubicBezierP1(t, p) {
  22540. var k = 1 - t;
  22541. return 3 * k * k * t * p;
  22542. }
  22543. function CubicBezierP2(t, p) {
  22544. return 3 * (1 - t) * t * t * p;
  22545. }
  22546. function CubicBezierP3(t, p) {
  22547. return t * t * t * p;
  22548. }
  22549. function CubicBezier(t, p0, p1, p2, p3) {
  22550. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  22551. }
  22552. function CubicBezierCurve(v0, v1, v2, v3) {
  22553. Curve.call(this);
  22554. this.type = 'CubicBezierCurve';
  22555. this.v0 = v0 || new Vector2();
  22556. this.v1 = v1 || new Vector2();
  22557. this.v2 = v2 || new Vector2();
  22558. this.v3 = v3 || new Vector2();
  22559. }
  22560. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  22561. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  22562. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  22563. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  22564. var point = optionalTarget || new Vector2();
  22565. var v0 = this.v0,
  22566. v1 = this.v1,
  22567. v2 = this.v2,
  22568. v3 = this.v3;
  22569. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  22570. return point;
  22571. };
  22572. CubicBezierCurve.prototype.copy = function (source) {
  22573. Curve.prototype.copy.call(this, source);
  22574. this.v0.copy(source.v0);
  22575. this.v1.copy(source.v1);
  22576. this.v2.copy(source.v2);
  22577. this.v3.copy(source.v3);
  22578. return this;
  22579. };
  22580. CubicBezierCurve.prototype.toJSON = function () {
  22581. var data = Curve.prototype.toJSON.call(this);
  22582. data.v0 = this.v0.toArray();
  22583. data.v1 = this.v1.toArray();
  22584. data.v2 = this.v2.toArray();
  22585. data.v3 = this.v3.toArray();
  22586. return data;
  22587. };
  22588. CubicBezierCurve.prototype.fromJSON = function (json) {
  22589. Curve.prototype.fromJSON.call(this, json);
  22590. this.v0.fromArray(json.v0);
  22591. this.v1.fromArray(json.v1);
  22592. this.v2.fromArray(json.v2);
  22593. this.v3.fromArray(json.v3);
  22594. return this;
  22595. };
  22596. function CubicBezierCurve3(v0, v1, v2, v3) {
  22597. Curve.call(this);
  22598. this.type = 'CubicBezierCurve3';
  22599. this.v0 = v0 || new Vector3();
  22600. this.v1 = v1 || new Vector3();
  22601. this.v2 = v2 || new Vector3();
  22602. this.v3 = v3 || new Vector3();
  22603. }
  22604. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  22605. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  22606. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  22607. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  22608. var point = optionalTarget || new Vector3();
  22609. var v0 = this.v0,
  22610. v1 = this.v1,
  22611. v2 = this.v2,
  22612. v3 = this.v3;
  22613. 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));
  22614. return point;
  22615. };
  22616. CubicBezierCurve3.prototype.copy = function (source) {
  22617. Curve.prototype.copy.call(this, source);
  22618. this.v0.copy(source.v0);
  22619. this.v1.copy(source.v1);
  22620. this.v2.copy(source.v2);
  22621. this.v3.copy(source.v3);
  22622. return this;
  22623. };
  22624. CubicBezierCurve3.prototype.toJSON = function () {
  22625. var data = Curve.prototype.toJSON.call(this);
  22626. data.v0 = this.v0.toArray();
  22627. data.v1 = this.v1.toArray();
  22628. data.v2 = this.v2.toArray();
  22629. data.v3 = this.v3.toArray();
  22630. return data;
  22631. };
  22632. CubicBezierCurve3.prototype.fromJSON = function (json) {
  22633. Curve.prototype.fromJSON.call(this, json);
  22634. this.v0.fromArray(json.v0);
  22635. this.v1.fromArray(json.v1);
  22636. this.v2.fromArray(json.v2);
  22637. this.v3.fromArray(json.v3);
  22638. return this;
  22639. };
  22640. function LineCurve(v1, v2) {
  22641. Curve.call(this);
  22642. this.type = 'LineCurve';
  22643. this.v1 = v1 || new Vector2();
  22644. this.v2 = v2 || new Vector2();
  22645. }
  22646. LineCurve.prototype = Object.create(Curve.prototype);
  22647. LineCurve.prototype.constructor = LineCurve;
  22648. LineCurve.prototype.isLineCurve = true;
  22649. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  22650. var point = optionalTarget || new Vector2();
  22651. if (t === 1) {
  22652. point.copy(this.v2);
  22653. } else {
  22654. point.copy(this.v2).sub(this.v1);
  22655. point.multiplyScalar(t).add(this.v1);
  22656. }
  22657. return point;
  22658. }; // Line curve is linear, so we can overwrite default getPointAt
  22659. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  22660. return this.getPoint(u, optionalTarget);
  22661. };
  22662. LineCurve.prototype.getTangent = function ()
  22663. /* t */
  22664. {
  22665. var tangent = this.v2.clone().sub(this.v1);
  22666. return tangent.normalize();
  22667. };
  22668. LineCurve.prototype.copy = function (source) {
  22669. Curve.prototype.copy.call(this, source);
  22670. this.v1.copy(source.v1);
  22671. this.v2.copy(source.v2);
  22672. return this;
  22673. };
  22674. LineCurve.prototype.toJSON = function () {
  22675. var data = Curve.prototype.toJSON.call(this);
  22676. data.v1 = this.v1.toArray();
  22677. data.v2 = this.v2.toArray();
  22678. return data;
  22679. };
  22680. LineCurve.prototype.fromJSON = function (json) {
  22681. Curve.prototype.fromJSON.call(this, json);
  22682. this.v1.fromArray(json.v1);
  22683. this.v2.fromArray(json.v2);
  22684. return this;
  22685. };
  22686. function LineCurve3(v1, v2) {
  22687. Curve.call(this);
  22688. this.type = 'LineCurve3';
  22689. this.v1 = v1 || new Vector3();
  22690. this.v2 = v2 || new Vector3();
  22691. }
  22692. LineCurve3.prototype = Object.create(Curve.prototype);
  22693. LineCurve3.prototype.constructor = LineCurve3;
  22694. LineCurve3.prototype.isLineCurve3 = true;
  22695. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  22696. var point = optionalTarget || new Vector3();
  22697. if (t === 1) {
  22698. point.copy(this.v2);
  22699. } else {
  22700. point.copy(this.v2).sub(this.v1);
  22701. point.multiplyScalar(t).add(this.v1);
  22702. }
  22703. return point;
  22704. }; // Line curve is linear, so we can overwrite default getPointAt
  22705. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  22706. return this.getPoint(u, optionalTarget);
  22707. };
  22708. LineCurve3.prototype.copy = function (source) {
  22709. Curve.prototype.copy.call(this, source);
  22710. this.v1.copy(source.v1);
  22711. this.v2.copy(source.v2);
  22712. return this;
  22713. };
  22714. LineCurve3.prototype.toJSON = function () {
  22715. var data = Curve.prototype.toJSON.call(this);
  22716. data.v1 = this.v1.toArray();
  22717. data.v2 = this.v2.toArray();
  22718. return data;
  22719. };
  22720. LineCurve3.prototype.fromJSON = function (json) {
  22721. Curve.prototype.fromJSON.call(this, json);
  22722. this.v1.fromArray(json.v1);
  22723. this.v2.fromArray(json.v2);
  22724. return this;
  22725. };
  22726. function QuadraticBezierCurve(v0, v1, v2) {
  22727. Curve.call(this);
  22728. this.type = 'QuadraticBezierCurve';
  22729. this.v0 = v0 || new Vector2();
  22730. this.v1 = v1 || new Vector2();
  22731. this.v2 = v2 || new Vector2();
  22732. }
  22733. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  22734. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  22735. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  22736. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  22737. var point = optionalTarget || new Vector2();
  22738. var v0 = this.v0,
  22739. v1 = this.v1,
  22740. v2 = this.v2;
  22741. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  22742. return point;
  22743. };
  22744. QuadraticBezierCurve.prototype.copy = function (source) {
  22745. Curve.prototype.copy.call(this, source);
  22746. this.v0.copy(source.v0);
  22747. this.v1.copy(source.v1);
  22748. this.v2.copy(source.v2);
  22749. return this;
  22750. };
  22751. QuadraticBezierCurve.prototype.toJSON = function () {
  22752. var data = Curve.prototype.toJSON.call(this);
  22753. data.v0 = this.v0.toArray();
  22754. data.v1 = this.v1.toArray();
  22755. data.v2 = this.v2.toArray();
  22756. return data;
  22757. };
  22758. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  22759. Curve.prototype.fromJSON.call(this, json);
  22760. this.v0.fromArray(json.v0);
  22761. this.v1.fromArray(json.v1);
  22762. this.v2.fromArray(json.v2);
  22763. return this;
  22764. };
  22765. function QuadraticBezierCurve3(v0, v1, v2) {
  22766. Curve.call(this);
  22767. this.type = 'QuadraticBezierCurve3';
  22768. this.v0 = v0 || new Vector3();
  22769. this.v1 = v1 || new Vector3();
  22770. this.v2 = v2 || new Vector3();
  22771. }
  22772. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  22773. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  22774. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  22775. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  22776. var point = optionalTarget || new Vector3();
  22777. var v0 = this.v0,
  22778. v1 = this.v1,
  22779. v2 = this.v2;
  22780. 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));
  22781. return point;
  22782. };
  22783. QuadraticBezierCurve3.prototype.copy = function (source) {
  22784. Curve.prototype.copy.call(this, source);
  22785. this.v0.copy(source.v0);
  22786. this.v1.copy(source.v1);
  22787. this.v2.copy(source.v2);
  22788. return this;
  22789. };
  22790. QuadraticBezierCurve3.prototype.toJSON = function () {
  22791. var data = Curve.prototype.toJSON.call(this);
  22792. data.v0 = this.v0.toArray();
  22793. data.v1 = this.v1.toArray();
  22794. data.v2 = this.v2.toArray();
  22795. return data;
  22796. };
  22797. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  22798. Curve.prototype.fromJSON.call(this, json);
  22799. this.v0.fromArray(json.v0);
  22800. this.v1.fromArray(json.v1);
  22801. this.v2.fromArray(json.v2);
  22802. return this;
  22803. };
  22804. function SplineCurve(points
  22805. /* array of Vector2 */
  22806. ) {
  22807. Curve.call(this);
  22808. this.type = 'SplineCurve';
  22809. this.points = points || [];
  22810. }
  22811. SplineCurve.prototype = Object.create(Curve.prototype);
  22812. SplineCurve.prototype.constructor = SplineCurve;
  22813. SplineCurve.prototype.isSplineCurve = true;
  22814. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  22815. var point = optionalTarget || new Vector2();
  22816. var points = this.points;
  22817. var p = (points.length - 1) * t;
  22818. var intPoint = Math.floor(p);
  22819. var weight = p - intPoint;
  22820. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  22821. var p1 = points[intPoint];
  22822. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  22823. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  22824. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  22825. return point;
  22826. };
  22827. SplineCurve.prototype.copy = function (source) {
  22828. Curve.prototype.copy.call(this, source);
  22829. this.points = [];
  22830. for (var i = 0, l = source.points.length; i < l; i++) {
  22831. var point = source.points[i];
  22832. this.points.push(point.clone());
  22833. }
  22834. return this;
  22835. };
  22836. SplineCurve.prototype.toJSON = function () {
  22837. var data = Curve.prototype.toJSON.call(this);
  22838. data.points = [];
  22839. for (var i = 0, l = this.points.length; i < l; i++) {
  22840. var point = this.points[i];
  22841. data.points.push(point.toArray());
  22842. }
  22843. return data;
  22844. };
  22845. SplineCurve.prototype.fromJSON = function (json) {
  22846. Curve.prototype.fromJSON.call(this, json);
  22847. this.points = [];
  22848. for (var i = 0, l = json.points.length; i < l; i++) {
  22849. var point = json.points[i];
  22850. this.points.push(new Vector2().fromArray(point));
  22851. }
  22852. return this;
  22853. };
  22854. var Curves =
  22855. /*#__PURE__*/
  22856. Object.freeze({
  22857. __proto__: null,
  22858. ArcCurve: ArcCurve,
  22859. CatmullRomCurve3: CatmullRomCurve3,
  22860. CubicBezierCurve: CubicBezierCurve,
  22861. CubicBezierCurve3: CubicBezierCurve3,
  22862. EllipseCurve: EllipseCurve,
  22863. LineCurve: LineCurve,
  22864. LineCurve3: LineCurve3,
  22865. QuadraticBezierCurve: QuadraticBezierCurve,
  22866. QuadraticBezierCurve3: QuadraticBezierCurve3,
  22867. SplineCurve: SplineCurve
  22868. });
  22869. /**
  22870. * @author zz85 / http://www.lab4games.net/zz85/blog
  22871. *
  22872. **/
  22873. /**************************************************************
  22874. * Curved Path - a curve path is simply a array of connected
  22875. * curves, but retains the api of a curve
  22876. **************************************************************/
  22877. function CurvePath() {
  22878. Curve.call(this);
  22879. this.type = 'CurvePath';
  22880. this.curves = [];
  22881. this.autoClose = false; // Automatically closes the path
  22882. }
  22883. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  22884. constructor: CurvePath,
  22885. add: function (curve) {
  22886. this.curves.push(curve);
  22887. },
  22888. closePath: function () {
  22889. // Add a line curve if start and end of lines are not connected
  22890. var startPoint = this.curves[0].getPoint(0);
  22891. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  22892. if (!startPoint.equals(endPoint)) {
  22893. this.curves.push(new LineCurve(endPoint, startPoint));
  22894. }
  22895. },
  22896. // To get accurate point with reference to
  22897. // entire path distance at time t,
  22898. // following has to be done:
  22899. // 1. Length of each sub path have to be known
  22900. // 2. Locate and identify type of curve
  22901. // 3. Get t for the curve
  22902. // 4. Return curve.getPointAt(t')
  22903. getPoint: function (t) {
  22904. var d = t * this.getLength();
  22905. var curveLengths = this.getCurveLengths();
  22906. var i = 0; // To think about boundaries points.
  22907. while (i < curveLengths.length) {
  22908. if (curveLengths[i] >= d) {
  22909. var diff = curveLengths[i] - d;
  22910. var curve = this.curves[i];
  22911. var segmentLength = curve.getLength();
  22912. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  22913. return curve.getPointAt(u);
  22914. }
  22915. i++;
  22916. }
  22917. return null; // loop where sum != 0, sum > d , sum+1 <d
  22918. },
  22919. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  22920. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  22921. // getPoint() depends on getLength
  22922. getLength: function () {
  22923. var lens = this.getCurveLengths();
  22924. return lens[lens.length - 1];
  22925. },
  22926. // cacheLengths must be recalculated.
  22927. updateArcLengths: function () {
  22928. this.needsUpdate = true;
  22929. this.cacheLengths = null;
  22930. this.getCurveLengths();
  22931. },
  22932. // Compute lengths and cache them
  22933. // We cannot overwrite getLengths() because UtoT mapping uses it.
  22934. getCurveLengths: function () {
  22935. // We use cache values if curves and cache array are same length
  22936. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  22937. return this.cacheLengths;
  22938. } // Get length of sub-curve
  22939. // Push sums into cached array
  22940. var lengths = [],
  22941. sums = 0;
  22942. for (var i = 0, l = this.curves.length; i < l; i++) {
  22943. sums += this.curves[i].getLength();
  22944. lengths.push(sums);
  22945. }
  22946. this.cacheLengths = lengths;
  22947. return lengths;
  22948. },
  22949. getSpacedPoints: function (divisions) {
  22950. if (divisions === undefined) divisions = 40;
  22951. var points = [];
  22952. for (var i = 0; i <= divisions; i++) {
  22953. points.push(this.getPoint(i / divisions));
  22954. }
  22955. if (this.autoClose) {
  22956. points.push(points[0]);
  22957. }
  22958. return points;
  22959. },
  22960. getPoints: function (divisions) {
  22961. divisions = divisions || 12;
  22962. var points = [],
  22963. last;
  22964. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  22965. var curve = curves[i];
  22966. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  22967. var pts = curve.getPoints(resolution);
  22968. for (var j = 0; j < pts.length; j++) {
  22969. var point = pts[j];
  22970. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  22971. points.push(point);
  22972. last = point;
  22973. }
  22974. }
  22975. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  22976. points.push(points[0]);
  22977. }
  22978. return points;
  22979. },
  22980. copy: function (source) {
  22981. Curve.prototype.copy.call(this, source);
  22982. this.curves = [];
  22983. for (var i = 0, l = source.curves.length; i < l; i++) {
  22984. var curve = source.curves[i];
  22985. this.curves.push(curve.clone());
  22986. }
  22987. this.autoClose = source.autoClose;
  22988. return this;
  22989. },
  22990. toJSON: function () {
  22991. var data = Curve.prototype.toJSON.call(this);
  22992. data.autoClose = this.autoClose;
  22993. data.curves = [];
  22994. for (var i = 0, l = this.curves.length; i < l; i++) {
  22995. var curve = this.curves[i];
  22996. data.curves.push(curve.toJSON());
  22997. }
  22998. return data;
  22999. },
  23000. fromJSON: function (json) {
  23001. Curve.prototype.fromJSON.call(this, json);
  23002. this.autoClose = json.autoClose;
  23003. this.curves = [];
  23004. for (var i = 0, l = json.curves.length; i < l; i++) {
  23005. var curve = json.curves[i];
  23006. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23007. }
  23008. return this;
  23009. }
  23010. });
  23011. /**
  23012. * @author zz85 / http://www.lab4games.net/zz85/blog
  23013. * Creates free form 2d path using series of points, lines or curves.
  23014. **/
  23015. function Path(points) {
  23016. CurvePath.call(this);
  23017. this.type = 'Path';
  23018. this.currentPoint = new Vector2();
  23019. if (points) {
  23020. this.setFromPoints(points);
  23021. }
  23022. }
  23023. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23024. constructor: Path,
  23025. setFromPoints: function (points) {
  23026. this.moveTo(points[0].x, points[0].y);
  23027. for (var i = 1, l = points.length; i < l; i++) {
  23028. this.lineTo(points[i].x, points[i].y);
  23029. }
  23030. return this;
  23031. },
  23032. moveTo: function (x, y) {
  23033. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23034. return this;
  23035. },
  23036. lineTo: function (x, y) {
  23037. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23038. this.curves.push(curve);
  23039. this.currentPoint.set(x, y);
  23040. return this;
  23041. },
  23042. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23043. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23044. this.curves.push(curve);
  23045. this.currentPoint.set(aX, aY);
  23046. return this;
  23047. },
  23048. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23049. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23050. this.curves.push(curve);
  23051. this.currentPoint.set(aX, aY);
  23052. return this;
  23053. },
  23054. splineThru: function (pts
  23055. /*Array of Vector*/
  23056. ) {
  23057. var npts = [this.currentPoint.clone()].concat(pts);
  23058. var curve = new SplineCurve(npts);
  23059. this.curves.push(curve);
  23060. this.currentPoint.copy(pts[pts.length - 1]);
  23061. return this;
  23062. },
  23063. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23064. var x0 = this.currentPoint.x;
  23065. var y0 = this.currentPoint.y;
  23066. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23067. return this;
  23068. },
  23069. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23070. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23071. return this;
  23072. },
  23073. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23074. var x0 = this.currentPoint.x;
  23075. var y0 = this.currentPoint.y;
  23076. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23077. return this;
  23078. },
  23079. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23080. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23081. if (this.curves.length > 0) {
  23082. // if a previous curve is present, attempt to join
  23083. var firstPoint = curve.getPoint(0);
  23084. if (!firstPoint.equals(this.currentPoint)) {
  23085. this.lineTo(firstPoint.x, firstPoint.y);
  23086. }
  23087. }
  23088. this.curves.push(curve);
  23089. var lastPoint = curve.getPoint(1);
  23090. this.currentPoint.copy(lastPoint);
  23091. return this;
  23092. },
  23093. copy: function (source) {
  23094. CurvePath.prototype.copy.call(this, source);
  23095. this.currentPoint.copy(source.currentPoint);
  23096. return this;
  23097. },
  23098. toJSON: function () {
  23099. var data = CurvePath.prototype.toJSON.call(this);
  23100. data.currentPoint = this.currentPoint.toArray();
  23101. return data;
  23102. },
  23103. fromJSON: function (json) {
  23104. CurvePath.prototype.fromJSON.call(this, json);
  23105. this.currentPoint.fromArray(json.currentPoint);
  23106. return this;
  23107. }
  23108. });
  23109. /**
  23110. * @author zz85 / http://www.lab4games.net/zz85/blog
  23111. * Defines a 2d shape plane using paths.
  23112. **/
  23113. // STEP 1 Create a path.
  23114. // STEP 2 Turn path into shape.
  23115. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  23116. // STEP 3a - Extract points from each shape, turn to vertices
  23117. // STEP 3b - Triangulate each shape, add faces.
  23118. function Shape(points) {
  23119. Path.call(this, points);
  23120. this.uuid = MathUtils.generateUUID();
  23121. this.type = 'Shape';
  23122. this.holes = [];
  23123. }
  23124. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23125. constructor: Shape,
  23126. getPointsHoles: function (divisions) {
  23127. var holesPts = [];
  23128. for (var i = 0, l = this.holes.length; i < l; i++) {
  23129. holesPts[i] = this.holes[i].getPoints(divisions);
  23130. }
  23131. return holesPts;
  23132. },
  23133. // get points of shape and holes (keypoints based on segments parameter)
  23134. extractPoints: function (divisions) {
  23135. return {
  23136. shape: this.getPoints(divisions),
  23137. holes: this.getPointsHoles(divisions)
  23138. };
  23139. },
  23140. copy: function (source) {
  23141. Path.prototype.copy.call(this, source);
  23142. this.holes = [];
  23143. for (var i = 0, l = source.holes.length; i < l; i++) {
  23144. var hole = source.holes[i];
  23145. this.holes.push(hole.clone());
  23146. }
  23147. return this;
  23148. },
  23149. toJSON: function () {
  23150. var data = Path.prototype.toJSON.call(this);
  23151. data.uuid = this.uuid;
  23152. data.holes = [];
  23153. for (var i = 0, l = this.holes.length; i < l; i++) {
  23154. var hole = this.holes[i];
  23155. data.holes.push(hole.toJSON());
  23156. }
  23157. return data;
  23158. },
  23159. fromJSON: function (json) {
  23160. Path.prototype.fromJSON.call(this, json);
  23161. this.uuid = json.uuid;
  23162. this.holes = [];
  23163. for (var i = 0, l = json.holes.length; i < l; i++) {
  23164. var hole = json.holes[i];
  23165. this.holes.push(new Path().fromJSON(hole));
  23166. }
  23167. return this;
  23168. }
  23169. });
  23170. /**
  23171. * @author mrdoob / http://mrdoob.com/
  23172. * @author alteredq / http://alteredqualia.com/
  23173. */
  23174. function Light(color, intensity) {
  23175. Object3D.call(this);
  23176. this.type = 'Light';
  23177. this.color = new Color(color);
  23178. this.intensity = intensity !== undefined ? intensity : 1;
  23179. this.receiveShadow = undefined;
  23180. }
  23181. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23182. constructor: Light,
  23183. isLight: true,
  23184. copy: function (source) {
  23185. Object3D.prototype.copy.call(this, source);
  23186. this.color.copy(source.color);
  23187. this.intensity = source.intensity;
  23188. return this;
  23189. },
  23190. toJSON: function (meta) {
  23191. var data = Object3D.prototype.toJSON.call(this, meta);
  23192. data.object.color = this.color.getHex();
  23193. data.object.intensity = this.intensity;
  23194. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23195. if (this.distance !== undefined) data.object.distance = this.distance;
  23196. if (this.angle !== undefined) data.object.angle = this.angle;
  23197. if (this.decay !== undefined) data.object.decay = this.decay;
  23198. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23199. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23200. return data;
  23201. }
  23202. });
  23203. /**
  23204. * @author alteredq / http://alteredqualia.com/
  23205. */
  23206. function HemisphereLight(skyColor, groundColor, intensity) {
  23207. Light.call(this, skyColor, intensity);
  23208. this.type = 'HemisphereLight';
  23209. this.castShadow = undefined;
  23210. this.position.copy(Object3D.DefaultUp);
  23211. this.updateMatrix();
  23212. this.groundColor = new Color(groundColor);
  23213. }
  23214. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23215. constructor: HemisphereLight,
  23216. isHemisphereLight: true,
  23217. copy: function (source) {
  23218. Light.prototype.copy.call(this, source);
  23219. this.groundColor.copy(source.groundColor);
  23220. return this;
  23221. }
  23222. });
  23223. /**
  23224. * @author mrdoob / http://mrdoob.com/
  23225. */
  23226. function LightShadow(camera) {
  23227. this.camera = camera;
  23228. this.bias = 0;
  23229. this.radius = 1;
  23230. this.mapSize = new Vector2(512, 512);
  23231. this.map = null;
  23232. this.mapPass = null;
  23233. this.matrix = new Matrix4();
  23234. this._frustum = new Frustum();
  23235. this._frameExtents = new Vector2(1, 1);
  23236. this._viewportCount = 1;
  23237. this._viewports = [new Vector4(0, 0, 1, 1)];
  23238. }
  23239. Object.assign(LightShadow.prototype, {
  23240. _projScreenMatrix: new Matrix4(),
  23241. _lightPositionWorld: new Vector3(),
  23242. _lookTarget: new Vector3(),
  23243. getViewportCount: function () {
  23244. return this._viewportCount;
  23245. },
  23246. getFrustum: function () {
  23247. return this._frustum;
  23248. },
  23249. updateMatrices: function (light) {
  23250. var shadowCamera = this.camera,
  23251. shadowMatrix = this.matrix,
  23252. projScreenMatrix = this._projScreenMatrix,
  23253. lookTarget = this._lookTarget,
  23254. lightPositionWorld = this._lightPositionWorld;
  23255. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23256. shadowCamera.position.copy(lightPositionWorld);
  23257. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23258. shadowCamera.lookAt(lookTarget);
  23259. shadowCamera.updateMatrixWorld();
  23260. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23261. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23262. 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);
  23263. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23264. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23265. },
  23266. getViewport: function (viewportIndex) {
  23267. return this._viewports[viewportIndex];
  23268. },
  23269. getFrameExtents: function () {
  23270. return this._frameExtents;
  23271. },
  23272. copy: function (source) {
  23273. this.camera = source.camera.clone();
  23274. this.bias = source.bias;
  23275. this.radius = source.radius;
  23276. this.mapSize.copy(source.mapSize);
  23277. return this;
  23278. },
  23279. clone: function () {
  23280. return new this.constructor().copy(this);
  23281. },
  23282. toJSON: function () {
  23283. var object = {};
  23284. if (this.bias !== 0) object.bias = this.bias;
  23285. if (this.radius !== 1) object.radius = this.radius;
  23286. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23287. object.camera = this.camera.toJSON(false).object;
  23288. delete object.camera.matrix;
  23289. return object;
  23290. }
  23291. });
  23292. /**
  23293. * @author mrdoob / http://mrdoob.com/
  23294. */
  23295. function SpotLightShadow() {
  23296. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  23297. }
  23298. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23299. constructor: SpotLightShadow,
  23300. isSpotLightShadow: true,
  23301. updateMatrices: function (light) {
  23302. var camera = this.camera;
  23303. var fov = MathUtils.RAD2DEG * 2 * light.angle;
  23304. var aspect = this.mapSize.width / this.mapSize.height;
  23305. var far = light.distance || camera.far;
  23306. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23307. camera.fov = fov;
  23308. camera.aspect = aspect;
  23309. camera.far = far;
  23310. camera.updateProjectionMatrix();
  23311. }
  23312. LightShadow.prototype.updateMatrices.call(this, light);
  23313. }
  23314. });
  23315. /**
  23316. * @author alteredq / http://alteredqualia.com/
  23317. */
  23318. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  23319. Light.call(this, color, intensity);
  23320. this.type = 'SpotLight';
  23321. this.position.copy(Object3D.DefaultUp);
  23322. this.updateMatrix();
  23323. this.target = new Object3D();
  23324. Object.defineProperty(this, 'power', {
  23325. get: function () {
  23326. // intensity = power per solid angle.
  23327. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23328. return this.intensity * Math.PI;
  23329. },
  23330. set: function (power) {
  23331. // intensity = power per solid angle.
  23332. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23333. this.intensity = power / Math.PI;
  23334. }
  23335. });
  23336. this.distance = distance !== undefined ? distance : 0;
  23337. this.angle = angle !== undefined ? angle : Math.PI / 3;
  23338. this.penumbra = penumbra !== undefined ? penumbra : 0;
  23339. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23340. this.shadow = new SpotLightShadow();
  23341. }
  23342. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  23343. constructor: SpotLight,
  23344. isSpotLight: true,
  23345. copy: function (source) {
  23346. Light.prototype.copy.call(this, source);
  23347. this.distance = source.distance;
  23348. this.angle = source.angle;
  23349. this.penumbra = source.penumbra;
  23350. this.decay = source.decay;
  23351. this.target = source.target.clone();
  23352. this.shadow = source.shadow.clone();
  23353. return this;
  23354. }
  23355. });
  23356. function PointLightShadow() {
  23357. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  23358. this._frameExtents = new Vector2(4, 2);
  23359. this._viewportCount = 6;
  23360. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23361. // following orientation:
  23362. //
  23363. // xzXZ
  23364. // y Y
  23365. //
  23366. // X - Positive x direction
  23367. // x - Negative x direction
  23368. // Y - Positive y direction
  23369. // y - Negative y direction
  23370. // Z - Positive z direction
  23371. // z - Negative z direction
  23372. // positive X
  23373. new Vector4(2, 1, 1, 1), // negative X
  23374. new Vector4(0, 1, 1, 1), // positive Z
  23375. new Vector4(3, 1, 1, 1), // negative Z
  23376. new Vector4(1, 1, 1, 1), // positive Y
  23377. new Vector4(3, 0, 1, 1), // negative Y
  23378. new Vector4(1, 0, 1, 1)];
  23379. 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)];
  23380. 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)];
  23381. }
  23382. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23383. constructor: PointLightShadow,
  23384. isPointLightShadow: true,
  23385. updateMatrices: function (light, viewportIndex) {
  23386. if (viewportIndex === undefined) viewportIndex = 0;
  23387. var camera = this.camera,
  23388. shadowMatrix = this.matrix,
  23389. lightPositionWorld = this._lightPositionWorld,
  23390. lookTarget = this._lookTarget,
  23391. projScreenMatrix = this._projScreenMatrix;
  23392. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23393. camera.position.copy(lightPositionWorld);
  23394. lookTarget.copy(camera.position);
  23395. lookTarget.add(this._cubeDirections[viewportIndex]);
  23396. camera.up.copy(this._cubeUps[viewportIndex]);
  23397. camera.lookAt(lookTarget);
  23398. camera.updateMatrixWorld();
  23399. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  23400. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23401. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23402. }
  23403. });
  23404. /**
  23405. * @author mrdoob / http://mrdoob.com/
  23406. */
  23407. function PointLight(color, intensity, distance, decay) {
  23408. Light.call(this, color, intensity);
  23409. this.type = 'PointLight';
  23410. Object.defineProperty(this, 'power', {
  23411. get: function () {
  23412. // intensity = power per solid angle.
  23413. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23414. return this.intensity * 4 * Math.PI;
  23415. },
  23416. set: function (power) {
  23417. // intensity = power per solid angle.
  23418. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23419. this.intensity = power / (4 * Math.PI);
  23420. }
  23421. });
  23422. this.distance = distance !== undefined ? distance : 0;
  23423. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23424. this.shadow = new PointLightShadow();
  23425. }
  23426. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  23427. constructor: PointLight,
  23428. isPointLight: true,
  23429. copy: function (source) {
  23430. Light.prototype.copy.call(this, source);
  23431. this.distance = source.distance;
  23432. this.decay = source.decay;
  23433. this.shadow = source.shadow.clone();
  23434. return this;
  23435. }
  23436. });
  23437. /**
  23438. * @author alteredq / http://alteredqualia.com/
  23439. * @author arose / http://github.com/arose
  23440. */
  23441. function OrthographicCamera(left, right, top, bottom, near, far) {
  23442. Camera.call(this);
  23443. this.type = 'OrthographicCamera';
  23444. this.zoom = 1;
  23445. this.view = null;
  23446. this.left = left !== undefined ? left : -1;
  23447. this.right = right !== undefined ? right : 1;
  23448. this.top = top !== undefined ? top : 1;
  23449. this.bottom = bottom !== undefined ? bottom : -1;
  23450. this.near = near !== undefined ? near : 0.1;
  23451. this.far = far !== undefined ? far : 2000;
  23452. this.updateProjectionMatrix();
  23453. }
  23454. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  23455. constructor: OrthographicCamera,
  23456. isOrthographicCamera: true,
  23457. copy: function (source, recursive) {
  23458. Camera.prototype.copy.call(this, source, recursive);
  23459. this.left = source.left;
  23460. this.right = source.right;
  23461. this.top = source.top;
  23462. this.bottom = source.bottom;
  23463. this.near = source.near;
  23464. this.far = source.far;
  23465. this.zoom = source.zoom;
  23466. this.view = source.view === null ? null : Object.assign({}, source.view);
  23467. return this;
  23468. },
  23469. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  23470. if (this.view === null) {
  23471. this.view = {
  23472. enabled: true,
  23473. fullWidth: 1,
  23474. fullHeight: 1,
  23475. offsetX: 0,
  23476. offsetY: 0,
  23477. width: 1,
  23478. height: 1
  23479. };
  23480. }
  23481. this.view.enabled = true;
  23482. this.view.fullWidth = fullWidth;
  23483. this.view.fullHeight = fullHeight;
  23484. this.view.offsetX = x;
  23485. this.view.offsetY = y;
  23486. this.view.width = width;
  23487. this.view.height = height;
  23488. this.updateProjectionMatrix();
  23489. },
  23490. clearViewOffset: function () {
  23491. if (this.view !== null) {
  23492. this.view.enabled = false;
  23493. }
  23494. this.updateProjectionMatrix();
  23495. },
  23496. updateProjectionMatrix: function () {
  23497. var dx = (this.right - this.left) / (2 * this.zoom);
  23498. var dy = (this.top - this.bottom) / (2 * this.zoom);
  23499. var cx = (this.right + this.left) / 2;
  23500. var cy = (this.top + this.bottom) / 2;
  23501. var left = cx - dx;
  23502. var right = cx + dx;
  23503. var top = cy + dy;
  23504. var bottom = cy - dy;
  23505. if (this.view !== null && this.view.enabled) {
  23506. var scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  23507. var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  23508. left += scaleW * this.view.offsetX;
  23509. right = left + scaleW * this.view.width;
  23510. top -= scaleH * this.view.offsetY;
  23511. bottom = top - scaleH * this.view.height;
  23512. }
  23513. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  23514. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  23515. },
  23516. toJSON: function (meta) {
  23517. var data = Object3D.prototype.toJSON.call(this, meta);
  23518. data.object.zoom = this.zoom;
  23519. data.object.left = this.left;
  23520. data.object.right = this.right;
  23521. data.object.top = this.top;
  23522. data.object.bottom = this.bottom;
  23523. data.object.near = this.near;
  23524. data.object.far = this.far;
  23525. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  23526. return data;
  23527. }
  23528. });
  23529. /**
  23530. * @author mrdoob / http://mrdoob.com/
  23531. */
  23532. function DirectionalLightShadow() {
  23533. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23534. }
  23535. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23536. constructor: DirectionalLightShadow,
  23537. isDirectionalLightShadow: true,
  23538. updateMatrices: function (light) {
  23539. LightShadow.prototype.updateMatrices.call(this, light);
  23540. }
  23541. });
  23542. /**
  23543. * @author mrdoob / http://mrdoob.com/
  23544. * @author alteredq / http://alteredqualia.com/
  23545. */
  23546. function DirectionalLight(color, intensity) {
  23547. Light.call(this, color, intensity);
  23548. this.type = 'DirectionalLight';
  23549. this.position.copy(Object3D.DefaultUp);
  23550. this.updateMatrix();
  23551. this.target = new Object3D();
  23552. this.shadow = new DirectionalLightShadow();
  23553. }
  23554. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  23555. constructor: DirectionalLight,
  23556. isDirectionalLight: true,
  23557. copy: function (source) {
  23558. Light.prototype.copy.call(this, source);
  23559. this.target = source.target.clone();
  23560. this.shadow = source.shadow.clone();
  23561. return this;
  23562. }
  23563. });
  23564. /**
  23565. * @author mrdoob / http://mrdoob.com/
  23566. */
  23567. function AmbientLight(color, intensity) {
  23568. Light.call(this, color, intensity);
  23569. this.type = 'AmbientLight';
  23570. this.castShadow = undefined;
  23571. }
  23572. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  23573. constructor: AmbientLight,
  23574. isAmbientLight: true
  23575. });
  23576. /**
  23577. * @author abelnation / http://github.com/abelnation
  23578. */
  23579. function RectAreaLight(color, intensity, width, height) {
  23580. Light.call(this, color, intensity);
  23581. this.type = 'RectAreaLight';
  23582. this.width = width !== undefined ? width : 10;
  23583. this.height = height !== undefined ? height : 10;
  23584. }
  23585. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  23586. constructor: RectAreaLight,
  23587. isRectAreaLight: true,
  23588. copy: function (source) {
  23589. Light.prototype.copy.call(this, source);
  23590. this.width = source.width;
  23591. this.height = source.height;
  23592. return this;
  23593. },
  23594. toJSON: function (meta) {
  23595. var data = Light.prototype.toJSON.call(this, meta);
  23596. data.object.width = this.width;
  23597. data.object.height = this.height;
  23598. return data;
  23599. }
  23600. });
  23601. /**
  23602. * @author mrdoob / http://mrdoob.com/
  23603. */
  23604. function MaterialLoader(manager) {
  23605. Loader.call(this, manager);
  23606. this.textures = {};
  23607. }
  23608. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23609. constructor: MaterialLoader,
  23610. load: function (url, onLoad, onProgress, onError) {
  23611. var scope = this;
  23612. var loader = new FileLoader(scope.manager);
  23613. loader.setPath(scope.path);
  23614. loader.load(url, function (text) {
  23615. onLoad(scope.parse(JSON.parse(text)));
  23616. }, onProgress, onError);
  23617. },
  23618. parse: function (json) {
  23619. var textures = this.textures;
  23620. function getTexture(name) {
  23621. if (textures[name] === undefined) {
  23622. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23623. }
  23624. return textures[name];
  23625. }
  23626. var material = new Materials[json.type]();
  23627. if (json.uuid !== undefined) material.uuid = json.uuid;
  23628. if (json.name !== undefined) material.name = json.name;
  23629. if (json.color !== undefined) material.color.setHex(json.color);
  23630. if (json.roughness !== undefined) material.roughness = json.roughness;
  23631. if (json.metalness !== undefined) material.metalness = json.metalness;
  23632. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  23633. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  23634. if (json.specular !== undefined) material.specular.setHex(json.specular);
  23635. if (json.shininess !== undefined) material.shininess = json.shininess;
  23636. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23637. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23638. if (json.fog !== undefined) material.fog = json.fog;
  23639. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23640. if (json.blending !== undefined) material.blending = json.blending;
  23641. if (json.combine !== undefined) material.combine = json.combine;
  23642. if (json.side !== undefined) material.side = json.side;
  23643. if (json.opacity !== undefined) material.opacity = json.opacity;
  23644. if (json.transparent !== undefined) material.transparent = json.transparent;
  23645. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23646. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23647. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23648. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23649. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23650. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23651. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23652. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23653. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23654. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23655. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23656. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23657. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23658. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23659. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23660. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23661. if (json.rotation !== undefined) material.rotation = json.rotation;
  23662. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23663. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23664. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23665. if (json.scale !== undefined) material.scale = json.scale;
  23666. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23667. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23668. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23669. if (json.skinning !== undefined) material.skinning = json.skinning;
  23670. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  23671. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  23672. if (json.dithering !== undefined) material.dithering = json.dithering;
  23673. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  23674. if (json.visible !== undefined) material.visible = json.visible;
  23675. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23676. if (json.userData !== undefined) material.userData = json.userData;
  23677. if (json.vertexColors !== undefined) {
  23678. if (typeof json.vertexColors === 'number') {
  23679. material.vertexColors = json.vertexColors > 0 ? true : false;
  23680. } else {
  23681. material.vertexColors = json.vertexColors;
  23682. }
  23683. } // Shader Material
  23684. if (json.uniforms !== undefined) {
  23685. for (var name in json.uniforms) {
  23686. var uniform = json.uniforms[name];
  23687. material.uniforms[name] = {};
  23688. switch (uniform.type) {
  23689. case 't':
  23690. material.uniforms[name].value = getTexture(uniform.value);
  23691. break;
  23692. case 'c':
  23693. material.uniforms[name].value = new Color().setHex(uniform.value);
  23694. break;
  23695. case 'v2':
  23696. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23697. break;
  23698. case 'v3':
  23699. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23700. break;
  23701. case 'v4':
  23702. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23703. break;
  23704. case 'm3':
  23705. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23706. case 'm4':
  23707. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23708. break;
  23709. default:
  23710. material.uniforms[name].value = uniform.value;
  23711. }
  23712. }
  23713. }
  23714. if (json.defines !== undefined) material.defines = json.defines;
  23715. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23716. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23717. if (json.extensions !== undefined) {
  23718. for (var key in json.extensions) {
  23719. material.extensions[key] = json.extensions[key];
  23720. }
  23721. } // Deprecated
  23722. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23723. // for PointsMaterial
  23724. if (json.size !== undefined) material.size = json.size;
  23725. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23726. if (json.map !== undefined) material.map = getTexture(json.map);
  23727. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23728. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23729. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23730. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23731. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23732. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23733. if (json.normalScale !== undefined) {
  23734. var normalScale = json.normalScale;
  23735. if (Array.isArray(normalScale) === false) {
  23736. // Blender exporter used to export a scalar. See #7459
  23737. normalScale = [normalScale, normalScale];
  23738. }
  23739. material.normalScale = new Vector2().fromArray(normalScale);
  23740. }
  23741. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23742. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23743. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23744. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23745. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23746. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23747. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23748. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23749. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23750. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23751. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23752. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23753. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23754. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23755. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23756. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23757. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23758. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  23759. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  23760. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23761. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23762. return material;
  23763. },
  23764. setTextures: function (value) {
  23765. this.textures = value;
  23766. return this;
  23767. }
  23768. });
  23769. /**
  23770. * @author Don McCurdy / https://www.donmccurdy.com
  23771. */
  23772. var LoaderUtils = {
  23773. decodeText: function (array) {
  23774. if (typeof TextDecoder !== 'undefined') {
  23775. return new TextDecoder().decode(array);
  23776. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23777. // throws a "maximum call stack size exceeded" error for large arrays.
  23778. var s = '';
  23779. for (var i = 0, il = array.length; i < il; i++) {
  23780. // Implicitly assumes little-endian.
  23781. s += String.fromCharCode(array[i]);
  23782. }
  23783. try {
  23784. // merges multi-byte utf-8 characters.
  23785. return decodeURIComponent(escape(s));
  23786. } catch (e) {
  23787. // see #16358
  23788. return s;
  23789. }
  23790. },
  23791. extractUrlBase: function (url) {
  23792. var index = url.lastIndexOf('/');
  23793. if (index === -1) return './';
  23794. return url.substr(0, index + 1);
  23795. }
  23796. };
  23797. /**
  23798. * @author benaadams / https://twitter.com/ben_a_adams
  23799. */
  23800. exports.LoaderUtils = LoaderUtils;
  23801. function InstancedBufferGeometry() {
  23802. BufferGeometry.call(this);
  23803. this.type = 'InstancedBufferGeometry';
  23804. this.maxInstancedCount = undefined;
  23805. }
  23806. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  23807. constructor: InstancedBufferGeometry,
  23808. isInstancedBufferGeometry: true,
  23809. copy: function (source) {
  23810. BufferGeometry.prototype.copy.call(this, source);
  23811. this.maxInstancedCount = source.maxInstancedCount;
  23812. return this;
  23813. },
  23814. clone: function () {
  23815. return new this.constructor().copy(this);
  23816. },
  23817. toJSON: function () {
  23818. var data = BufferGeometry.prototype.toJSON.call(this);
  23819. data.maxInstancedCount = this.maxInstancedCount;
  23820. data.isInstancedBufferGeometry = true;
  23821. return data;
  23822. }
  23823. });
  23824. /**
  23825. * @author benaadams / https://twitter.com/ben_a_adams
  23826. */
  23827. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  23828. if (typeof normalized === 'number') {
  23829. meshPerAttribute = normalized;
  23830. normalized = false;
  23831. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  23832. }
  23833. BufferAttribute.call(this, array, itemSize, normalized);
  23834. this.meshPerAttribute = meshPerAttribute || 1;
  23835. }
  23836. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  23837. constructor: InstancedBufferAttribute,
  23838. isInstancedBufferAttribute: true,
  23839. copy: function (source) {
  23840. BufferAttribute.prototype.copy.call(this, source);
  23841. this.meshPerAttribute = source.meshPerAttribute;
  23842. return this;
  23843. },
  23844. toJSON: function () {
  23845. var data = BufferAttribute.prototype.toJSON.call(this);
  23846. data.meshPerAttribute = this.meshPerAttribute;
  23847. data.isInstancedBufferAttribute = true;
  23848. return data;
  23849. }
  23850. });
  23851. /**
  23852. * @author mrdoob / http://mrdoob.com/
  23853. */
  23854. function BufferGeometryLoader(manager) {
  23855. Loader.call(this, manager);
  23856. }
  23857. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23858. constructor: BufferGeometryLoader,
  23859. load: function (url, onLoad, onProgress, onError) {
  23860. var scope = this;
  23861. var loader = new FileLoader(scope.manager);
  23862. loader.setPath(scope.path);
  23863. loader.load(url, function (text) {
  23864. onLoad(scope.parse(JSON.parse(text)));
  23865. }, onProgress, onError);
  23866. },
  23867. parse: function (json) {
  23868. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23869. var index = json.data.index;
  23870. if (index !== undefined) {
  23871. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  23872. geometry.setIndex(new BufferAttribute(typedArray, 1));
  23873. }
  23874. var attributes = json.data.attributes;
  23875. for (var key in attributes) {
  23876. var attribute = attributes[key];
  23877. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  23878. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23879. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  23880. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23881. geometry.setAttribute(key, bufferAttribute);
  23882. }
  23883. var morphAttributes = json.data.morphAttributes;
  23884. if (morphAttributes) {
  23885. for (var key in morphAttributes) {
  23886. var attributeArray = morphAttributes[key];
  23887. var array = [];
  23888. for (var i = 0, il = attributeArray.length; i < il; i++) {
  23889. var attribute = attributeArray[i];
  23890. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  23891. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  23892. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23893. array.push(bufferAttribute);
  23894. }
  23895. geometry.morphAttributes[key] = array;
  23896. }
  23897. }
  23898. var morphTargetsRelative = json.data.morphTargetsRelative;
  23899. if (morphTargetsRelative) {
  23900. geometry.morphTargetsRelative = true;
  23901. }
  23902. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23903. if (groups !== undefined) {
  23904. for (var i = 0, n = groups.length; i !== n; ++i) {
  23905. var group = groups[i];
  23906. geometry.addGroup(group.start, group.count, group.materialIndex);
  23907. }
  23908. }
  23909. var boundingSphere = json.data.boundingSphere;
  23910. if (boundingSphere !== undefined) {
  23911. var center = new Vector3();
  23912. if (boundingSphere.center !== undefined) {
  23913. center.fromArray(boundingSphere.center);
  23914. }
  23915. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23916. }
  23917. if (json.name) geometry.name = json.name;
  23918. if (json.userData) geometry.userData = json.userData;
  23919. return geometry;
  23920. }
  23921. });
  23922. var TYPED_ARRAYS = {
  23923. Int8Array: Int8Array,
  23924. Uint8Array: Uint8Array,
  23925. // Workaround for IE11 pre KB2929437. See #11440
  23926. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  23927. Int16Array: Int16Array,
  23928. Uint16Array: Uint16Array,
  23929. Int32Array: Int32Array,
  23930. Uint32Array: Uint32Array,
  23931. Float32Array: Float32Array,
  23932. Float64Array: Float64Array
  23933. };
  23934. /**
  23935. * @author mrdoob / http://mrdoob.com/
  23936. */
  23937. function ObjectLoader(manager) {
  23938. Loader.call(this, manager);
  23939. }
  23940. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23941. constructor: ObjectLoader,
  23942. load: function (url, onLoad, onProgress, onError) {
  23943. var scope = this;
  23944. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23945. this.resourcePath = this.resourcePath || path;
  23946. var loader = new FileLoader(scope.manager);
  23947. loader.setPath(this.path);
  23948. loader.load(url, function (text) {
  23949. var json = null;
  23950. try {
  23951. json = JSON.parse(text);
  23952. } catch (error) {
  23953. if (onError !== undefined) onError(error);
  23954. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23955. return;
  23956. }
  23957. var metadata = json.metadata;
  23958. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23959. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23960. return;
  23961. }
  23962. scope.parse(json, onLoad);
  23963. }, onProgress, onError);
  23964. },
  23965. parse: function (json, onLoad) {
  23966. var shapes = this.parseShape(json.shapes);
  23967. var geometries = this.parseGeometries(json.geometries, shapes);
  23968. var images = this.parseImages(json.images, function () {
  23969. if (onLoad !== undefined) onLoad(object);
  23970. });
  23971. var textures = this.parseTextures(json.textures, images);
  23972. var materials = this.parseMaterials(json.materials, textures);
  23973. var object = this.parseObject(json.object, geometries, materials);
  23974. if (json.animations) {
  23975. object.animations = this.parseAnimations(json.animations);
  23976. }
  23977. if (json.images === undefined || json.images.length === 0) {
  23978. if (onLoad !== undefined) onLoad(object);
  23979. }
  23980. return object;
  23981. },
  23982. parseShape: function (json) {
  23983. var shapes = {};
  23984. if (json !== undefined) {
  23985. for (var i = 0, l = json.length; i < l; i++) {
  23986. var shape = new Shape().fromJSON(json[i]);
  23987. shapes[shape.uuid] = shape;
  23988. }
  23989. }
  23990. return shapes;
  23991. },
  23992. parseGeometries: function (json, shapes) {
  23993. var geometries = {};
  23994. if (json !== undefined) {
  23995. var bufferGeometryLoader = new BufferGeometryLoader();
  23996. for (var i = 0, l = json.length; i < l; i++) {
  23997. var geometry;
  23998. var data = json[i];
  23999. switch (data.type) {
  24000. case 'PlaneGeometry':
  24001. case 'PlaneBufferGeometry':
  24002. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24003. break;
  24004. case 'BoxGeometry':
  24005. case 'BoxBufferGeometry':
  24006. case 'CubeGeometry':
  24007. // backwards compatible
  24008. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24009. break;
  24010. case 'CircleGeometry':
  24011. case 'CircleBufferGeometry':
  24012. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24013. break;
  24014. case 'CylinderGeometry':
  24015. case 'CylinderBufferGeometry':
  24016. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24017. break;
  24018. case 'ConeGeometry':
  24019. case 'ConeBufferGeometry':
  24020. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24021. break;
  24022. case 'SphereGeometry':
  24023. case 'SphereBufferGeometry':
  24024. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24025. break;
  24026. case 'DodecahedronGeometry':
  24027. case 'DodecahedronBufferGeometry':
  24028. case 'IcosahedronGeometry':
  24029. case 'IcosahedronBufferGeometry':
  24030. case 'OctahedronGeometry':
  24031. case 'OctahedronBufferGeometry':
  24032. case 'TetrahedronGeometry':
  24033. case 'TetrahedronBufferGeometry':
  24034. geometry = new Geometries[data.type](data.radius, data.detail);
  24035. break;
  24036. case 'RingGeometry':
  24037. case 'RingBufferGeometry':
  24038. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24039. break;
  24040. case 'TorusGeometry':
  24041. case 'TorusBufferGeometry':
  24042. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24043. break;
  24044. case 'TorusKnotGeometry':
  24045. case 'TorusKnotBufferGeometry':
  24046. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24047. break;
  24048. case 'TubeGeometry':
  24049. case 'TubeBufferGeometry':
  24050. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24051. // User defined curves or instances of CurvePath will not be deserialized.
  24052. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24053. break;
  24054. case 'LatheGeometry':
  24055. case 'LatheBufferGeometry':
  24056. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24057. break;
  24058. case 'PolyhedronGeometry':
  24059. case 'PolyhedronBufferGeometry':
  24060. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24061. break;
  24062. case 'ShapeGeometry':
  24063. case 'ShapeBufferGeometry':
  24064. var geometryShapes = [];
  24065. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24066. var shape = shapes[data.shapes[j]];
  24067. geometryShapes.push(shape);
  24068. }
  24069. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24070. break;
  24071. case 'ExtrudeGeometry':
  24072. case 'ExtrudeBufferGeometry':
  24073. var geometryShapes = [];
  24074. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24075. var shape = shapes[data.shapes[j]];
  24076. geometryShapes.push(shape);
  24077. }
  24078. var extrudePath = data.options.extrudePath;
  24079. if (extrudePath !== undefined) {
  24080. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24081. }
  24082. geometry = new Geometries[data.type](geometryShapes, data.options);
  24083. break;
  24084. case 'BufferGeometry':
  24085. case 'InstancedBufferGeometry':
  24086. geometry = bufferGeometryLoader.parse(data);
  24087. break;
  24088. case 'Geometry':
  24089. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  24090. break;
  24091. default:
  24092. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24093. continue;
  24094. }
  24095. geometry.uuid = data.uuid;
  24096. if (data.name !== undefined) geometry.name = data.name;
  24097. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24098. geometries[data.uuid] = geometry;
  24099. }
  24100. }
  24101. return geometries;
  24102. },
  24103. parseMaterials: function (json, textures) {
  24104. var cache = {}; // MultiMaterial
  24105. var materials = {};
  24106. if (json !== undefined) {
  24107. var loader = new MaterialLoader();
  24108. loader.setTextures(textures);
  24109. for (var i = 0, l = json.length; i < l; i++) {
  24110. var data = json[i];
  24111. if (data.type === 'MultiMaterial') {
  24112. // Deprecated
  24113. var array = [];
  24114. for (var j = 0; j < data.materials.length; j++) {
  24115. var material = data.materials[j];
  24116. if (cache[material.uuid] === undefined) {
  24117. cache[material.uuid] = loader.parse(material);
  24118. }
  24119. array.push(cache[material.uuid]);
  24120. }
  24121. materials[data.uuid] = array;
  24122. } else {
  24123. if (cache[data.uuid] === undefined) {
  24124. cache[data.uuid] = loader.parse(data);
  24125. }
  24126. materials[data.uuid] = cache[data.uuid];
  24127. }
  24128. }
  24129. }
  24130. return materials;
  24131. },
  24132. parseAnimations: function (json) {
  24133. var animations = [];
  24134. for (var i = 0; i < json.length; i++) {
  24135. var data = json[i];
  24136. var clip = AnimationClip.parse(data);
  24137. if (data.uuid !== undefined) clip.uuid = data.uuid;
  24138. animations.push(clip);
  24139. }
  24140. return animations;
  24141. },
  24142. parseImages: function (json, onLoad) {
  24143. var scope = this;
  24144. var images = {};
  24145. function loadImage(url) {
  24146. scope.manager.itemStart(url);
  24147. return loader.load(url, function () {
  24148. scope.manager.itemEnd(url);
  24149. }, undefined, function () {
  24150. scope.manager.itemError(url);
  24151. scope.manager.itemEnd(url);
  24152. });
  24153. }
  24154. if (json !== undefined && json.length > 0) {
  24155. var manager = new LoadingManager(onLoad);
  24156. var loader = new ImageLoader(manager);
  24157. loader.setCrossOrigin(this.crossOrigin);
  24158. for (var i = 0, il = json.length; i < il; i++) {
  24159. var image = json[i];
  24160. var url = image.url;
  24161. if (Array.isArray(url)) {
  24162. // load array of images e.g CubeTexture
  24163. images[image.uuid] = [];
  24164. for (var j = 0, jl = url.length; j < jl; j++) {
  24165. var currentUrl = url[j];
  24166. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  24167. images[image.uuid].push(loadImage(path));
  24168. }
  24169. } else {
  24170. // load single image
  24171. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  24172. images[image.uuid] = loadImage(path);
  24173. }
  24174. }
  24175. }
  24176. return images;
  24177. },
  24178. parseTextures: function (json, images) {
  24179. function parseConstant(value, type) {
  24180. if (typeof value === 'number') return value;
  24181. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24182. return type[value];
  24183. }
  24184. var textures = {};
  24185. if (json !== undefined) {
  24186. for (var i = 0, l = json.length; i < l; i++) {
  24187. var data = json[i];
  24188. if (data.image === undefined) {
  24189. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24190. }
  24191. if (images[data.image] === undefined) {
  24192. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24193. }
  24194. var texture;
  24195. if (Array.isArray(images[data.image])) {
  24196. texture = new CubeTexture(images[data.image]);
  24197. } else {
  24198. texture = new Texture(images[data.image]);
  24199. }
  24200. texture.needsUpdate = true;
  24201. texture.uuid = data.uuid;
  24202. if (data.name !== undefined) texture.name = data.name;
  24203. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24204. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24205. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24206. if (data.center !== undefined) texture.center.fromArray(data.center);
  24207. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24208. if (data.wrap !== undefined) {
  24209. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24210. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24211. }
  24212. if (data.format !== undefined) texture.format = data.format;
  24213. if (data.type !== undefined) texture.type = data.type;
  24214. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24215. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24216. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24217. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24218. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24219. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24220. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24221. textures[data.uuid] = texture;
  24222. }
  24223. }
  24224. return textures;
  24225. },
  24226. parseObject: function (data, geometries, materials) {
  24227. var object;
  24228. function getGeometry(name) {
  24229. if (geometries[name] === undefined) {
  24230. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24231. }
  24232. return geometries[name];
  24233. }
  24234. function getMaterial(name) {
  24235. if (name === undefined) return undefined;
  24236. if (Array.isArray(name)) {
  24237. var array = [];
  24238. for (var i = 0, l = name.length; i < l; i++) {
  24239. var uuid = name[i];
  24240. if (materials[uuid] === undefined) {
  24241. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24242. }
  24243. array.push(materials[uuid]);
  24244. }
  24245. return array;
  24246. }
  24247. if (materials[name] === undefined) {
  24248. console.warn('THREE.ObjectLoader: Undefined material', name);
  24249. }
  24250. return materials[name];
  24251. }
  24252. switch (data.type) {
  24253. case 'Scene':
  24254. object = new Scene();
  24255. if (data.background !== undefined) {
  24256. if (Number.isInteger(data.background)) {
  24257. object.background = new Color(data.background);
  24258. }
  24259. }
  24260. if (data.fog !== undefined) {
  24261. if (data.fog.type === 'Fog') {
  24262. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24263. } else if (data.fog.type === 'FogExp2') {
  24264. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24265. }
  24266. }
  24267. break;
  24268. case 'PerspectiveCamera':
  24269. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24270. if (data.focus !== undefined) object.focus = data.focus;
  24271. if (data.zoom !== undefined) object.zoom = data.zoom;
  24272. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24273. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24274. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24275. break;
  24276. case 'OrthographicCamera':
  24277. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24278. if (data.zoom !== undefined) object.zoom = data.zoom;
  24279. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24280. break;
  24281. case 'AmbientLight':
  24282. object = new AmbientLight(data.color, data.intensity);
  24283. break;
  24284. case 'DirectionalLight':
  24285. object = new DirectionalLight(data.color, data.intensity);
  24286. break;
  24287. case 'PointLight':
  24288. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24289. break;
  24290. case 'RectAreaLight':
  24291. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24292. break;
  24293. case 'SpotLight':
  24294. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24295. break;
  24296. case 'HemisphereLight':
  24297. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24298. break;
  24299. case 'SkinnedMesh':
  24300. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  24301. case 'Mesh':
  24302. var geometry = getGeometry(data.geometry);
  24303. var material = getMaterial(data.material);
  24304. object = new Mesh(geometry, material);
  24305. break;
  24306. case 'InstancedMesh':
  24307. var geometry = getGeometry(data.geometry);
  24308. var material = getMaterial(data.material);
  24309. var count = data.count;
  24310. var instanceMatrix = data.instanceMatrix;
  24311. object = new InstancedMesh(geometry, material, count);
  24312. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24313. break;
  24314. case 'LOD':
  24315. object = new LOD();
  24316. break;
  24317. case 'Line':
  24318. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  24319. break;
  24320. case 'LineLoop':
  24321. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24322. break;
  24323. case 'LineSegments':
  24324. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24325. break;
  24326. case 'PointCloud':
  24327. case 'Points':
  24328. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24329. break;
  24330. case 'Sprite':
  24331. object = new Sprite(getMaterial(data.material));
  24332. break;
  24333. case 'Group':
  24334. object = new Group();
  24335. break;
  24336. default:
  24337. object = new Object3D();
  24338. }
  24339. object.uuid = data.uuid;
  24340. if (data.name !== undefined) object.name = data.name;
  24341. if (data.matrix !== undefined) {
  24342. object.matrix.fromArray(data.matrix);
  24343. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24344. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24345. } else {
  24346. if (data.position !== undefined) object.position.fromArray(data.position);
  24347. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24348. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24349. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24350. }
  24351. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24352. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24353. if (data.shadow) {
  24354. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24355. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24356. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24357. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24358. }
  24359. if (data.visible !== undefined) object.visible = data.visible;
  24360. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24361. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24362. if (data.userData !== undefined) object.userData = data.userData;
  24363. if (data.layers !== undefined) object.layers.mask = data.layers;
  24364. if (data.children !== undefined) {
  24365. var children = data.children;
  24366. for (var i = 0; i < children.length; i++) {
  24367. object.add(this.parseObject(children[i], geometries, materials));
  24368. }
  24369. }
  24370. if (data.type === 'LOD') {
  24371. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24372. var levels = data.levels;
  24373. for (var l = 0; l < levels.length; l++) {
  24374. var level = levels[l];
  24375. var child = object.getObjectByProperty('uuid', level.object);
  24376. if (child !== undefined) {
  24377. object.addLevel(child, level.distance);
  24378. }
  24379. }
  24380. }
  24381. return object;
  24382. }
  24383. });
  24384. var TEXTURE_MAPPING = {
  24385. UVMapping: UVMapping,
  24386. CubeReflectionMapping: CubeReflectionMapping,
  24387. CubeRefractionMapping: CubeRefractionMapping,
  24388. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24389. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24390. SphericalReflectionMapping: SphericalReflectionMapping,
  24391. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24392. CubeUVRefractionMapping: CubeUVRefractionMapping
  24393. };
  24394. var TEXTURE_WRAPPING = {
  24395. RepeatWrapping: RepeatWrapping,
  24396. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24397. MirroredRepeatWrapping: MirroredRepeatWrapping
  24398. };
  24399. var TEXTURE_FILTER = {
  24400. NearestFilter: NearestFilter,
  24401. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24402. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24403. LinearFilter: LinearFilter,
  24404. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24405. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24406. };
  24407. /**
  24408. * @author thespite / http://clicktorelease.com/
  24409. */
  24410. function ImageBitmapLoader(manager) {
  24411. if (typeof createImageBitmap === 'undefined') {
  24412. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24413. }
  24414. if (typeof fetch === 'undefined') {
  24415. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24416. }
  24417. Loader.call(this, manager);
  24418. this.options = undefined;
  24419. }
  24420. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24421. constructor: ImageBitmapLoader,
  24422. setOptions: function setOptions(options) {
  24423. this.options = options;
  24424. return this;
  24425. },
  24426. load: function (url, onLoad, onProgress, onError) {
  24427. if (url === undefined) url = '';
  24428. if (this.path !== undefined) url = this.path + url;
  24429. url = this.manager.resolveURL(url);
  24430. var scope = this;
  24431. var cached = Cache.get(url);
  24432. if (cached !== undefined) {
  24433. scope.manager.itemStart(url);
  24434. setTimeout(function () {
  24435. if (onLoad) onLoad(cached);
  24436. scope.manager.itemEnd(url);
  24437. }, 0);
  24438. return cached;
  24439. }
  24440. fetch(url).then(function (res) {
  24441. return res.blob();
  24442. }).then(function (blob) {
  24443. if (scope.options === undefined) {
  24444. // Workaround for FireFox. It causes an error if you pass options.
  24445. return createImageBitmap(blob);
  24446. } else {
  24447. return createImageBitmap(blob, scope.options);
  24448. }
  24449. }).then(function (imageBitmap) {
  24450. Cache.add(url, imageBitmap);
  24451. if (onLoad) onLoad(imageBitmap);
  24452. scope.manager.itemEnd(url);
  24453. }).catch(function (e) {
  24454. if (onError) onError(e);
  24455. scope.manager.itemError(url);
  24456. scope.manager.itemEnd(url);
  24457. });
  24458. scope.manager.itemStart(url);
  24459. }
  24460. });
  24461. /**
  24462. * @author zz85 / http://www.lab4games.net/zz85/blog
  24463. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  24464. **/
  24465. function ShapePath() {
  24466. this.type = 'ShapePath';
  24467. this.color = new Color();
  24468. this.subPaths = [];
  24469. this.currentPath = null;
  24470. }
  24471. Object.assign(ShapePath.prototype, {
  24472. moveTo: function (x, y) {
  24473. this.currentPath = new Path();
  24474. this.subPaths.push(this.currentPath);
  24475. this.currentPath.moveTo(x, y);
  24476. return this;
  24477. },
  24478. lineTo: function (x, y) {
  24479. this.currentPath.lineTo(x, y);
  24480. return this;
  24481. },
  24482. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  24483. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  24484. return this;
  24485. },
  24486. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  24487. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  24488. return this;
  24489. },
  24490. splineThru: function (pts) {
  24491. this.currentPath.splineThru(pts);
  24492. return this;
  24493. },
  24494. toShapes: function (isCCW, noHoles) {
  24495. function toShapesNoHoles(inSubpaths) {
  24496. var shapes = [];
  24497. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  24498. var tmpPath = inSubpaths[i];
  24499. var tmpShape = new Shape();
  24500. tmpShape.curves = tmpPath.curves;
  24501. shapes.push(tmpShape);
  24502. }
  24503. return shapes;
  24504. }
  24505. function isPointInsidePolygon(inPt, inPolygon) {
  24506. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  24507. // toggling of inside/outside at every single! intersection point of an edge
  24508. // with the horizontal line through inPt, left of inPt
  24509. // not counting lowerY endpoints of edges and whole edges on that line
  24510. var inside = false;
  24511. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  24512. var edgeLowPt = inPolygon[p];
  24513. var edgeHighPt = inPolygon[q];
  24514. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  24515. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  24516. if (Math.abs(edgeDy) > Number.EPSILON) {
  24517. // not parallel
  24518. if (edgeDy < 0) {
  24519. edgeLowPt = inPolygon[q];
  24520. edgeDx = -edgeDx;
  24521. edgeHighPt = inPolygon[p];
  24522. edgeDy = -edgeDy;
  24523. }
  24524. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  24525. if (inPt.y === edgeLowPt.y) {
  24526. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  24527. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24528. } else {
  24529. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  24530. if (perpEdge === 0) return true; // inPt is on contour ?
  24531. if (perpEdge < 0) continue;
  24532. inside = !inside; // true intersection left of inPt
  24533. }
  24534. } else {
  24535. // parallel or collinear
  24536. if (inPt.y !== edgeLowPt.y) continue; // parallel
  24537. // edge lies on the same horizontal line as inPt
  24538. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  24539. // continue;
  24540. }
  24541. }
  24542. return inside;
  24543. }
  24544. var isClockWise = ShapeUtils.isClockWise;
  24545. var subPaths = this.subPaths;
  24546. if (subPaths.length === 0) return [];
  24547. if (noHoles === true) return toShapesNoHoles(subPaths);
  24548. var solid,
  24549. tmpPath,
  24550. tmpShape,
  24551. shapes = [];
  24552. if (subPaths.length === 1) {
  24553. tmpPath = subPaths[0];
  24554. tmpShape = new Shape();
  24555. tmpShape.curves = tmpPath.curves;
  24556. shapes.push(tmpShape);
  24557. return shapes;
  24558. }
  24559. var holesFirst = !isClockWise(subPaths[0].getPoints());
  24560. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  24561. var betterShapeHoles = [];
  24562. var newShapes = [];
  24563. var newShapeHoles = [];
  24564. var mainIdx = 0;
  24565. var tmpPoints;
  24566. newShapes[mainIdx] = undefined;
  24567. newShapeHoles[mainIdx] = [];
  24568. for (var i = 0, l = subPaths.length; i < l; i++) {
  24569. tmpPath = subPaths[i];
  24570. tmpPoints = tmpPath.getPoints();
  24571. solid = isClockWise(tmpPoints);
  24572. solid = isCCW ? !solid : solid;
  24573. if (solid) {
  24574. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  24575. newShapes[mainIdx] = {
  24576. s: new Shape(),
  24577. p: tmpPoints
  24578. };
  24579. newShapes[mainIdx].s.curves = tmpPath.curves;
  24580. if (holesFirst) mainIdx++;
  24581. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  24582. } else {
  24583. newShapeHoles[mainIdx].push({
  24584. h: tmpPath,
  24585. p: tmpPoints[0]
  24586. }); //console.log('ccw', i);
  24587. }
  24588. } // only Holes? -> probably all Shapes with wrong orientation
  24589. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  24590. if (newShapes.length > 1) {
  24591. var ambiguous = false;
  24592. var toChange = [];
  24593. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24594. betterShapeHoles[sIdx] = [];
  24595. }
  24596. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24597. var sho = newShapeHoles[sIdx];
  24598. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  24599. var ho = sho[hIdx];
  24600. var hole_unassigned = true;
  24601. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  24602. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  24603. if (sIdx !== s2Idx) toChange.push({
  24604. froms: sIdx,
  24605. tos: s2Idx,
  24606. hole: hIdx
  24607. });
  24608. if (hole_unassigned) {
  24609. hole_unassigned = false;
  24610. betterShapeHoles[s2Idx].push(ho);
  24611. } else {
  24612. ambiguous = true;
  24613. }
  24614. }
  24615. }
  24616. if (hole_unassigned) {
  24617. betterShapeHoles[sIdx].push(ho);
  24618. }
  24619. }
  24620. } // console.log("ambiguous: ", ambiguous);
  24621. if (toChange.length > 0) {
  24622. // console.log("to change: ", toChange);
  24623. if (!ambiguous) newShapeHoles = betterShapeHoles;
  24624. }
  24625. }
  24626. var tmpHoles;
  24627. for (var i = 0, il = newShapes.length; i < il; i++) {
  24628. tmpShape = newShapes[i].s;
  24629. shapes.push(tmpShape);
  24630. tmpHoles = newShapeHoles[i];
  24631. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  24632. tmpShape.holes.push(tmpHoles[j].h);
  24633. }
  24634. } //console.log("shape", shapes);
  24635. return shapes;
  24636. }
  24637. });
  24638. /**
  24639. * @author zz85 / http://www.lab4games.net/zz85/blog
  24640. * @author mrdoob / http://mrdoob.com/
  24641. */
  24642. function Font(data) {
  24643. this.type = 'Font';
  24644. this.data = data;
  24645. }
  24646. Object.assign(Font.prototype, {
  24647. isFont: true,
  24648. generateShapes: function (text, size) {
  24649. if (size === undefined) size = 100;
  24650. var shapes = [];
  24651. var paths = createPaths(text, size, this.data);
  24652. for (var p = 0, pl = paths.length; p < pl; p++) {
  24653. Array.prototype.push.apply(shapes, paths[p].toShapes());
  24654. }
  24655. return shapes;
  24656. }
  24657. });
  24658. function createPaths(text, size, data) {
  24659. var chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
  24660. var scale = size / data.resolution;
  24661. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  24662. var paths = [];
  24663. var offsetX = 0,
  24664. offsetY = 0;
  24665. for (var i = 0; i < chars.length; i++) {
  24666. var char = chars[i];
  24667. if (char === '\n') {
  24668. offsetX = 0;
  24669. offsetY -= line_height;
  24670. } else {
  24671. var ret = createPath(char, scale, offsetX, offsetY, data);
  24672. offsetX += ret.offsetX;
  24673. paths.push(ret.path);
  24674. }
  24675. }
  24676. return paths;
  24677. }
  24678. function createPath(char, scale, offsetX, offsetY, data) {
  24679. var glyph = data.glyphs[char] || data.glyphs['?'];
  24680. if (!glyph) {
  24681. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  24682. return;
  24683. }
  24684. var path = new ShapePath();
  24685. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  24686. if (glyph.o) {
  24687. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  24688. for (var i = 0, l = outline.length; i < l;) {
  24689. var action = outline[i++];
  24690. switch (action) {
  24691. case 'm':
  24692. // moveTo
  24693. x = outline[i++] * scale + offsetX;
  24694. y = outline[i++] * scale + offsetY;
  24695. path.moveTo(x, y);
  24696. break;
  24697. case 'l':
  24698. // lineTo
  24699. x = outline[i++] * scale + offsetX;
  24700. y = outline[i++] * scale + offsetY;
  24701. path.lineTo(x, y);
  24702. break;
  24703. case 'q':
  24704. // quadraticCurveTo
  24705. cpx = outline[i++] * scale + offsetX;
  24706. cpy = outline[i++] * scale + offsetY;
  24707. cpx1 = outline[i++] * scale + offsetX;
  24708. cpy1 = outline[i++] * scale + offsetY;
  24709. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  24710. break;
  24711. case 'b':
  24712. // bezierCurveTo
  24713. cpx = outline[i++] * scale + offsetX;
  24714. cpy = outline[i++] * scale + offsetY;
  24715. cpx1 = outline[i++] * scale + offsetX;
  24716. cpy1 = outline[i++] * scale + offsetY;
  24717. cpx2 = outline[i++] * scale + offsetX;
  24718. cpy2 = outline[i++] * scale + offsetY;
  24719. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  24720. break;
  24721. }
  24722. }
  24723. }
  24724. return {
  24725. offsetX: glyph.ha * scale,
  24726. path: path
  24727. };
  24728. }
  24729. /**
  24730. * @author mrdoob / http://mrdoob.com/
  24731. */
  24732. function FontLoader(manager) {
  24733. Loader.call(this, manager);
  24734. }
  24735. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24736. constructor: FontLoader,
  24737. load: function (url, onLoad, onProgress, onError) {
  24738. var scope = this;
  24739. var loader = new FileLoader(this.manager);
  24740. loader.setPath(this.path);
  24741. loader.load(url, function (text) {
  24742. var json;
  24743. try {
  24744. json = JSON.parse(text);
  24745. } catch (e) {
  24746. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  24747. json = JSON.parse(text.substring(65, text.length - 2));
  24748. }
  24749. var font = scope.parse(json);
  24750. if (onLoad) onLoad(font);
  24751. }, onProgress, onError);
  24752. },
  24753. parse: function (json) {
  24754. return new Font(json);
  24755. }
  24756. });
  24757. /**
  24758. * @author mrdoob / http://mrdoob.com/
  24759. */
  24760. var _context;
  24761. var AudioContext = {
  24762. getContext: function () {
  24763. if (_context === undefined) {
  24764. _context = new (window.AudioContext || window.webkitAudioContext)();
  24765. }
  24766. return _context;
  24767. },
  24768. setContext: function (value) {
  24769. _context = value;
  24770. }
  24771. };
  24772. /**
  24773. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  24774. */
  24775. exports.AudioContext = AudioContext;
  24776. function AudioLoader(manager) {
  24777. Loader.call(this, manager);
  24778. }
  24779. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24780. constructor: AudioLoader,
  24781. load: function (url, onLoad, onProgress, onError) {
  24782. var loader = new FileLoader(this.manager);
  24783. loader.setResponseType('arraybuffer');
  24784. loader.setPath(this.path);
  24785. loader.load(url, function (buffer) {
  24786. // Create a copy of the buffer. The `decodeAudioData` method
  24787. // detaches the buffer when complete, preventing reuse.
  24788. var bufferCopy = buffer.slice(0);
  24789. var context = AudioContext.getContext();
  24790. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24791. onLoad(audioBuffer);
  24792. });
  24793. }, onProgress, onError);
  24794. }
  24795. });
  24796. /**
  24797. * @author bhouston / http://clara.io
  24798. * @author WestLangley / http://github.com/WestLangley
  24799. *
  24800. * Primary reference:
  24801. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24802. *
  24803. * Secondary reference:
  24804. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24805. */
  24806. // 3-band SH defined by 9 coefficients
  24807. function SphericalHarmonics3() {
  24808. this.coefficients = [];
  24809. for (var i = 0; i < 9; i++) {
  24810. this.coefficients.push(new Vector3());
  24811. }
  24812. }
  24813. Object.assign(SphericalHarmonics3.prototype, {
  24814. isSphericalHarmonics3: true,
  24815. set: function (coefficients) {
  24816. for (var i = 0; i < 9; i++) {
  24817. this.coefficients[i].copy(coefficients[i]);
  24818. }
  24819. return this;
  24820. },
  24821. zero: function () {
  24822. for (var i = 0; i < 9; i++) {
  24823. this.coefficients[i].set(0, 0, 0);
  24824. }
  24825. return this;
  24826. },
  24827. // get the radiance in the direction of the normal
  24828. // target is a Vector3
  24829. getAt: function (normal, target) {
  24830. // normal is assumed to be unit length
  24831. var x = normal.x,
  24832. y = normal.y,
  24833. z = normal.z;
  24834. var coeff = this.coefficients; // band 0
  24835. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  24836. target.addScaledVector(coeff[1], 0.488603 * y);
  24837. target.addScaledVector(coeff[2], 0.488603 * z);
  24838. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  24839. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  24840. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  24841. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  24842. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  24843. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  24844. return target;
  24845. },
  24846. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24847. // target is a Vector3
  24848. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24849. getIrradianceAt: function (normal, target) {
  24850. // normal is assumed to be unit length
  24851. var x = normal.x,
  24852. y = normal.y,
  24853. z = normal.z;
  24854. var coeff = this.coefficients; // band 0
  24855. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  24856. // band 1
  24857. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  24858. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  24859. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  24860. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  24861. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  24862. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  24863. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  24864. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  24865. return target;
  24866. },
  24867. add: function (sh) {
  24868. for (var i = 0; i < 9; i++) {
  24869. this.coefficients[i].add(sh.coefficients[i]);
  24870. }
  24871. return this;
  24872. },
  24873. addScaledSH: function (sh, s) {
  24874. for (var i = 0; i < 9; i++) {
  24875. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  24876. }
  24877. return this;
  24878. },
  24879. scale: function (s) {
  24880. for (var i = 0; i < 9; i++) {
  24881. this.coefficients[i].multiplyScalar(s);
  24882. }
  24883. return this;
  24884. },
  24885. lerp: function (sh, alpha) {
  24886. for (var i = 0; i < 9; i++) {
  24887. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24888. }
  24889. return this;
  24890. },
  24891. equals: function (sh) {
  24892. for (var i = 0; i < 9; i++) {
  24893. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24894. return false;
  24895. }
  24896. }
  24897. return true;
  24898. },
  24899. copy: function (sh) {
  24900. return this.set(sh.coefficients);
  24901. },
  24902. clone: function () {
  24903. return new this.constructor().copy(this);
  24904. },
  24905. fromArray: function (array, offset) {
  24906. if (offset === undefined) offset = 0;
  24907. var coefficients = this.coefficients;
  24908. for (var i = 0; i < 9; i++) {
  24909. coefficients[i].fromArray(array, offset + i * 3);
  24910. }
  24911. return this;
  24912. },
  24913. toArray: function (array, offset) {
  24914. if (array === undefined) array = [];
  24915. if (offset === undefined) offset = 0;
  24916. var coefficients = this.coefficients;
  24917. for (var i = 0; i < 9; i++) {
  24918. coefficients[i].toArray(array, offset + i * 3);
  24919. }
  24920. return array;
  24921. }
  24922. });
  24923. Object.assign(SphericalHarmonics3, {
  24924. // evaluate the basis functions
  24925. // shBasis is an Array[ 9 ]
  24926. getBasisAt: function (normal, shBasis) {
  24927. // normal is assumed to be unit length
  24928. var x = normal.x,
  24929. y = normal.y,
  24930. z = normal.z; // band 0
  24931. shBasis[0] = 0.282095; // band 1
  24932. shBasis[1] = 0.488603 * y;
  24933. shBasis[2] = 0.488603 * z;
  24934. shBasis[3] = 0.488603 * x; // band 2
  24935. shBasis[4] = 1.092548 * x * y;
  24936. shBasis[5] = 1.092548 * y * z;
  24937. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24938. shBasis[7] = 1.092548 * x * z;
  24939. shBasis[8] = 0.546274 * (x * x - y * y);
  24940. }
  24941. });
  24942. /**
  24943. * @author WestLangley / http://github.com/WestLangley
  24944. *
  24945. * A LightProbe is a source of indirect-diffuse light
  24946. */
  24947. function LightProbe(sh, intensity) {
  24948. Light.call(this, undefined, intensity);
  24949. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  24950. }
  24951. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  24952. constructor: LightProbe,
  24953. isLightProbe: true,
  24954. copy: function (source) {
  24955. Light.prototype.copy.call(this, source);
  24956. this.sh.copy(source.sh);
  24957. this.intensity = source.intensity;
  24958. return this;
  24959. },
  24960. toJSON: function (meta) {
  24961. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24962. return data;
  24963. }
  24964. });
  24965. /**
  24966. * @author WestLangley / http://github.com/WestLangley
  24967. */
  24968. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  24969. LightProbe.call(this, undefined, intensity);
  24970. var color1 = new Color().set(skyColor);
  24971. var color2 = new Color().set(groundColor);
  24972. var sky = new Vector3(color1.r, color1.g, color1.b);
  24973. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24974. var c0 = Math.sqrt(Math.PI);
  24975. var c1 = c0 * Math.sqrt(0.75);
  24976. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24977. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24978. }
  24979. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  24980. constructor: HemisphereLightProbe,
  24981. isHemisphereLightProbe: true,
  24982. copy: function (source) {
  24983. // modifying colors not currently supported
  24984. LightProbe.prototype.copy.call(this, source);
  24985. return this;
  24986. },
  24987. toJSON: function (meta) {
  24988. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24989. return data;
  24990. }
  24991. });
  24992. /**
  24993. * @author WestLangley / http://github.com/WestLangley
  24994. */
  24995. function AmbientLightProbe(color, intensity) {
  24996. LightProbe.call(this, undefined, intensity);
  24997. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24998. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24999. }
  25000. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25001. constructor: AmbientLightProbe,
  25002. isAmbientLightProbe: true,
  25003. copy: function (source) {
  25004. // modifying color not currently supported
  25005. LightProbe.prototype.copy.call(this, source);
  25006. return this;
  25007. },
  25008. toJSON: function (meta) {
  25009. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25010. return data;
  25011. }
  25012. });
  25013. var _eyeRight = new Matrix4();
  25014. var _eyeLeft = new Matrix4();
  25015. /**
  25016. * @author mrdoob / http://mrdoob.com/
  25017. */
  25018. function StereoCamera() {
  25019. this.type = 'StereoCamera';
  25020. this.aspect = 1;
  25021. this.eyeSep = 0.064;
  25022. this.cameraL = new PerspectiveCamera();
  25023. this.cameraL.layers.enable(1);
  25024. this.cameraL.matrixAutoUpdate = false;
  25025. this.cameraR = new PerspectiveCamera();
  25026. this.cameraR.layers.enable(2);
  25027. this.cameraR.matrixAutoUpdate = false;
  25028. this._cache = {
  25029. focus: null,
  25030. fov: null,
  25031. aspect: null,
  25032. near: null,
  25033. far: null,
  25034. zoom: null,
  25035. eyeSep: null
  25036. };
  25037. }
  25038. Object.assign(StereoCamera.prototype, {
  25039. update: function (camera) {
  25040. var cache = this._cache;
  25041. 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;
  25042. if (needsUpdate) {
  25043. cache.focus = camera.focus;
  25044. cache.fov = camera.fov;
  25045. cache.aspect = camera.aspect * this.aspect;
  25046. cache.near = camera.near;
  25047. cache.far = camera.far;
  25048. cache.zoom = camera.zoom;
  25049. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25050. // http://paulbourke.net/stereographics/stereorender/
  25051. var projectionMatrix = camera.projectionMatrix.clone();
  25052. var eyeSepHalf = cache.eyeSep / 2;
  25053. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25054. var ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25055. var xmin, xmax; // translate xOffset
  25056. _eyeLeft.elements[12] = -eyeSepHalf;
  25057. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25058. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25059. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25060. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25061. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25062. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25063. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25064. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25065. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25066. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25067. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25068. }
  25069. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25070. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25071. }
  25072. });
  25073. /**
  25074. * @author alteredq / http://alteredqualia.com/
  25075. */
  25076. function Clock(autoStart) {
  25077. this.autoStart = autoStart !== undefined ? autoStart : true;
  25078. this.startTime = 0;
  25079. this.oldTime = 0;
  25080. this.elapsedTime = 0;
  25081. this.running = false;
  25082. }
  25083. Object.assign(Clock.prototype, {
  25084. start: function () {
  25085. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25086. this.oldTime = this.startTime;
  25087. this.elapsedTime = 0;
  25088. this.running = true;
  25089. },
  25090. stop: function () {
  25091. this.getElapsedTime();
  25092. this.running = false;
  25093. this.autoStart = false;
  25094. },
  25095. getElapsedTime: function () {
  25096. this.getDelta();
  25097. return this.elapsedTime;
  25098. },
  25099. getDelta: function () {
  25100. var diff = 0;
  25101. if (this.autoStart && !this.running) {
  25102. this.start();
  25103. return 0;
  25104. }
  25105. if (this.running) {
  25106. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  25107. diff = (newTime - this.oldTime) / 1000;
  25108. this.oldTime = newTime;
  25109. this.elapsedTime += diff;
  25110. }
  25111. return diff;
  25112. }
  25113. });
  25114. /**
  25115. * @author mrdoob / http://mrdoob.com/
  25116. */
  25117. var _position$2 = new Vector3();
  25118. var _quaternion$3 = new Quaternion();
  25119. var _scale$1 = new Vector3();
  25120. var _orientation = new Vector3();
  25121. function AudioListener() {
  25122. Object3D.call(this);
  25123. this.type = 'AudioListener';
  25124. this.context = AudioContext.getContext();
  25125. this.gain = this.context.createGain();
  25126. this.gain.connect(this.context.destination);
  25127. this.filter = null;
  25128. this.timeDelta = 0; // private
  25129. this._clock = new Clock();
  25130. }
  25131. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  25132. constructor: AudioListener,
  25133. getInput: function () {
  25134. return this.gain;
  25135. },
  25136. removeFilter: function () {
  25137. if (this.filter !== null) {
  25138. this.gain.disconnect(this.filter);
  25139. this.filter.disconnect(this.context.destination);
  25140. this.gain.connect(this.context.destination);
  25141. this.filter = null;
  25142. }
  25143. return this;
  25144. },
  25145. getFilter: function () {
  25146. return this.filter;
  25147. },
  25148. setFilter: function (value) {
  25149. if (this.filter !== null) {
  25150. this.gain.disconnect(this.filter);
  25151. this.filter.disconnect(this.context.destination);
  25152. } else {
  25153. this.gain.disconnect(this.context.destination);
  25154. }
  25155. this.filter = value;
  25156. this.gain.connect(this.filter);
  25157. this.filter.connect(this.context.destination);
  25158. return this;
  25159. },
  25160. getMasterVolume: function () {
  25161. return this.gain.gain.value;
  25162. },
  25163. setMasterVolume: function (value) {
  25164. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25165. return this;
  25166. },
  25167. updateMatrixWorld: function (force) {
  25168. Object3D.prototype.updateMatrixWorld.call(this, force);
  25169. var listener = this.context.listener;
  25170. var up = this.up;
  25171. this.timeDelta = this._clock.getDelta();
  25172. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25173. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25174. if (listener.positionX) {
  25175. // code path for Chrome (see #14393)
  25176. var endTime = this.context.currentTime + this.timeDelta;
  25177. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25178. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25179. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25180. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25181. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25182. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25183. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25184. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25185. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25186. } else {
  25187. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25188. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25189. }
  25190. }
  25191. });
  25192. /**
  25193. * @author mrdoob / http://mrdoob.com/
  25194. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25195. */
  25196. function Audio(listener) {
  25197. Object3D.call(this);
  25198. this.type = 'Audio';
  25199. this.listener = listener;
  25200. this.context = listener.context;
  25201. this.gain = this.context.createGain();
  25202. this.gain.connect(listener.getInput());
  25203. this.autoplay = false;
  25204. this.buffer = null;
  25205. this.detune = 0;
  25206. this.loop = false;
  25207. this.loopStart = 0;
  25208. this.loopEnd = 0;
  25209. this.offset = 0;
  25210. this.duration = undefined;
  25211. this.playbackRate = 1;
  25212. this.isPlaying = false;
  25213. this.hasPlaybackControl = true;
  25214. this.sourceType = 'empty';
  25215. this._startedAt = 0;
  25216. this._pausedAt = 0;
  25217. this.filters = [];
  25218. }
  25219. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  25220. constructor: Audio,
  25221. getOutput: function () {
  25222. return this.gain;
  25223. },
  25224. setNodeSource: function (audioNode) {
  25225. this.hasPlaybackControl = false;
  25226. this.sourceType = 'audioNode';
  25227. this.source = audioNode;
  25228. this.connect();
  25229. return this;
  25230. },
  25231. setMediaElementSource: function (mediaElement) {
  25232. this.hasPlaybackControl = false;
  25233. this.sourceType = 'mediaNode';
  25234. this.source = this.context.createMediaElementSource(mediaElement);
  25235. this.connect();
  25236. return this;
  25237. },
  25238. setMediaStreamSource: function (mediaStream) {
  25239. this.hasPlaybackControl = false;
  25240. this.sourceType = 'mediaStreamNode';
  25241. this.source = this.context.createMediaStreamSource(mediaStream);
  25242. this.connect();
  25243. return this;
  25244. },
  25245. setBuffer: function (audioBuffer) {
  25246. this.buffer = audioBuffer;
  25247. this.sourceType = 'buffer';
  25248. if (this.autoplay) this.play();
  25249. return this;
  25250. },
  25251. play: function (delay) {
  25252. if (delay === undefined) delay = 0;
  25253. if (this.isPlaying === true) {
  25254. console.warn('THREE.Audio: Audio is already playing.');
  25255. return;
  25256. }
  25257. if (this.hasPlaybackControl === false) {
  25258. console.warn('THREE.Audio: this Audio has no playback control.');
  25259. return;
  25260. }
  25261. this._startedAt = this.context.currentTime + delay;
  25262. var source = this.context.createBufferSource();
  25263. source.buffer = this.buffer;
  25264. source.loop = this.loop;
  25265. source.loopStart = this.loopStart;
  25266. source.loopEnd = this.loopEnd;
  25267. source.onended = this.onEnded.bind(this);
  25268. source.start(this._startedAt, this._pausedAt + this.offset, this.duration);
  25269. this.isPlaying = true;
  25270. this.source = source;
  25271. this.setDetune(this.detune);
  25272. this.setPlaybackRate(this.playbackRate);
  25273. return this.connect();
  25274. },
  25275. pause: function () {
  25276. if (this.hasPlaybackControl === false) {
  25277. console.warn('THREE.Audio: this Audio has no playback control.');
  25278. return;
  25279. }
  25280. if (this.isPlaying === true) {
  25281. this._pausedAt += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25282. this.source.stop();
  25283. this.source.onended = null;
  25284. this.isPlaying = false;
  25285. }
  25286. return this;
  25287. },
  25288. stop: function () {
  25289. if (this.hasPlaybackControl === false) {
  25290. console.warn('THREE.Audio: this Audio has no playback control.');
  25291. return;
  25292. }
  25293. this._pausedAt = 0;
  25294. this.source.stop();
  25295. this.source.onended = null;
  25296. this.isPlaying = false;
  25297. return this;
  25298. },
  25299. connect: function () {
  25300. if (this.filters.length > 0) {
  25301. this.source.connect(this.filters[0]);
  25302. for (var i = 1, l = this.filters.length; i < l; i++) {
  25303. this.filters[i - 1].connect(this.filters[i]);
  25304. }
  25305. this.filters[this.filters.length - 1].connect(this.getOutput());
  25306. } else {
  25307. this.source.connect(this.getOutput());
  25308. }
  25309. return this;
  25310. },
  25311. disconnect: function () {
  25312. if (this.filters.length > 0) {
  25313. this.source.disconnect(this.filters[0]);
  25314. for (var i = 1, l = this.filters.length; i < l; i++) {
  25315. this.filters[i - 1].disconnect(this.filters[i]);
  25316. }
  25317. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25318. } else {
  25319. this.source.disconnect(this.getOutput());
  25320. }
  25321. return this;
  25322. },
  25323. getFilters: function () {
  25324. return this.filters;
  25325. },
  25326. setFilters: function (value) {
  25327. if (!value) value = [];
  25328. if (this.isPlaying === true) {
  25329. this.disconnect();
  25330. this.filters = value;
  25331. this.connect();
  25332. } else {
  25333. this.filters = value;
  25334. }
  25335. return this;
  25336. },
  25337. setDetune: function (value) {
  25338. this.detune = value;
  25339. if (this.source.detune === undefined) return; // only set detune when available
  25340. if (this.isPlaying === true) {
  25341. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25342. }
  25343. return this;
  25344. },
  25345. getDetune: function () {
  25346. return this.detune;
  25347. },
  25348. getFilter: function () {
  25349. return this.getFilters()[0];
  25350. },
  25351. setFilter: function (filter) {
  25352. return this.setFilters(filter ? [filter] : []);
  25353. },
  25354. setPlaybackRate: function (value) {
  25355. if (this.hasPlaybackControl === false) {
  25356. console.warn('THREE.Audio: this Audio has no playback control.');
  25357. return;
  25358. }
  25359. this.playbackRate = value;
  25360. if (this.isPlaying === true) {
  25361. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25362. }
  25363. return this;
  25364. },
  25365. getPlaybackRate: function () {
  25366. return this.playbackRate;
  25367. },
  25368. onEnded: function () {
  25369. this.isPlaying = false;
  25370. },
  25371. getLoop: function () {
  25372. if (this.hasPlaybackControl === false) {
  25373. console.warn('THREE.Audio: this Audio has no playback control.');
  25374. return false;
  25375. }
  25376. return this.loop;
  25377. },
  25378. setLoop: function (value) {
  25379. if (this.hasPlaybackControl === false) {
  25380. console.warn('THREE.Audio: this Audio has no playback control.');
  25381. return;
  25382. }
  25383. this.loop = value;
  25384. if (this.isPlaying === true) {
  25385. this.source.loop = this.loop;
  25386. }
  25387. return this;
  25388. },
  25389. setLoopStart: function (value) {
  25390. this.loopStart = value;
  25391. return this;
  25392. },
  25393. setLoopEnd: function (value) {
  25394. this.loopEnd = value;
  25395. return this;
  25396. },
  25397. getVolume: function () {
  25398. return this.gain.gain.value;
  25399. },
  25400. setVolume: function (value) {
  25401. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25402. return this;
  25403. }
  25404. });
  25405. /**
  25406. * @author mrdoob / http://mrdoob.com/
  25407. */
  25408. var _position$3 = new Vector3();
  25409. var _quaternion$4 = new Quaternion();
  25410. var _scale$2 = new Vector3();
  25411. var _orientation$1 = new Vector3();
  25412. function PositionalAudio(listener) {
  25413. Audio.call(this, listener);
  25414. this.panner = this.context.createPanner();
  25415. this.panner.panningModel = 'HRTF';
  25416. this.panner.connect(this.gain);
  25417. }
  25418. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  25419. constructor: PositionalAudio,
  25420. getOutput: function () {
  25421. return this.panner;
  25422. },
  25423. getRefDistance: function () {
  25424. return this.panner.refDistance;
  25425. },
  25426. setRefDistance: function (value) {
  25427. this.panner.refDistance = value;
  25428. return this;
  25429. },
  25430. getRolloffFactor: function () {
  25431. return this.panner.rolloffFactor;
  25432. },
  25433. setRolloffFactor: function (value) {
  25434. this.panner.rolloffFactor = value;
  25435. return this;
  25436. },
  25437. getDistanceModel: function () {
  25438. return this.panner.distanceModel;
  25439. },
  25440. setDistanceModel: function (value) {
  25441. this.panner.distanceModel = value;
  25442. return this;
  25443. },
  25444. getMaxDistance: function () {
  25445. return this.panner.maxDistance;
  25446. },
  25447. setMaxDistance: function (value) {
  25448. this.panner.maxDistance = value;
  25449. return this;
  25450. },
  25451. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25452. this.panner.coneInnerAngle = coneInnerAngle;
  25453. this.panner.coneOuterAngle = coneOuterAngle;
  25454. this.panner.coneOuterGain = coneOuterGain;
  25455. return this;
  25456. },
  25457. updateMatrixWorld: function (force) {
  25458. Object3D.prototype.updateMatrixWorld.call(this, force);
  25459. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25460. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  25461. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  25462. var panner = this.panner;
  25463. if (panner.positionX) {
  25464. // code path for Chrome and Firefox (see #14393)
  25465. var endTime = this.context.currentTime + this.listener.timeDelta;
  25466. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  25467. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  25468. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  25469. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25470. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25471. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25472. } else {
  25473. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  25474. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  25475. }
  25476. }
  25477. });
  25478. /**
  25479. * @author mrdoob / http://mrdoob.com/
  25480. */
  25481. function AudioAnalyser(audio, fftSize) {
  25482. this.analyser = audio.context.createAnalyser();
  25483. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  25484. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25485. audio.getOutput().connect(this.analyser);
  25486. }
  25487. Object.assign(AudioAnalyser.prototype, {
  25488. getFrequencyData: function () {
  25489. this.analyser.getByteFrequencyData(this.data);
  25490. return this.data;
  25491. },
  25492. getAverageFrequency: function () {
  25493. var value = 0,
  25494. data = this.getFrequencyData();
  25495. for (var i = 0; i < data.length; i++) {
  25496. value += data[i];
  25497. }
  25498. return value / data.length;
  25499. }
  25500. });
  25501. /**
  25502. *
  25503. * Buffered scene graph property that allows weighted accumulation.
  25504. *
  25505. *
  25506. * @author Ben Houston / http://clara.io/
  25507. * @author David Sarno / http://lighthaus.us/
  25508. * @author tschw
  25509. */
  25510. function PropertyMixer(binding, typeName, valueSize) {
  25511. this.binding = binding;
  25512. this.valueSize = valueSize;
  25513. var bufferType = Float64Array,
  25514. mixFunction;
  25515. switch (typeName) {
  25516. case 'quaternion':
  25517. mixFunction = this._slerp;
  25518. break;
  25519. case 'string':
  25520. case 'bool':
  25521. bufferType = Array;
  25522. mixFunction = this._select;
  25523. break;
  25524. default:
  25525. mixFunction = this._lerp;
  25526. }
  25527. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  25528. //
  25529. // interpolators can use .buffer as their .result
  25530. // the data then goes to 'incoming'
  25531. //
  25532. // 'accu0' and 'accu1' are used frame-interleaved for
  25533. // the cumulative result and are compared to detect
  25534. // changes
  25535. //
  25536. // 'orig' stores the original state of the property
  25537. this._mixBufferRegion = mixFunction;
  25538. this.cumulativeWeight = 0;
  25539. this.useCount = 0;
  25540. this.referenceCount = 0;
  25541. }
  25542. Object.assign(PropertyMixer.prototype, {
  25543. // accumulate data in the 'incoming' region into 'accu<i>'
  25544. accumulate: function (accuIndex, weight) {
  25545. // note: happily accumulating nothing when weight = 0, the caller knows
  25546. // the weight and shouldn't have made the call in the first place
  25547. var buffer = this.buffer,
  25548. stride = this.valueSize,
  25549. offset = accuIndex * stride + stride,
  25550. currentWeight = this.cumulativeWeight;
  25551. if (currentWeight === 0) {
  25552. // accuN := incoming * weight
  25553. for (var i = 0; i !== stride; ++i) {
  25554. buffer[offset + i] = buffer[i];
  25555. }
  25556. currentWeight = weight;
  25557. } else {
  25558. // accuN := accuN + incoming * weight
  25559. currentWeight += weight;
  25560. var mix = weight / currentWeight;
  25561. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25562. }
  25563. this.cumulativeWeight = currentWeight;
  25564. },
  25565. // apply the state of 'accu<i>' to the binding when accus differ
  25566. apply: function (accuIndex) {
  25567. var stride = this.valueSize,
  25568. buffer = this.buffer,
  25569. offset = accuIndex * stride + stride,
  25570. weight = this.cumulativeWeight,
  25571. binding = this.binding;
  25572. this.cumulativeWeight = 0;
  25573. if (weight < 1) {
  25574. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25575. var originalValueOffset = stride * 3;
  25576. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25577. }
  25578. for (var i = stride, e = stride + stride; i !== e; ++i) {
  25579. if (buffer[i] !== buffer[i + stride]) {
  25580. // value has changed -> update scene graph
  25581. binding.setValue(buffer, offset);
  25582. break;
  25583. }
  25584. }
  25585. },
  25586. // remember the state of the bound property and copy it to both accus
  25587. saveOriginalState: function () {
  25588. var binding = this.binding;
  25589. var buffer = this.buffer,
  25590. stride = this.valueSize,
  25591. originalValueOffset = stride * 3;
  25592. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25593. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  25594. buffer[i] = buffer[originalValueOffset + i % stride];
  25595. }
  25596. this.cumulativeWeight = 0;
  25597. },
  25598. // apply the state previously taken via 'saveOriginalState' to the binding
  25599. restoreOriginalState: function () {
  25600. var originalValueOffset = this.valueSize * 3;
  25601. this.binding.setValue(this.buffer, originalValueOffset);
  25602. },
  25603. // mix functions
  25604. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  25605. if (t >= 0.5) {
  25606. for (var i = 0; i !== stride; ++i) {
  25607. buffer[dstOffset + i] = buffer[srcOffset + i];
  25608. }
  25609. }
  25610. },
  25611. _slerp: function (buffer, dstOffset, srcOffset, t) {
  25612. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25613. },
  25614. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  25615. var s = 1 - t;
  25616. for (var i = 0; i !== stride; ++i) {
  25617. var j = dstOffset + i;
  25618. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25619. }
  25620. }
  25621. });
  25622. /**
  25623. *
  25624. * A reference to a real property in the scene graph.
  25625. *
  25626. *
  25627. * @author Ben Houston / http://clara.io/
  25628. * @author David Sarno / http://lighthaus.us/
  25629. * @author tschw
  25630. */
  25631. // Characters [].:/ are reserved for track binding syntax.
  25632. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25633. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25634. // only latin characters, and the unicode \p{L} is not yet supported. So
  25635. // instead, we exclude reserved characters and match everything else.
  25636. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25637. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25638. // be matched to parse the rest of the track name.
  25639. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25640. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25641. // characters. Accessor may contain any character except closing bracket.
  25642. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25643. // contain any non-bracket characters.
  25644. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25645. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25646. var _supportedObjectNames = ['material', 'materials', 'bones'];
  25647. function Composite(targetGroup, path, optionalParsedPath) {
  25648. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25649. this._targetGroup = targetGroup;
  25650. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25651. }
  25652. Object.assign(Composite.prototype, {
  25653. getValue: function (array, offset) {
  25654. this.bind(); // bind all binding
  25655. var firstValidIndex = this._targetGroup.nCachedObjects_,
  25656. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25657. if (binding !== undefined) binding.getValue(array, offset);
  25658. },
  25659. setValue: function (array, offset) {
  25660. var bindings = this._bindings;
  25661. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25662. bindings[i].setValue(array, offset);
  25663. }
  25664. },
  25665. bind: function () {
  25666. var bindings = this._bindings;
  25667. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25668. bindings[i].bind();
  25669. }
  25670. },
  25671. unbind: function () {
  25672. var bindings = this._bindings;
  25673. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25674. bindings[i].unbind();
  25675. }
  25676. }
  25677. });
  25678. function PropertyBinding(rootNode, path, parsedPath) {
  25679. this.path = path;
  25680. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25681. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25682. this.rootNode = rootNode;
  25683. }
  25684. Object.assign(PropertyBinding, {
  25685. Composite: Composite,
  25686. create: function (root, path, parsedPath) {
  25687. if (!(root && root.isAnimationObjectGroup)) {
  25688. return new PropertyBinding(root, path, parsedPath);
  25689. } else {
  25690. return new PropertyBinding.Composite(root, path, parsedPath);
  25691. }
  25692. },
  25693. /**
  25694. * Replaces spaces with underscores and removes unsupported characters from
  25695. * node names, to ensure compatibility with parseTrackName().
  25696. *
  25697. * @param {string} name Node name to be sanitized.
  25698. * @return {string}
  25699. */
  25700. sanitizeNodeName: function (name) {
  25701. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25702. },
  25703. parseTrackName: function (trackName) {
  25704. var matches = _trackRe.exec(trackName);
  25705. if (!matches) {
  25706. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25707. }
  25708. var results = {
  25709. // directoryName: matches[ 1 ], // (tschw) currently unused
  25710. nodeName: matches[2],
  25711. objectName: matches[3],
  25712. objectIndex: matches[4],
  25713. propertyName: matches[5],
  25714. // required
  25715. propertyIndex: matches[6]
  25716. };
  25717. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25718. if (lastDot !== undefined && lastDot !== -1) {
  25719. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  25720. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25721. // 'bar' could be the objectName, or part of a nodeName (which can
  25722. // include '.' characters).
  25723. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25724. results.nodeName = results.nodeName.substring(0, lastDot);
  25725. results.objectName = objectName;
  25726. }
  25727. }
  25728. if (results.propertyName === null || results.propertyName.length === 0) {
  25729. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25730. }
  25731. return results;
  25732. },
  25733. findNode: function (root, nodeName) {
  25734. if (!nodeName || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25735. return root;
  25736. } // search into skeleton bones.
  25737. if (root.skeleton) {
  25738. var bone = root.skeleton.getBoneByName(nodeName);
  25739. if (bone !== undefined) {
  25740. return bone;
  25741. }
  25742. } // search into node subtree.
  25743. if (root.children) {
  25744. var searchNodeSubtree = function (children) {
  25745. for (var i = 0; i < children.length; i++) {
  25746. var childNode = children[i];
  25747. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25748. return childNode;
  25749. }
  25750. var result = searchNodeSubtree(childNode.children);
  25751. if (result) return result;
  25752. }
  25753. return null;
  25754. };
  25755. var subTreeNode = searchNodeSubtree(root.children);
  25756. if (subTreeNode) {
  25757. return subTreeNode;
  25758. }
  25759. }
  25760. return null;
  25761. }
  25762. });
  25763. Object.assign(PropertyBinding.prototype, {
  25764. // prototype, continued
  25765. // these are used to "bind" a nonexistent property
  25766. _getValue_unavailable: function () {},
  25767. _setValue_unavailable: function () {},
  25768. BindingType: {
  25769. Direct: 0,
  25770. EntireArray: 1,
  25771. ArrayElement: 2,
  25772. HasFromToArray: 3
  25773. },
  25774. Versioning: {
  25775. None: 0,
  25776. NeedsUpdate: 1,
  25777. MatrixWorldNeedsUpdate: 2
  25778. },
  25779. GetterByBindingType: [function getValue_direct(buffer, offset) {
  25780. buffer[offset] = this.node[this.propertyName];
  25781. }, function getValue_array(buffer, offset) {
  25782. var source = this.resolvedProperty;
  25783. for (var i = 0, n = source.length; i !== n; ++i) {
  25784. buffer[offset++] = source[i];
  25785. }
  25786. }, function getValue_arrayElement(buffer, offset) {
  25787. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25788. }, function getValue_toArray(buffer, offset) {
  25789. this.resolvedProperty.toArray(buffer, offset);
  25790. }],
  25791. SetterByBindingTypeAndVersioning: [[// Direct
  25792. function setValue_direct(buffer, offset) {
  25793. this.targetObject[this.propertyName] = buffer[offset];
  25794. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  25795. this.targetObject[this.propertyName] = buffer[offset];
  25796. this.targetObject.needsUpdate = true;
  25797. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25798. this.targetObject[this.propertyName] = buffer[offset];
  25799. this.targetObject.matrixWorldNeedsUpdate = true;
  25800. }], [// EntireArray
  25801. function setValue_array(buffer, offset) {
  25802. var dest = this.resolvedProperty;
  25803. for (var i = 0, n = dest.length; i !== n; ++i) {
  25804. dest[i] = buffer[offset++];
  25805. }
  25806. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  25807. var dest = this.resolvedProperty;
  25808. for (var i = 0, n = dest.length; i !== n; ++i) {
  25809. dest[i] = buffer[offset++];
  25810. }
  25811. this.targetObject.needsUpdate = true;
  25812. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25813. var dest = this.resolvedProperty;
  25814. for (var i = 0, n = dest.length; i !== n; ++i) {
  25815. dest[i] = buffer[offset++];
  25816. }
  25817. this.targetObject.matrixWorldNeedsUpdate = true;
  25818. }], [// ArrayElement
  25819. function setValue_arrayElement(buffer, offset) {
  25820. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25821. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25822. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25823. this.targetObject.needsUpdate = true;
  25824. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25825. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25826. this.targetObject.matrixWorldNeedsUpdate = true;
  25827. }], [// HasToFromArray
  25828. function setValue_fromArray(buffer, offset) {
  25829. this.resolvedProperty.fromArray(buffer, offset);
  25830. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25831. this.resolvedProperty.fromArray(buffer, offset);
  25832. this.targetObject.needsUpdate = true;
  25833. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25834. this.resolvedProperty.fromArray(buffer, offset);
  25835. this.targetObject.matrixWorldNeedsUpdate = true;
  25836. }]],
  25837. getValue: function getValue_unbound(targetArray, offset) {
  25838. this.bind();
  25839. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  25840. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25841. // prototype version of these methods with one that represents
  25842. // the bound state. When the property is not found, the methods
  25843. // become no-ops.
  25844. },
  25845. setValue: function getValue_unbound(sourceArray, offset) {
  25846. this.bind();
  25847. this.setValue(sourceArray, offset);
  25848. },
  25849. // create getter / setter pair for a property in the scene graph
  25850. bind: function () {
  25851. var targetObject = this.node,
  25852. parsedPath = this.parsedPath,
  25853. objectName = parsedPath.objectName,
  25854. propertyName = parsedPath.propertyName,
  25855. propertyIndex = parsedPath.propertyIndex;
  25856. if (!targetObject) {
  25857. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25858. this.node = targetObject;
  25859. } // set fail state so we can just 'return' on error
  25860. this.getValue = this._getValue_unavailable;
  25861. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25862. if (!targetObject) {
  25863. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25864. return;
  25865. }
  25866. if (objectName) {
  25867. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25868. switch (objectName) {
  25869. case 'materials':
  25870. if (!targetObject.material) {
  25871. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25872. return;
  25873. }
  25874. if (!targetObject.material.materials) {
  25875. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25876. return;
  25877. }
  25878. targetObject = targetObject.material.materials;
  25879. break;
  25880. case 'bones':
  25881. if (!targetObject.skeleton) {
  25882. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25883. return;
  25884. } // potential future optimization: skip this if propertyIndex is already an integer
  25885. // and convert the integer string to a true integer.
  25886. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25887. for (var i = 0; i < targetObject.length; i++) {
  25888. if (targetObject[i].name === objectIndex) {
  25889. objectIndex = i;
  25890. break;
  25891. }
  25892. }
  25893. break;
  25894. default:
  25895. if (targetObject[objectName] === undefined) {
  25896. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25897. return;
  25898. }
  25899. targetObject = targetObject[objectName];
  25900. }
  25901. if (objectIndex !== undefined) {
  25902. if (targetObject[objectIndex] === undefined) {
  25903. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25904. return;
  25905. }
  25906. targetObject = targetObject[objectIndex];
  25907. }
  25908. } // resolve property
  25909. var nodeProperty = targetObject[propertyName];
  25910. if (nodeProperty === undefined) {
  25911. var nodeName = parsedPath.nodeName;
  25912. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25913. return;
  25914. } // determine versioning scheme
  25915. var versioning = this.Versioning.None;
  25916. this.targetObject = targetObject;
  25917. if (targetObject.needsUpdate !== undefined) {
  25918. // material
  25919. versioning = this.Versioning.NeedsUpdate;
  25920. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25921. // node transform
  25922. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25923. } // determine how the property gets bound
  25924. var bindingType = this.BindingType.Direct;
  25925. if (propertyIndex !== undefined) {
  25926. // access a sub element of the property array (only primitives are supported right now)
  25927. if (propertyName === "morphTargetInfluences") {
  25928. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25929. // support resolving morphTarget names into indices.
  25930. if (!targetObject.geometry) {
  25931. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25932. return;
  25933. }
  25934. if (targetObject.geometry.isBufferGeometry) {
  25935. if (!targetObject.geometry.morphAttributes) {
  25936. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25937. return;
  25938. }
  25939. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  25940. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  25941. propertyIndex = i;
  25942. break;
  25943. }
  25944. }
  25945. } else {
  25946. if (!targetObject.geometry.morphTargets) {
  25947. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  25948. return;
  25949. }
  25950. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  25951. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  25952. propertyIndex = i;
  25953. break;
  25954. }
  25955. }
  25956. }
  25957. }
  25958. bindingType = this.BindingType.ArrayElement;
  25959. this.resolvedProperty = nodeProperty;
  25960. this.propertyIndex = propertyIndex;
  25961. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25962. // must use copy for Object3D.Euler/Quaternion
  25963. bindingType = this.BindingType.HasFromToArray;
  25964. this.resolvedProperty = nodeProperty;
  25965. } else if (Array.isArray(nodeProperty)) {
  25966. bindingType = this.BindingType.EntireArray;
  25967. this.resolvedProperty = nodeProperty;
  25968. } else {
  25969. this.propertyName = propertyName;
  25970. } // select getter / setter
  25971. this.getValue = this.GetterByBindingType[bindingType];
  25972. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25973. },
  25974. unbind: function () {
  25975. this.node = null; // back to the prototype version of getValue / setValue
  25976. // note: avoiding to mutate the shape of 'this' via 'delete'
  25977. this.getValue = this._getValue_unbound;
  25978. this.setValue = this._setValue_unbound;
  25979. }
  25980. }); // DECLARE ALIAS AFTER assign prototype
  25981. Object.assign(PropertyBinding.prototype, {
  25982. // initial state of these methods that calls 'bind'
  25983. _getValue_unbound: PropertyBinding.prototype.getValue,
  25984. _setValue_unbound: PropertyBinding.prototype.setValue
  25985. });
  25986. /**
  25987. *
  25988. * A group of objects that receives a shared animation state.
  25989. *
  25990. * Usage:
  25991. *
  25992. * - Add objects you would otherwise pass as 'root' to the
  25993. * constructor or the .clipAction method of AnimationMixer.
  25994. *
  25995. * - Instead pass this object as 'root'.
  25996. *
  25997. * - You can also add and remove objects later when the mixer
  25998. * is running.
  25999. *
  26000. * Note:
  26001. *
  26002. * Objects of this class appear as one object to the mixer,
  26003. * so cache control of the individual objects must be done
  26004. * on the group.
  26005. *
  26006. * Limitation:
  26007. *
  26008. * - The animated properties must be compatible among the
  26009. * all objects in the group.
  26010. *
  26011. * - A single property can either be controlled through a
  26012. * target group or directly, but not both.
  26013. *
  26014. * @author tschw
  26015. */
  26016. function AnimationObjectGroup() {
  26017. this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
  26018. this._objects = Array.prototype.slice.call(arguments);
  26019. this.nCachedObjects_ = 0; // threshold
  26020. // note: read by PropertyBinding.Composite
  26021. var indices = {};
  26022. this._indicesByUUID = indices; // for bookkeeping
  26023. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26024. indices[arguments[i].uuid] = i;
  26025. }
  26026. this._paths = []; // inside: string
  26027. this._parsedPaths = []; // inside: { we don't care, here }
  26028. this._bindings = []; // inside: Array< PropertyBinding >
  26029. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26030. var scope = this;
  26031. this.stats = {
  26032. objects: {
  26033. get total() {
  26034. return scope._objects.length;
  26035. },
  26036. get inUse() {
  26037. return this.total - scope.nCachedObjects_;
  26038. }
  26039. },
  26040. get bindingsPerObject() {
  26041. return scope._bindings.length;
  26042. }
  26043. };
  26044. }
  26045. Object.assign(AnimationObjectGroup.prototype, {
  26046. isAnimationObjectGroup: true,
  26047. add: function () {
  26048. var objects = this._objects,
  26049. nObjects = objects.length,
  26050. nCachedObjects = this.nCachedObjects_,
  26051. indicesByUUID = this._indicesByUUID,
  26052. paths = this._paths,
  26053. parsedPaths = this._parsedPaths,
  26054. bindings = this._bindings,
  26055. nBindings = bindings.length,
  26056. knownObject = undefined;
  26057. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26058. var object = arguments[i],
  26059. uuid = object.uuid,
  26060. index = indicesByUUID[uuid];
  26061. if (index === undefined) {
  26062. // unknown object -> add it to the ACTIVE region
  26063. index = nObjects++;
  26064. indicesByUUID[uuid] = index;
  26065. objects.push(object); // accounting is done, now do the same for all bindings
  26066. for (var j = 0, m = nBindings; j !== m; ++j) {
  26067. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26068. }
  26069. } else if (index < nCachedObjects) {
  26070. knownObject = objects[index]; // move existing object to the ACTIVE region
  26071. var firstActiveIndex = --nCachedObjects,
  26072. lastCachedObject = objects[firstActiveIndex];
  26073. indicesByUUID[lastCachedObject.uuid] = index;
  26074. objects[index] = lastCachedObject;
  26075. indicesByUUID[uuid] = firstActiveIndex;
  26076. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26077. for (var j = 0, m = nBindings; j !== m; ++j) {
  26078. var bindingsForPath = bindings[j],
  26079. lastCached = bindingsForPath[firstActiveIndex],
  26080. binding = bindingsForPath[index];
  26081. bindingsForPath[index] = lastCached;
  26082. if (binding === undefined) {
  26083. // since we do not bother to create new bindings
  26084. // for objects that are cached, the binding may
  26085. // or may not exist
  26086. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26087. }
  26088. bindingsForPath[firstActiveIndex] = binding;
  26089. }
  26090. } else if (objects[index] !== knownObject) {
  26091. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26092. } // else the object is already where we want it to be
  26093. } // for arguments
  26094. this.nCachedObjects_ = nCachedObjects;
  26095. },
  26096. remove: function () {
  26097. var objects = this._objects,
  26098. nCachedObjects = this.nCachedObjects_,
  26099. indicesByUUID = this._indicesByUUID,
  26100. bindings = this._bindings,
  26101. nBindings = bindings.length;
  26102. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26103. var object = arguments[i],
  26104. uuid = object.uuid,
  26105. index = indicesByUUID[uuid];
  26106. if (index !== undefined && index >= nCachedObjects) {
  26107. // move existing object into the CACHED region
  26108. var lastCachedIndex = nCachedObjects++,
  26109. firstActiveObject = objects[lastCachedIndex];
  26110. indicesByUUID[firstActiveObject.uuid] = index;
  26111. objects[index] = firstActiveObject;
  26112. indicesByUUID[uuid] = lastCachedIndex;
  26113. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26114. for (var j = 0, m = nBindings; j !== m; ++j) {
  26115. var bindingsForPath = bindings[j],
  26116. firstActive = bindingsForPath[lastCachedIndex],
  26117. binding = bindingsForPath[index];
  26118. bindingsForPath[index] = firstActive;
  26119. bindingsForPath[lastCachedIndex] = binding;
  26120. }
  26121. }
  26122. } // for arguments
  26123. this.nCachedObjects_ = nCachedObjects;
  26124. },
  26125. // remove & forget
  26126. uncache: function () {
  26127. var objects = this._objects,
  26128. nObjects = objects.length,
  26129. nCachedObjects = this.nCachedObjects_,
  26130. indicesByUUID = this._indicesByUUID,
  26131. bindings = this._bindings,
  26132. nBindings = bindings.length;
  26133. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26134. var object = arguments[i],
  26135. uuid = object.uuid,
  26136. index = indicesByUUID[uuid];
  26137. if (index !== undefined) {
  26138. delete indicesByUUID[uuid];
  26139. if (index < nCachedObjects) {
  26140. // object is cached, shrink the CACHED region
  26141. var firstActiveIndex = --nCachedObjects,
  26142. lastCachedObject = objects[firstActiveIndex],
  26143. lastIndex = --nObjects,
  26144. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26145. indicesByUUID[lastCachedObject.uuid] = index;
  26146. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26147. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26148. objects[firstActiveIndex] = lastObject;
  26149. objects.pop(); // accounting is done, now do the same for all bindings
  26150. for (var j = 0, m = nBindings; j !== m; ++j) {
  26151. var bindingsForPath = bindings[j],
  26152. lastCached = bindingsForPath[firstActiveIndex],
  26153. last = bindingsForPath[lastIndex];
  26154. bindingsForPath[index] = lastCached;
  26155. bindingsForPath[firstActiveIndex] = last;
  26156. bindingsForPath.pop();
  26157. }
  26158. } else {
  26159. // object is active, just swap with the last and pop
  26160. var lastIndex = --nObjects,
  26161. lastObject = objects[lastIndex];
  26162. indicesByUUID[lastObject.uuid] = index;
  26163. objects[index] = lastObject;
  26164. objects.pop(); // accounting is done, now do the same for all bindings
  26165. for (var j = 0, m = nBindings; j !== m; ++j) {
  26166. var bindingsForPath = bindings[j];
  26167. bindingsForPath[index] = bindingsForPath[lastIndex];
  26168. bindingsForPath.pop();
  26169. }
  26170. } // cached or active
  26171. } // if object is known
  26172. } // for arguments
  26173. this.nCachedObjects_ = nCachedObjects;
  26174. },
  26175. // Internal interface used by befriended PropertyBinding.Composite:
  26176. subscribe_: function (path, parsedPath) {
  26177. // returns an array of bindings for the given path that is changed
  26178. // according to the contained objects in the group
  26179. var indicesByPath = this._bindingsIndicesByPath,
  26180. index = indicesByPath[path],
  26181. bindings = this._bindings;
  26182. if (index !== undefined) return bindings[index];
  26183. var paths = this._paths,
  26184. parsedPaths = this._parsedPaths,
  26185. objects = this._objects,
  26186. nObjects = objects.length,
  26187. nCachedObjects = this.nCachedObjects_,
  26188. bindingsForPath = new Array(nObjects);
  26189. index = bindings.length;
  26190. indicesByPath[path] = index;
  26191. paths.push(path);
  26192. parsedPaths.push(parsedPath);
  26193. bindings.push(bindingsForPath);
  26194. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26195. var object = objects[i];
  26196. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26197. }
  26198. return bindingsForPath;
  26199. },
  26200. unsubscribe_: function (path) {
  26201. // tells the group to forget about a property path and no longer
  26202. // update the array previously obtained with 'subscribe_'
  26203. var indicesByPath = this._bindingsIndicesByPath,
  26204. index = indicesByPath[path];
  26205. if (index !== undefined) {
  26206. var paths = this._paths,
  26207. parsedPaths = this._parsedPaths,
  26208. bindings = this._bindings,
  26209. lastBindingsIndex = bindings.length - 1,
  26210. lastBindings = bindings[lastBindingsIndex],
  26211. lastBindingsPath = path[lastBindingsIndex];
  26212. indicesByPath[lastBindingsPath] = index;
  26213. bindings[index] = lastBindings;
  26214. bindings.pop();
  26215. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26216. parsedPaths.pop();
  26217. paths[index] = paths[lastBindingsIndex];
  26218. paths.pop();
  26219. }
  26220. }
  26221. });
  26222. /**
  26223. *
  26224. * Action provided by AnimationMixer for scheduling clip playback on specific
  26225. * objects.
  26226. *
  26227. * @author Ben Houston / http://clara.io/
  26228. * @author David Sarno / http://lighthaus.us/
  26229. * @author tschw
  26230. *
  26231. */
  26232. function AnimationAction(mixer, clip, localRoot) {
  26233. this._mixer = mixer;
  26234. this._clip = clip;
  26235. this._localRoot = localRoot || null;
  26236. var tracks = clip.tracks,
  26237. nTracks = tracks.length,
  26238. interpolants = new Array(nTracks);
  26239. var interpolantSettings = {
  26240. endingStart: ZeroCurvatureEnding,
  26241. endingEnd: ZeroCurvatureEnding
  26242. };
  26243. for (var i = 0; i !== nTracks; ++i) {
  26244. var interpolant = tracks[i].createInterpolant(null);
  26245. interpolants[i] = interpolant;
  26246. interpolant.settings = interpolantSettings;
  26247. }
  26248. this._interpolantSettings = interpolantSettings;
  26249. this._interpolants = interpolants; // bound by the mixer
  26250. // inside: PropertyMixer (managed by the mixer)
  26251. this._propertyBindings = new Array(nTracks);
  26252. this._cacheIndex = null; // for the memory manager
  26253. this._byClipCacheIndex = null; // for the memory manager
  26254. this._timeScaleInterpolant = null;
  26255. this._weightInterpolant = null;
  26256. this.loop = LoopRepeat;
  26257. this._loopCount = -1; // global mixer time when the action is to be started
  26258. // it's set back to 'null' upon start of the action
  26259. this._startTime = null; // scaled local time of the action
  26260. // gets clamped or wrapped to 0..clip.duration according to loop
  26261. this.time = 0;
  26262. this.timeScale = 1;
  26263. this._effectiveTimeScale = 1;
  26264. this.weight = 1;
  26265. this._effectiveWeight = 1;
  26266. this.repetitions = Infinity; // no. of repetitions when looping
  26267. this.paused = false; // true -> zero effective time scale
  26268. this.enabled = true; // false -> zero effective weight
  26269. this.clampWhenFinished = false; // keep feeding the last frame?
  26270. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26271. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26272. }
  26273. Object.assign(AnimationAction.prototype, {
  26274. // State & Scheduling
  26275. play: function () {
  26276. this._mixer._activateAction(this);
  26277. return this;
  26278. },
  26279. stop: function () {
  26280. this._mixer._deactivateAction(this);
  26281. return this.reset();
  26282. },
  26283. reset: function () {
  26284. this.paused = false;
  26285. this.enabled = true;
  26286. this.time = 0; // restart clip
  26287. this._loopCount = -1; // forget previous loops
  26288. this._startTime = null; // forget scheduling
  26289. return this.stopFading().stopWarping();
  26290. },
  26291. isRunning: function () {
  26292. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26293. },
  26294. // return true when play has been called
  26295. isScheduled: function () {
  26296. return this._mixer._isActiveAction(this);
  26297. },
  26298. startAt: function (time) {
  26299. this._startTime = time;
  26300. return this;
  26301. },
  26302. setLoop: function (mode, repetitions) {
  26303. this.loop = mode;
  26304. this.repetitions = repetitions;
  26305. return this;
  26306. },
  26307. // Weight
  26308. // set the weight stopping any scheduled fading
  26309. // although .enabled = false yields an effective weight of zero, this
  26310. // method does *not* change .enabled, because it would be confusing
  26311. setEffectiveWeight: function (weight) {
  26312. this.weight = weight; // note: same logic as when updated at runtime
  26313. this._effectiveWeight = this.enabled ? weight : 0;
  26314. return this.stopFading();
  26315. },
  26316. // return the weight considering fading and .enabled
  26317. getEffectiveWeight: function () {
  26318. return this._effectiveWeight;
  26319. },
  26320. fadeIn: function (duration) {
  26321. return this._scheduleFading(duration, 0, 1);
  26322. },
  26323. fadeOut: function (duration) {
  26324. return this._scheduleFading(duration, 1, 0);
  26325. },
  26326. crossFadeFrom: function (fadeOutAction, duration, warp) {
  26327. fadeOutAction.fadeOut(duration);
  26328. this.fadeIn(duration);
  26329. if (warp) {
  26330. var fadeInDuration = this._clip.duration,
  26331. fadeOutDuration = fadeOutAction._clip.duration,
  26332. startEndRatio = fadeOutDuration / fadeInDuration,
  26333. endStartRatio = fadeInDuration / fadeOutDuration;
  26334. fadeOutAction.warp(1.0, startEndRatio, duration);
  26335. this.warp(endStartRatio, 1.0, duration);
  26336. }
  26337. return this;
  26338. },
  26339. crossFadeTo: function (fadeInAction, duration, warp) {
  26340. return fadeInAction.crossFadeFrom(this, duration, warp);
  26341. },
  26342. stopFading: function () {
  26343. var weightInterpolant = this._weightInterpolant;
  26344. if (weightInterpolant !== null) {
  26345. this._weightInterpolant = null;
  26346. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26347. }
  26348. return this;
  26349. },
  26350. // Time Scale Control
  26351. // set the time scale stopping any scheduled warping
  26352. // although .paused = true yields an effective time scale of zero, this
  26353. // method does *not* change .paused, because it would be confusing
  26354. setEffectiveTimeScale: function (timeScale) {
  26355. this.timeScale = timeScale;
  26356. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26357. return this.stopWarping();
  26358. },
  26359. // return the time scale considering warping and .paused
  26360. getEffectiveTimeScale: function () {
  26361. return this._effectiveTimeScale;
  26362. },
  26363. setDuration: function (duration) {
  26364. this.timeScale = this._clip.duration / duration;
  26365. return this.stopWarping();
  26366. },
  26367. syncWith: function (action) {
  26368. this.time = action.time;
  26369. this.timeScale = action.timeScale;
  26370. return this.stopWarping();
  26371. },
  26372. halt: function (duration) {
  26373. return this.warp(this._effectiveTimeScale, 0, duration);
  26374. },
  26375. warp: function (startTimeScale, endTimeScale, duration) {
  26376. var mixer = this._mixer,
  26377. now = mixer.time,
  26378. interpolant = this._timeScaleInterpolant,
  26379. timeScale = this.timeScale;
  26380. if (interpolant === null) {
  26381. interpolant = mixer._lendControlInterpolant();
  26382. this._timeScaleInterpolant = interpolant;
  26383. }
  26384. var times = interpolant.parameterPositions,
  26385. values = interpolant.sampleValues;
  26386. times[0] = now;
  26387. times[1] = now + duration;
  26388. values[0] = startTimeScale / timeScale;
  26389. values[1] = endTimeScale / timeScale;
  26390. return this;
  26391. },
  26392. stopWarping: function () {
  26393. var timeScaleInterpolant = this._timeScaleInterpolant;
  26394. if (timeScaleInterpolant !== null) {
  26395. this._timeScaleInterpolant = null;
  26396. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26397. }
  26398. return this;
  26399. },
  26400. // Object Accessors
  26401. getMixer: function () {
  26402. return this._mixer;
  26403. },
  26404. getClip: function () {
  26405. return this._clip;
  26406. },
  26407. getRoot: function () {
  26408. return this._localRoot || this._mixer._root;
  26409. },
  26410. // Interna
  26411. _update: function (time, deltaTime, timeDirection, accuIndex) {
  26412. // called by the mixer
  26413. if (!this.enabled) {
  26414. // call ._updateWeight() to update ._effectiveWeight
  26415. this._updateWeight(time);
  26416. return;
  26417. }
  26418. var startTime = this._startTime;
  26419. if (startTime !== null) {
  26420. // check for scheduled start of action
  26421. var timeRunning = (time - startTime) * timeDirection;
  26422. if (timeRunning < 0 || timeDirection === 0) {
  26423. return; // yet to come / don't decide when delta = 0
  26424. } // start
  26425. this._startTime = null; // unschedule
  26426. deltaTime = timeDirection * timeRunning;
  26427. } // apply time scale and advance time
  26428. deltaTime *= this._updateTimeScale(time);
  26429. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26430. // an effective weight of 0
  26431. var weight = this._updateWeight(time);
  26432. if (weight > 0) {
  26433. var interpolants = this._interpolants;
  26434. var propertyMixers = this._propertyBindings;
  26435. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  26436. interpolants[j].evaluate(clipTime);
  26437. propertyMixers[j].accumulate(accuIndex, weight);
  26438. }
  26439. }
  26440. },
  26441. _updateWeight: function (time) {
  26442. var weight = 0;
  26443. if (this.enabled) {
  26444. weight = this.weight;
  26445. var interpolant = this._weightInterpolant;
  26446. if (interpolant !== null) {
  26447. var interpolantValue = interpolant.evaluate(time)[0];
  26448. weight *= interpolantValue;
  26449. if (time > interpolant.parameterPositions[1]) {
  26450. this.stopFading();
  26451. if (interpolantValue === 0) {
  26452. // faded out, disable
  26453. this.enabled = false;
  26454. }
  26455. }
  26456. }
  26457. }
  26458. this._effectiveWeight = weight;
  26459. return weight;
  26460. },
  26461. _updateTimeScale: function (time) {
  26462. var timeScale = 0;
  26463. if (!this.paused) {
  26464. timeScale = this.timeScale;
  26465. var interpolant = this._timeScaleInterpolant;
  26466. if (interpolant !== null) {
  26467. var interpolantValue = interpolant.evaluate(time)[0];
  26468. timeScale *= interpolantValue;
  26469. if (time > interpolant.parameterPositions[1]) {
  26470. this.stopWarping();
  26471. if (timeScale === 0) {
  26472. // motion has halted, pause
  26473. this.paused = true;
  26474. } else {
  26475. // warp done - apply final time scale
  26476. this.timeScale = timeScale;
  26477. }
  26478. }
  26479. }
  26480. }
  26481. this._effectiveTimeScale = timeScale;
  26482. return timeScale;
  26483. },
  26484. _updateTime: function (deltaTime) {
  26485. var time = this.time + deltaTime;
  26486. var duration = this._clip.duration;
  26487. var loop = this.loop;
  26488. var loopCount = this._loopCount;
  26489. var pingPong = loop === LoopPingPong;
  26490. if (deltaTime === 0) {
  26491. if (loopCount === -1) return time;
  26492. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26493. }
  26494. if (loop === LoopOnce) {
  26495. if (loopCount === -1) {
  26496. // just started
  26497. this._loopCount = 0;
  26498. this._setEndings(true, true, false);
  26499. }
  26500. handle_stop: {
  26501. if (time >= duration) {
  26502. time = duration;
  26503. } else if (time < 0) {
  26504. time = 0;
  26505. } else {
  26506. this.time = time;
  26507. break handle_stop;
  26508. }
  26509. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26510. this.time = time;
  26511. this._mixer.dispatchEvent({
  26512. type: 'finished',
  26513. action: this,
  26514. direction: deltaTime < 0 ? -1 : 1
  26515. });
  26516. }
  26517. } else {
  26518. // repetitive Repeat or PingPong
  26519. if (loopCount === -1) {
  26520. // just started
  26521. if (deltaTime >= 0) {
  26522. loopCount = 0;
  26523. this._setEndings(true, this.repetitions === 0, pingPong);
  26524. } else {
  26525. // when looping in reverse direction, the initial
  26526. // transition through zero counts as a repetition,
  26527. // so leave loopCount at -1
  26528. this._setEndings(this.repetitions === 0, true, pingPong);
  26529. }
  26530. }
  26531. if (time >= duration || time < 0) {
  26532. // wrap around
  26533. var loopDelta = Math.floor(time / duration); // signed
  26534. time -= duration * loopDelta;
  26535. loopCount += Math.abs(loopDelta);
  26536. var pending = this.repetitions - loopCount;
  26537. if (pending <= 0) {
  26538. // have to stop (switch state, clamp time, fire event)
  26539. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26540. time = deltaTime > 0 ? duration : 0;
  26541. this.time = time;
  26542. this._mixer.dispatchEvent({
  26543. type: 'finished',
  26544. action: this,
  26545. direction: deltaTime > 0 ? 1 : -1
  26546. });
  26547. } else {
  26548. // keep running
  26549. if (pending === 1) {
  26550. // entering the last round
  26551. var atStart = deltaTime < 0;
  26552. this._setEndings(atStart, !atStart, pingPong);
  26553. } else {
  26554. this._setEndings(false, false, pingPong);
  26555. }
  26556. this._loopCount = loopCount;
  26557. this.time = time;
  26558. this._mixer.dispatchEvent({
  26559. type: 'loop',
  26560. action: this,
  26561. loopDelta: loopDelta
  26562. });
  26563. }
  26564. } else {
  26565. this.time = time;
  26566. }
  26567. if (pingPong && (loopCount & 1) === 1) {
  26568. // invert time for the "pong round"
  26569. return duration - time;
  26570. }
  26571. }
  26572. return time;
  26573. },
  26574. _setEndings: function (atStart, atEnd, pingPong) {
  26575. var settings = this._interpolantSettings;
  26576. if (pingPong) {
  26577. settings.endingStart = ZeroSlopeEnding;
  26578. settings.endingEnd = ZeroSlopeEnding;
  26579. } else {
  26580. // assuming for LoopOnce atStart == atEnd == true
  26581. if (atStart) {
  26582. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26583. } else {
  26584. settings.endingStart = WrapAroundEnding;
  26585. }
  26586. if (atEnd) {
  26587. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26588. } else {
  26589. settings.endingEnd = WrapAroundEnding;
  26590. }
  26591. }
  26592. },
  26593. _scheduleFading: function (duration, weightNow, weightThen) {
  26594. var mixer = this._mixer,
  26595. now = mixer.time,
  26596. interpolant = this._weightInterpolant;
  26597. if (interpolant === null) {
  26598. interpolant = mixer._lendControlInterpolant();
  26599. this._weightInterpolant = interpolant;
  26600. }
  26601. var times = interpolant.parameterPositions,
  26602. values = interpolant.sampleValues;
  26603. times[0] = now;
  26604. values[0] = weightNow;
  26605. times[1] = now + duration;
  26606. values[1] = weightThen;
  26607. return this;
  26608. }
  26609. });
  26610. /**
  26611. *
  26612. * Player for AnimationClips.
  26613. *
  26614. *
  26615. * @author Ben Houston / http://clara.io/
  26616. * @author David Sarno / http://lighthaus.us/
  26617. * @author tschw
  26618. */
  26619. function AnimationMixer(root) {
  26620. this._root = root;
  26621. this._initMemoryManager();
  26622. this._accuIndex = 0;
  26623. this.time = 0;
  26624. this.timeScale = 1.0;
  26625. }
  26626. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  26627. constructor: AnimationMixer,
  26628. _bindAction: function (action, prototypeAction) {
  26629. var root = action._localRoot || this._root,
  26630. tracks = action._clip.tracks,
  26631. nTracks = tracks.length,
  26632. bindings = action._propertyBindings,
  26633. interpolants = action._interpolants,
  26634. rootUuid = root.uuid,
  26635. bindingsByRoot = this._bindingsByRootAndName,
  26636. bindingsByName = bindingsByRoot[rootUuid];
  26637. if (bindingsByName === undefined) {
  26638. bindingsByName = {};
  26639. bindingsByRoot[rootUuid] = bindingsByName;
  26640. }
  26641. for (var i = 0; i !== nTracks; ++i) {
  26642. var track = tracks[i],
  26643. trackName = track.name,
  26644. binding = bindingsByName[trackName];
  26645. if (binding !== undefined) {
  26646. bindings[i] = binding;
  26647. } else {
  26648. binding = bindings[i];
  26649. if (binding !== undefined) {
  26650. // existing binding, make sure the cache knows
  26651. if (binding._cacheIndex === null) {
  26652. ++binding.referenceCount;
  26653. this._addInactiveBinding(binding, rootUuid, trackName);
  26654. }
  26655. continue;
  26656. }
  26657. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26658. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26659. ++binding.referenceCount;
  26660. this._addInactiveBinding(binding, rootUuid, trackName);
  26661. bindings[i] = binding;
  26662. }
  26663. interpolants[i].resultBuffer = binding.buffer;
  26664. }
  26665. },
  26666. _activateAction: function (action) {
  26667. if (!this._isActiveAction(action)) {
  26668. if (action._cacheIndex === null) {
  26669. // this action has been forgotten by the cache, but the user
  26670. // appears to be still using it -> rebind
  26671. var rootUuid = (action._localRoot || this._root).uuid,
  26672. clipUuid = action._clip.uuid,
  26673. actionsForClip = this._actionsByClip[clipUuid];
  26674. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26675. this._addInactiveAction(action, clipUuid, rootUuid);
  26676. }
  26677. var bindings = action._propertyBindings; // increment reference counts / sort out state
  26678. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26679. var binding = bindings[i];
  26680. if (binding.useCount++ === 0) {
  26681. this._lendBinding(binding);
  26682. binding.saveOriginalState();
  26683. }
  26684. }
  26685. this._lendAction(action);
  26686. }
  26687. },
  26688. _deactivateAction: function (action) {
  26689. if (this._isActiveAction(action)) {
  26690. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  26691. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26692. var binding = bindings[i];
  26693. if (--binding.useCount === 0) {
  26694. binding.restoreOriginalState();
  26695. this._takeBackBinding(binding);
  26696. }
  26697. }
  26698. this._takeBackAction(action);
  26699. }
  26700. },
  26701. // Memory manager
  26702. _initMemoryManager: function () {
  26703. this._actions = []; // 'nActiveActions' followed by inactive ones
  26704. this._nActiveActions = 0;
  26705. this._actionsByClip = {}; // inside:
  26706. // {
  26707. // knownActions: Array< AnimationAction > - used as prototypes
  26708. // actionByRoot: AnimationAction - lookup
  26709. // }
  26710. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26711. this._nActiveBindings = 0;
  26712. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26713. this._controlInterpolants = []; // same game as above
  26714. this._nActiveControlInterpolants = 0;
  26715. var scope = this;
  26716. this.stats = {
  26717. actions: {
  26718. get total() {
  26719. return scope._actions.length;
  26720. },
  26721. get inUse() {
  26722. return scope._nActiveActions;
  26723. }
  26724. },
  26725. bindings: {
  26726. get total() {
  26727. return scope._bindings.length;
  26728. },
  26729. get inUse() {
  26730. return scope._nActiveBindings;
  26731. }
  26732. },
  26733. controlInterpolants: {
  26734. get total() {
  26735. return scope._controlInterpolants.length;
  26736. },
  26737. get inUse() {
  26738. return scope._nActiveControlInterpolants;
  26739. }
  26740. }
  26741. };
  26742. },
  26743. // Memory management for AnimationAction objects
  26744. _isActiveAction: function (action) {
  26745. var index = action._cacheIndex;
  26746. return index !== null && index < this._nActiveActions;
  26747. },
  26748. _addInactiveAction: function (action, clipUuid, rootUuid) {
  26749. var actions = this._actions,
  26750. actionsByClip = this._actionsByClip,
  26751. actionsForClip = actionsByClip[clipUuid];
  26752. if (actionsForClip === undefined) {
  26753. actionsForClip = {
  26754. knownActions: [action],
  26755. actionByRoot: {}
  26756. };
  26757. action._byClipCacheIndex = 0;
  26758. actionsByClip[clipUuid] = actionsForClip;
  26759. } else {
  26760. var knownActions = actionsForClip.knownActions;
  26761. action._byClipCacheIndex = knownActions.length;
  26762. knownActions.push(action);
  26763. }
  26764. action._cacheIndex = actions.length;
  26765. actions.push(action);
  26766. actionsForClip.actionByRoot[rootUuid] = action;
  26767. },
  26768. _removeInactiveAction: function (action) {
  26769. var actions = this._actions,
  26770. lastInactiveAction = actions[actions.length - 1],
  26771. cacheIndex = action._cacheIndex;
  26772. lastInactiveAction._cacheIndex = cacheIndex;
  26773. actions[cacheIndex] = lastInactiveAction;
  26774. actions.pop();
  26775. action._cacheIndex = null;
  26776. var clipUuid = action._clip.uuid,
  26777. actionsByClip = this._actionsByClip,
  26778. actionsForClip = actionsByClip[clipUuid],
  26779. knownActionsForClip = actionsForClip.knownActions,
  26780. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26781. byClipCacheIndex = action._byClipCacheIndex;
  26782. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26783. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26784. knownActionsForClip.pop();
  26785. action._byClipCacheIndex = null;
  26786. var actionByRoot = actionsForClip.actionByRoot,
  26787. rootUuid = (action._localRoot || this._root).uuid;
  26788. delete actionByRoot[rootUuid];
  26789. if (knownActionsForClip.length === 0) {
  26790. delete actionsByClip[clipUuid];
  26791. }
  26792. this._removeInactiveBindingsForAction(action);
  26793. },
  26794. _removeInactiveBindingsForAction: function (action) {
  26795. var bindings = action._propertyBindings;
  26796. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26797. var binding = bindings[i];
  26798. if (--binding.referenceCount === 0) {
  26799. this._removeInactiveBinding(binding);
  26800. }
  26801. }
  26802. },
  26803. _lendAction: function (action) {
  26804. // [ active actions | inactive actions ]
  26805. // [ active actions >| inactive actions ]
  26806. // s a
  26807. // <-swap->
  26808. // a s
  26809. var actions = this._actions,
  26810. prevIndex = action._cacheIndex,
  26811. lastActiveIndex = this._nActiveActions++,
  26812. firstInactiveAction = actions[lastActiveIndex];
  26813. action._cacheIndex = lastActiveIndex;
  26814. actions[lastActiveIndex] = action;
  26815. firstInactiveAction._cacheIndex = prevIndex;
  26816. actions[prevIndex] = firstInactiveAction;
  26817. },
  26818. _takeBackAction: function (action) {
  26819. // [ active actions | inactive actions ]
  26820. // [ active actions |< inactive actions ]
  26821. // a s
  26822. // <-swap->
  26823. // s a
  26824. var actions = this._actions,
  26825. prevIndex = action._cacheIndex,
  26826. firstInactiveIndex = --this._nActiveActions,
  26827. lastActiveAction = actions[firstInactiveIndex];
  26828. action._cacheIndex = firstInactiveIndex;
  26829. actions[firstInactiveIndex] = action;
  26830. lastActiveAction._cacheIndex = prevIndex;
  26831. actions[prevIndex] = lastActiveAction;
  26832. },
  26833. // Memory management for PropertyMixer objects
  26834. _addInactiveBinding: function (binding, rootUuid, trackName) {
  26835. var bindingsByRoot = this._bindingsByRootAndName,
  26836. bindingByName = bindingsByRoot[rootUuid],
  26837. bindings = this._bindings;
  26838. if (bindingByName === undefined) {
  26839. bindingByName = {};
  26840. bindingsByRoot[rootUuid] = bindingByName;
  26841. }
  26842. bindingByName[trackName] = binding;
  26843. binding._cacheIndex = bindings.length;
  26844. bindings.push(binding);
  26845. },
  26846. _removeInactiveBinding: function (binding) {
  26847. var bindings = this._bindings,
  26848. propBinding = binding.binding,
  26849. rootUuid = propBinding.rootNode.uuid,
  26850. trackName = propBinding.path,
  26851. bindingsByRoot = this._bindingsByRootAndName,
  26852. bindingByName = bindingsByRoot[rootUuid],
  26853. lastInactiveBinding = bindings[bindings.length - 1],
  26854. cacheIndex = binding._cacheIndex;
  26855. lastInactiveBinding._cacheIndex = cacheIndex;
  26856. bindings[cacheIndex] = lastInactiveBinding;
  26857. bindings.pop();
  26858. delete bindingByName[trackName];
  26859. if (Object.keys(bindingByName).length === 0) {
  26860. delete bindingsByRoot[rootUuid];
  26861. }
  26862. },
  26863. _lendBinding: function (binding) {
  26864. var bindings = this._bindings,
  26865. prevIndex = binding._cacheIndex,
  26866. lastActiveIndex = this._nActiveBindings++,
  26867. firstInactiveBinding = bindings[lastActiveIndex];
  26868. binding._cacheIndex = lastActiveIndex;
  26869. bindings[lastActiveIndex] = binding;
  26870. firstInactiveBinding._cacheIndex = prevIndex;
  26871. bindings[prevIndex] = firstInactiveBinding;
  26872. },
  26873. _takeBackBinding: function (binding) {
  26874. var bindings = this._bindings,
  26875. prevIndex = binding._cacheIndex,
  26876. firstInactiveIndex = --this._nActiveBindings,
  26877. lastActiveBinding = bindings[firstInactiveIndex];
  26878. binding._cacheIndex = firstInactiveIndex;
  26879. bindings[firstInactiveIndex] = binding;
  26880. lastActiveBinding._cacheIndex = prevIndex;
  26881. bindings[prevIndex] = lastActiveBinding;
  26882. },
  26883. // Memory management of Interpolants for weight and time scale
  26884. _lendControlInterpolant: function () {
  26885. var interpolants = this._controlInterpolants,
  26886. lastActiveIndex = this._nActiveControlInterpolants++,
  26887. interpolant = interpolants[lastActiveIndex];
  26888. if (interpolant === undefined) {
  26889. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26890. interpolant.__cacheIndex = lastActiveIndex;
  26891. interpolants[lastActiveIndex] = interpolant;
  26892. }
  26893. return interpolant;
  26894. },
  26895. _takeBackControlInterpolant: function (interpolant) {
  26896. var interpolants = this._controlInterpolants,
  26897. prevIndex = interpolant.__cacheIndex,
  26898. firstInactiveIndex = --this._nActiveControlInterpolants,
  26899. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26900. interpolant.__cacheIndex = firstInactiveIndex;
  26901. interpolants[firstInactiveIndex] = interpolant;
  26902. lastActiveInterpolant.__cacheIndex = prevIndex;
  26903. interpolants[prevIndex] = lastActiveInterpolant;
  26904. },
  26905. _controlInterpolantsResultBuffer: new Float32Array(1),
  26906. // return an action for a clip optionally using a custom root target
  26907. // object (this method allocates a lot of dynamic memory in case a
  26908. // previously unknown clip/root combination is specified)
  26909. clipAction: function (clip, optionalRoot) {
  26910. var root = optionalRoot || this._root,
  26911. rootUuid = root.uuid,
  26912. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26913. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  26914. actionsForClip = this._actionsByClip[clipUuid],
  26915. prototypeAction = null;
  26916. if (actionsForClip !== undefined) {
  26917. var existingAction = actionsForClip.actionByRoot[rootUuid];
  26918. if (existingAction !== undefined) {
  26919. return existingAction;
  26920. } // we know the clip, so we don't have to parse all
  26921. // the bindings again but can just copy
  26922. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26923. if (clipObject === null) clipObject = prototypeAction._clip;
  26924. } // clip must be known when specified via string
  26925. if (clipObject === null) return null; // allocate all resources required to run it
  26926. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  26927. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26928. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26929. return newAction;
  26930. },
  26931. // get an existing action
  26932. existingAction: function (clip, optionalRoot) {
  26933. var root = optionalRoot || this._root,
  26934. rootUuid = root.uuid,
  26935. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26936. clipUuid = clipObject ? clipObject.uuid : clip,
  26937. actionsForClip = this._actionsByClip[clipUuid];
  26938. if (actionsForClip !== undefined) {
  26939. return actionsForClip.actionByRoot[rootUuid] || null;
  26940. }
  26941. return null;
  26942. },
  26943. // deactivates all previously scheduled actions
  26944. stopAllAction: function () {
  26945. var actions = this._actions,
  26946. nActions = this._nActiveActions,
  26947. bindings = this._bindings,
  26948. nBindings = this._nActiveBindings;
  26949. this._nActiveActions = 0;
  26950. this._nActiveBindings = 0;
  26951. for (var i = 0; i !== nActions; ++i) {
  26952. actions[i].reset();
  26953. }
  26954. for (var i = 0; i !== nBindings; ++i) {
  26955. bindings[i].useCount = 0;
  26956. }
  26957. return this;
  26958. },
  26959. // advance the time and update apply the animation
  26960. update: function (deltaTime) {
  26961. deltaTime *= this.timeScale;
  26962. var actions = this._actions,
  26963. nActions = this._nActiveActions,
  26964. time = this.time += deltaTime,
  26965. timeDirection = Math.sign(deltaTime),
  26966. accuIndex = this._accuIndex ^= 1; // run active actions
  26967. for (var i = 0; i !== nActions; ++i) {
  26968. var action = actions[i];
  26969. action._update(time, deltaTime, timeDirection, accuIndex);
  26970. } // update scene graph
  26971. var bindings = this._bindings,
  26972. nBindings = this._nActiveBindings;
  26973. for (var i = 0; i !== nBindings; ++i) {
  26974. bindings[i].apply(accuIndex);
  26975. }
  26976. return this;
  26977. },
  26978. // Allows you to seek to a specific time in an animation.
  26979. setTime: function (timeInSeconds) {
  26980. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26981. for (var i = 0; i < this._actions.length; i++) {
  26982. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26983. }
  26984. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26985. },
  26986. // return this mixer's root target object
  26987. getRoot: function () {
  26988. return this._root;
  26989. },
  26990. // free all resources specific to a particular clip
  26991. uncacheClip: function (clip) {
  26992. var actions = this._actions,
  26993. clipUuid = clip.uuid,
  26994. actionsByClip = this._actionsByClip,
  26995. actionsForClip = actionsByClip[clipUuid];
  26996. if (actionsForClip !== undefined) {
  26997. // note: just calling _removeInactiveAction would mess up the
  26998. // iteration state and also require updating the state we can
  26999. // just throw away
  27000. var actionsToRemove = actionsForClip.knownActions;
  27001. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27002. var action = actionsToRemove[i];
  27003. this._deactivateAction(action);
  27004. var cacheIndex = action._cacheIndex,
  27005. lastInactiveAction = actions[actions.length - 1];
  27006. action._cacheIndex = null;
  27007. action._byClipCacheIndex = null;
  27008. lastInactiveAction._cacheIndex = cacheIndex;
  27009. actions[cacheIndex] = lastInactiveAction;
  27010. actions.pop();
  27011. this._removeInactiveBindingsForAction(action);
  27012. }
  27013. delete actionsByClip[clipUuid];
  27014. }
  27015. },
  27016. // free all resources specific to a particular root target object
  27017. uncacheRoot: function (root) {
  27018. var rootUuid = root.uuid,
  27019. actionsByClip = this._actionsByClip;
  27020. for (var clipUuid in actionsByClip) {
  27021. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27022. action = actionByRoot[rootUuid];
  27023. if (action !== undefined) {
  27024. this._deactivateAction(action);
  27025. this._removeInactiveAction(action);
  27026. }
  27027. }
  27028. var bindingsByRoot = this._bindingsByRootAndName,
  27029. bindingByName = bindingsByRoot[rootUuid];
  27030. if (bindingByName !== undefined) {
  27031. for (var trackName in bindingByName) {
  27032. var binding = bindingByName[trackName];
  27033. binding.restoreOriginalState();
  27034. this._removeInactiveBinding(binding);
  27035. }
  27036. }
  27037. },
  27038. // remove a targeted clip from the cache
  27039. uncacheAction: function (clip, optionalRoot) {
  27040. var action = this.existingAction(clip, optionalRoot);
  27041. if (action !== null) {
  27042. this._deactivateAction(action);
  27043. this._removeInactiveAction(action);
  27044. }
  27045. }
  27046. });
  27047. /**
  27048. * @author mrdoob / http://mrdoob.com/
  27049. */
  27050. function Uniform(value) {
  27051. if (typeof value === 'string') {
  27052. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27053. value = arguments[1];
  27054. }
  27055. this.value = value;
  27056. }
  27057. Uniform.prototype.clone = function () {
  27058. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27059. };
  27060. /**
  27061. * @author benaadams / https://twitter.com/ben_a_adams
  27062. */
  27063. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27064. InterleavedBuffer.call(this, array, stride);
  27065. this.meshPerAttribute = meshPerAttribute || 1;
  27066. }
  27067. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27068. constructor: InstancedInterleavedBuffer,
  27069. isInstancedInterleavedBuffer: true,
  27070. copy: function (source) {
  27071. InterleavedBuffer.prototype.copy.call(this, source);
  27072. this.meshPerAttribute = source.meshPerAttribute;
  27073. return this;
  27074. }
  27075. });
  27076. /**
  27077. * @author mrdoob / http://mrdoob.com/
  27078. * @author bhouston / http://clara.io/
  27079. * @author stephomi / http://stephaneginier.com/
  27080. */
  27081. function Raycaster(origin, direction, near, far) {
  27082. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27083. this.near = near || 0;
  27084. this.far = far || Infinity;
  27085. this.camera = null;
  27086. this.layers = new Layers();
  27087. this.params = {
  27088. Mesh: {},
  27089. Line: {
  27090. threshold: 1
  27091. },
  27092. LOD: {},
  27093. Points: {
  27094. threshold: 1
  27095. },
  27096. Sprite: {}
  27097. };
  27098. Object.defineProperties(this.params, {
  27099. PointCloud: {
  27100. get: function () {
  27101. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27102. return this.Points;
  27103. }
  27104. }
  27105. });
  27106. }
  27107. function ascSort(a, b) {
  27108. return a.distance - b.distance;
  27109. }
  27110. function intersectObject(object, raycaster, intersects, recursive) {
  27111. if (object.layers.test(raycaster.layers)) {
  27112. object.raycast(raycaster, intersects);
  27113. }
  27114. if (recursive === true) {
  27115. var children = object.children;
  27116. for (var i = 0, l = children.length; i < l; i++) {
  27117. intersectObject(children[i], raycaster, intersects, true);
  27118. }
  27119. }
  27120. }
  27121. Object.assign(Raycaster.prototype, {
  27122. set: function (origin, direction) {
  27123. // direction is assumed to be normalized (for accurate distance calculations)
  27124. this.ray.set(origin, direction);
  27125. },
  27126. setFromCamera: function (coords, camera) {
  27127. if (camera && camera.isPerspectiveCamera) {
  27128. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27129. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27130. this.camera = camera;
  27131. } else if (camera && camera.isOrthographicCamera) {
  27132. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27133. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27134. this.camera = camera;
  27135. } else {
  27136. console.error('THREE.Raycaster: Unsupported camera type.');
  27137. }
  27138. },
  27139. intersectObject: function (object, recursive, optionalTarget) {
  27140. var intersects = optionalTarget || [];
  27141. intersectObject(object, this, intersects, recursive);
  27142. intersects.sort(ascSort);
  27143. return intersects;
  27144. },
  27145. intersectObjects: function (objects, recursive, optionalTarget) {
  27146. var intersects = optionalTarget || [];
  27147. if (Array.isArray(objects) === false) {
  27148. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27149. return intersects;
  27150. }
  27151. for (var i = 0, l = objects.length; i < l; i++) {
  27152. intersectObject(objects[i], this, intersects, recursive);
  27153. }
  27154. intersects.sort(ascSort);
  27155. return intersects;
  27156. }
  27157. });
  27158. /**
  27159. * @author bhouston / http://clara.io
  27160. * @author WestLangley / http://github.com/WestLangley
  27161. *
  27162. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27163. *
  27164. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27165. * The azimuthal angle (theta) is measured from the positive z-axis.
  27166. */
  27167. function Spherical(radius, phi, theta) {
  27168. this.radius = radius !== undefined ? radius : 1.0;
  27169. this.phi = phi !== undefined ? phi : 0; // polar angle
  27170. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  27171. return this;
  27172. }
  27173. Object.assign(Spherical.prototype, {
  27174. set: function (radius, phi, theta) {
  27175. this.radius = radius;
  27176. this.phi = phi;
  27177. this.theta = theta;
  27178. return this;
  27179. },
  27180. clone: function () {
  27181. return new this.constructor().copy(this);
  27182. },
  27183. copy: function (other) {
  27184. this.radius = other.radius;
  27185. this.phi = other.phi;
  27186. this.theta = other.theta;
  27187. return this;
  27188. },
  27189. // restrict phi to be betwee EPS and PI-EPS
  27190. makeSafe: function () {
  27191. var EPS = 0.000001;
  27192. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27193. return this;
  27194. },
  27195. setFromVector3: function (v) {
  27196. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27197. },
  27198. setFromCartesianCoords: function (x, y, z) {
  27199. this.radius = Math.sqrt(x * x + y * y + z * z);
  27200. if (this.radius === 0) {
  27201. this.theta = 0;
  27202. this.phi = 0;
  27203. } else {
  27204. this.theta = Math.atan2(x, z);
  27205. this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
  27206. }
  27207. return this;
  27208. }
  27209. });
  27210. /**
  27211. * @author Mugen87 / https://github.com/Mugen87
  27212. *
  27213. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27214. *
  27215. */
  27216. function Cylindrical(radius, theta, y) {
  27217. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27218. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27219. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27220. return this;
  27221. }
  27222. Object.assign(Cylindrical.prototype, {
  27223. set: function (radius, theta, y) {
  27224. this.radius = radius;
  27225. this.theta = theta;
  27226. this.y = y;
  27227. return this;
  27228. },
  27229. clone: function () {
  27230. return new this.constructor().copy(this);
  27231. },
  27232. copy: function (other) {
  27233. this.radius = other.radius;
  27234. this.theta = other.theta;
  27235. this.y = other.y;
  27236. return this;
  27237. },
  27238. setFromVector3: function (v) {
  27239. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27240. },
  27241. setFromCartesianCoords: function (x, y, z) {
  27242. this.radius = Math.sqrt(x * x + z * z);
  27243. this.theta = Math.atan2(x, z);
  27244. this.y = y;
  27245. return this;
  27246. }
  27247. });
  27248. /**
  27249. * @author bhouston / http://clara.io
  27250. */
  27251. var _vector$7 = new Vector2();
  27252. function Box2(min, max) {
  27253. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27254. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27255. }
  27256. Object.assign(Box2.prototype, {
  27257. set: function (min, max) {
  27258. this.min.copy(min);
  27259. this.max.copy(max);
  27260. return this;
  27261. },
  27262. setFromPoints: function (points) {
  27263. this.makeEmpty();
  27264. for (var i = 0, il = points.length; i < il; i++) {
  27265. this.expandByPoint(points[i]);
  27266. }
  27267. return this;
  27268. },
  27269. setFromCenterAndSize: function (center, size) {
  27270. var halfSize = _vector$7.copy(size).multiplyScalar(0.5);
  27271. this.min.copy(center).sub(halfSize);
  27272. this.max.copy(center).add(halfSize);
  27273. return this;
  27274. },
  27275. clone: function () {
  27276. return new this.constructor().copy(this);
  27277. },
  27278. copy: function (box) {
  27279. this.min.copy(box.min);
  27280. this.max.copy(box.max);
  27281. return this;
  27282. },
  27283. makeEmpty: function () {
  27284. this.min.x = this.min.y = +Infinity;
  27285. this.max.x = this.max.y = -Infinity;
  27286. return this;
  27287. },
  27288. isEmpty: function () {
  27289. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27290. return this.max.x < this.min.x || this.max.y < this.min.y;
  27291. },
  27292. getCenter: function (target) {
  27293. if (target === undefined) {
  27294. console.warn('THREE.Box2: .getCenter() target is now required');
  27295. target = new Vector2();
  27296. }
  27297. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27298. },
  27299. getSize: function (target) {
  27300. if (target === undefined) {
  27301. console.warn('THREE.Box2: .getSize() target is now required');
  27302. target = new Vector2();
  27303. }
  27304. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27305. },
  27306. expandByPoint: function (point) {
  27307. this.min.min(point);
  27308. this.max.max(point);
  27309. return this;
  27310. },
  27311. expandByVector: function (vector) {
  27312. this.min.sub(vector);
  27313. this.max.add(vector);
  27314. return this;
  27315. },
  27316. expandByScalar: function (scalar) {
  27317. this.min.addScalar(-scalar);
  27318. this.max.addScalar(scalar);
  27319. return this;
  27320. },
  27321. containsPoint: function (point) {
  27322. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27323. },
  27324. containsBox: function (box) {
  27325. 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;
  27326. },
  27327. getParameter: function (point, target) {
  27328. // This can potentially have a divide by zero if the box
  27329. // has a size dimension of 0.
  27330. if (target === undefined) {
  27331. console.warn('THREE.Box2: .getParameter() target is now required');
  27332. target = new Vector2();
  27333. }
  27334. 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));
  27335. },
  27336. intersectsBox: function (box) {
  27337. // using 4 splitting planes to rule out intersections
  27338. 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;
  27339. },
  27340. clampPoint: function (point, target) {
  27341. if (target === undefined) {
  27342. console.warn('THREE.Box2: .clampPoint() target is now required');
  27343. target = new Vector2();
  27344. }
  27345. return target.copy(point).clamp(this.min, this.max);
  27346. },
  27347. distanceToPoint: function (point) {
  27348. var clampedPoint = _vector$7.copy(point).clamp(this.min, this.max);
  27349. return clampedPoint.sub(point).length();
  27350. },
  27351. intersect: function (box) {
  27352. this.min.max(box.min);
  27353. this.max.min(box.max);
  27354. return this;
  27355. },
  27356. union: function (box) {
  27357. this.min.min(box.min);
  27358. this.max.max(box.max);
  27359. return this;
  27360. },
  27361. translate: function (offset) {
  27362. this.min.add(offset);
  27363. this.max.add(offset);
  27364. return this;
  27365. },
  27366. equals: function (box) {
  27367. return box.min.equals(this.min) && box.max.equals(this.max);
  27368. }
  27369. });
  27370. /**
  27371. * @author bhouston / http://clara.io
  27372. */
  27373. var _startP = new Vector3();
  27374. var _startEnd = new Vector3();
  27375. function Line3(start, end) {
  27376. this.start = start !== undefined ? start : new Vector3();
  27377. this.end = end !== undefined ? end : new Vector3();
  27378. }
  27379. Object.assign(Line3.prototype, {
  27380. set: function (start, end) {
  27381. this.start.copy(start);
  27382. this.end.copy(end);
  27383. return this;
  27384. },
  27385. clone: function () {
  27386. return new this.constructor().copy(this);
  27387. },
  27388. copy: function (line) {
  27389. this.start.copy(line.start);
  27390. this.end.copy(line.end);
  27391. return this;
  27392. },
  27393. getCenter: function (target) {
  27394. if (target === undefined) {
  27395. console.warn('THREE.Line3: .getCenter() target is now required');
  27396. target = new Vector3();
  27397. }
  27398. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27399. },
  27400. delta: function (target) {
  27401. if (target === undefined) {
  27402. console.warn('THREE.Line3: .delta() target is now required');
  27403. target = new Vector3();
  27404. }
  27405. return target.subVectors(this.end, this.start);
  27406. },
  27407. distanceSq: function () {
  27408. return this.start.distanceToSquared(this.end);
  27409. },
  27410. distance: function () {
  27411. return this.start.distanceTo(this.end);
  27412. },
  27413. at: function (t, target) {
  27414. if (target === undefined) {
  27415. console.warn('THREE.Line3: .at() target is now required');
  27416. target = new Vector3();
  27417. }
  27418. return this.delta(target).multiplyScalar(t).add(this.start);
  27419. },
  27420. closestPointToPointParameter: function (point, clampToLine) {
  27421. _startP.subVectors(point, this.start);
  27422. _startEnd.subVectors(this.end, this.start);
  27423. var startEnd2 = _startEnd.dot(_startEnd);
  27424. var startEnd_startP = _startEnd.dot(_startP);
  27425. var t = startEnd_startP / startEnd2;
  27426. if (clampToLine) {
  27427. t = MathUtils.clamp(t, 0, 1);
  27428. }
  27429. return t;
  27430. },
  27431. closestPointToPoint: function (point, clampToLine, target) {
  27432. var t = this.closestPointToPointParameter(point, clampToLine);
  27433. if (target === undefined) {
  27434. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  27435. target = new Vector3();
  27436. }
  27437. return this.delta(target).multiplyScalar(t).add(this.start);
  27438. },
  27439. applyMatrix4: function (matrix) {
  27440. this.start.applyMatrix4(matrix);
  27441. this.end.applyMatrix4(matrix);
  27442. return this;
  27443. },
  27444. equals: function (line) {
  27445. return line.start.equals(this.start) && line.end.equals(this.end);
  27446. }
  27447. });
  27448. /**
  27449. * @author alteredq / http://alteredqualia.com/
  27450. */
  27451. function ImmediateRenderObject(material) {
  27452. Object3D.call(this);
  27453. this.material = material;
  27454. this.render = function ()
  27455. /* renderCallback */
  27456. {};
  27457. }
  27458. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  27459. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  27460. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27461. /**
  27462. * @author alteredq / http://alteredqualia.com/
  27463. * @author mrdoob / http://mrdoob.com/
  27464. * @author WestLangley / http://github.com/WestLangley
  27465. */
  27466. var _vector$8 = new Vector3();
  27467. function SpotLightHelper(light, color) {
  27468. Object3D.call(this);
  27469. this.light = light;
  27470. this.light.updateMatrixWorld();
  27471. this.matrix = light.matrixWorld;
  27472. this.matrixAutoUpdate = false;
  27473. this.color = color;
  27474. var geometry = new BufferGeometry();
  27475. 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];
  27476. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  27477. var p1 = i / l * Math.PI * 2;
  27478. var p2 = j / l * Math.PI * 2;
  27479. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27480. }
  27481. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27482. var material = new LineBasicMaterial({
  27483. fog: false,
  27484. toneMapped: false
  27485. });
  27486. this.cone = new LineSegments(geometry, material);
  27487. this.add(this.cone);
  27488. this.update();
  27489. }
  27490. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  27491. SpotLightHelper.prototype.constructor = SpotLightHelper;
  27492. SpotLightHelper.prototype.dispose = function () {
  27493. this.cone.geometry.dispose();
  27494. this.cone.material.dispose();
  27495. };
  27496. SpotLightHelper.prototype.update = function () {
  27497. this.light.updateMatrixWorld();
  27498. var coneLength = this.light.distance ? this.light.distance : 1000;
  27499. var coneWidth = coneLength * Math.tan(this.light.angle);
  27500. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27501. _vector$8.setFromMatrixPosition(this.light.target.matrixWorld);
  27502. this.cone.lookAt(_vector$8);
  27503. if (this.color !== undefined) {
  27504. this.cone.material.color.set(this.color);
  27505. } else {
  27506. this.cone.material.color.copy(this.light.color);
  27507. }
  27508. };
  27509. /**
  27510. * @author Sean Griffin / http://twitter.com/sgrif
  27511. * @author Michael Guerrero / http://realitymeltdown.com
  27512. * @author mrdoob / http://mrdoob.com/
  27513. * @author ikerr / http://verold.com
  27514. * @author Mugen87 / https://github.com/Mugen87
  27515. */
  27516. var _vector$9 = new Vector3();
  27517. var _boneMatrix = new Matrix4();
  27518. var _matrixWorldInv = new Matrix4();
  27519. function getBoneList(object) {
  27520. var boneList = [];
  27521. if (object && object.isBone) {
  27522. boneList.push(object);
  27523. }
  27524. for (var i = 0; i < object.children.length; i++) {
  27525. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27526. }
  27527. return boneList;
  27528. }
  27529. function SkeletonHelper(object) {
  27530. var bones = getBoneList(object);
  27531. var geometry = new BufferGeometry();
  27532. var vertices = [];
  27533. var colors = [];
  27534. var color1 = new Color(0, 0, 1);
  27535. var color2 = new Color(0, 1, 0);
  27536. for (var i = 0; i < bones.length; i++) {
  27537. var bone = bones[i];
  27538. if (bone.parent && bone.parent.isBone) {
  27539. vertices.push(0, 0, 0);
  27540. vertices.push(0, 0, 0);
  27541. colors.push(color1.r, color1.g, color1.b);
  27542. colors.push(color2.r, color2.g, color2.b);
  27543. }
  27544. }
  27545. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27546. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27547. var material = new LineBasicMaterial({
  27548. vertexColors: true,
  27549. depthTest: false,
  27550. depthWrite: false,
  27551. toneMapped: false,
  27552. transparent: true
  27553. });
  27554. LineSegments.call(this, geometry, material);
  27555. this.root = object;
  27556. this.bones = bones;
  27557. this.matrix = object.matrixWorld;
  27558. this.matrixAutoUpdate = false;
  27559. }
  27560. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  27561. SkeletonHelper.prototype.constructor = SkeletonHelper;
  27562. SkeletonHelper.prototype.isSkeletonHelper = true;
  27563. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  27564. var bones = this.bones;
  27565. var geometry = this.geometry;
  27566. var position = geometry.getAttribute('position');
  27567. _matrixWorldInv.getInverse(this.root.matrixWorld);
  27568. for (var i = 0, j = 0; i < bones.length; i++) {
  27569. var bone = bones[i];
  27570. if (bone.parent && bone.parent.isBone) {
  27571. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27572. _vector$9.setFromMatrixPosition(_boneMatrix);
  27573. position.setXYZ(j, _vector$9.x, _vector$9.y, _vector$9.z);
  27574. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27575. _vector$9.setFromMatrixPosition(_boneMatrix);
  27576. position.setXYZ(j + 1, _vector$9.x, _vector$9.y, _vector$9.z);
  27577. j += 2;
  27578. }
  27579. }
  27580. geometry.getAttribute('position').needsUpdate = true;
  27581. Object3D.prototype.updateMatrixWorld.call(this, force);
  27582. };
  27583. /**
  27584. * @author alteredq / http://alteredqualia.com/
  27585. * @author mrdoob / http://mrdoob.com/
  27586. */
  27587. function PointLightHelper(light, sphereSize, color) {
  27588. this.light = light;
  27589. this.light.updateMatrixWorld();
  27590. this.color = color;
  27591. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  27592. var material = new MeshBasicMaterial({
  27593. wireframe: true,
  27594. fog: false,
  27595. toneMapped: false
  27596. });
  27597. Mesh.call(this, geometry, material);
  27598. this.matrix = this.light.matrixWorld;
  27599. this.matrixAutoUpdate = false;
  27600. this.update();
  27601. /*
  27602. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27603. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27604. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27605. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27606. var d = light.distance;
  27607. if ( d === 0.0 ) {
  27608. this.lightDistance.visible = false;
  27609. } else {
  27610. this.lightDistance.scale.set( d, d, d );
  27611. }
  27612. this.add( this.lightDistance );
  27613. */
  27614. }
  27615. PointLightHelper.prototype = Object.create(Mesh.prototype);
  27616. PointLightHelper.prototype.constructor = PointLightHelper;
  27617. PointLightHelper.prototype.dispose = function () {
  27618. this.geometry.dispose();
  27619. this.material.dispose();
  27620. };
  27621. PointLightHelper.prototype.update = function () {
  27622. if (this.color !== undefined) {
  27623. this.material.color.set(this.color);
  27624. } else {
  27625. this.material.color.copy(this.light.color);
  27626. }
  27627. /*
  27628. var d = this.light.distance;
  27629. if ( d === 0.0 ) {
  27630. this.lightDistance.visible = false;
  27631. } else {
  27632. this.lightDistance.visible = true;
  27633. this.lightDistance.scale.set( d, d, d );
  27634. }
  27635. */
  27636. };
  27637. /**
  27638. * @author alteredq / http://alteredqualia.com/
  27639. * @author mrdoob / http://mrdoob.com/
  27640. * @author Mugen87 / https://github.com/Mugen87
  27641. */
  27642. var _vector$a = new Vector3();
  27643. var _color1 = new Color();
  27644. var _color2 = new Color();
  27645. function HemisphereLightHelper(light, size, color) {
  27646. Object3D.call(this);
  27647. this.light = light;
  27648. this.light.updateMatrixWorld();
  27649. this.matrix = light.matrixWorld;
  27650. this.matrixAutoUpdate = false;
  27651. this.color = color;
  27652. var geometry = new OctahedronBufferGeometry(size);
  27653. geometry.rotateY(Math.PI * 0.5);
  27654. this.material = new MeshBasicMaterial({
  27655. wireframe: true,
  27656. fog: false,
  27657. toneMapped: false
  27658. });
  27659. if (this.color === undefined) this.material.vertexColors = true;
  27660. var position = geometry.getAttribute('position');
  27661. var colors = new Float32Array(position.count * 3);
  27662. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27663. this.add(new Mesh(geometry, this.material));
  27664. this.update();
  27665. }
  27666. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  27667. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  27668. HemisphereLightHelper.prototype.dispose = function () {
  27669. this.children[0].geometry.dispose();
  27670. this.children[0].material.dispose();
  27671. };
  27672. HemisphereLightHelper.prototype.update = function () {
  27673. var mesh = this.children[0];
  27674. if (this.color !== undefined) {
  27675. this.material.color.set(this.color);
  27676. } else {
  27677. var colors = mesh.geometry.getAttribute('color');
  27678. _color1.copy(this.light.color);
  27679. _color2.copy(this.light.groundColor);
  27680. for (var i = 0, l = colors.count; i < l; i++) {
  27681. var color = i < l / 2 ? _color1 : _color2;
  27682. colors.setXYZ(i, color.r, color.g, color.b);
  27683. }
  27684. colors.needsUpdate = true;
  27685. }
  27686. mesh.lookAt(_vector$a.setFromMatrixPosition(this.light.matrixWorld).negate());
  27687. };
  27688. /**
  27689. * @author mrdoob / http://mrdoob.com/
  27690. */
  27691. function GridHelper(size, divisions, color1, color2) {
  27692. size = size || 10;
  27693. divisions = divisions || 10;
  27694. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  27695. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  27696. var center = divisions / 2;
  27697. var step = size / divisions;
  27698. var halfSize = size / 2;
  27699. var vertices = [],
  27700. colors = [];
  27701. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27702. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27703. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27704. var color = i === center ? color1 : color2;
  27705. color.toArray(colors, j);
  27706. j += 3;
  27707. color.toArray(colors, j);
  27708. j += 3;
  27709. color.toArray(colors, j);
  27710. j += 3;
  27711. color.toArray(colors, j);
  27712. j += 3;
  27713. }
  27714. var geometry = new BufferGeometry();
  27715. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27716. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27717. var material = new LineBasicMaterial({
  27718. vertexColors: true,
  27719. toneMapped: false
  27720. });
  27721. LineSegments.call(this, geometry, material);
  27722. }
  27723. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  27724. constructor: GridHelper,
  27725. copy: function (source) {
  27726. LineSegments.prototype.copy.call(this, source);
  27727. this.geometry.copy(source.geometry);
  27728. this.material.copy(source.material);
  27729. return this;
  27730. },
  27731. clone: function () {
  27732. return new this.constructor().copy(this);
  27733. }
  27734. });
  27735. /**
  27736. * @author mrdoob / http://mrdoob.com/
  27737. * @author Mugen87 / http://github.com/Mugen87
  27738. * @author Hectate / http://www.github.com/Hectate
  27739. */
  27740. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  27741. radius = radius || 10;
  27742. radials = radials || 16;
  27743. circles = circles || 8;
  27744. divisions = divisions || 64;
  27745. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  27746. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  27747. var vertices = [];
  27748. var colors = [];
  27749. var x, z;
  27750. var v, i, j, r, color; // create the radials
  27751. for (i = 0; i <= radials; i++) {
  27752. v = i / radials * (Math.PI * 2);
  27753. x = Math.sin(v) * radius;
  27754. z = Math.cos(v) * radius;
  27755. vertices.push(0, 0, 0);
  27756. vertices.push(x, 0, z);
  27757. color = i & 1 ? color1 : color2;
  27758. colors.push(color.r, color.g, color.b);
  27759. colors.push(color.r, color.g, color.b);
  27760. } // create the circles
  27761. for (i = 0; i <= circles; i++) {
  27762. color = i & 1 ? color1 : color2;
  27763. r = radius - radius / circles * i;
  27764. for (j = 0; j < divisions; j++) {
  27765. // first vertex
  27766. v = j / divisions * (Math.PI * 2);
  27767. x = Math.sin(v) * r;
  27768. z = Math.cos(v) * r;
  27769. vertices.push(x, 0, z);
  27770. colors.push(color.r, color.g, color.b); // second vertex
  27771. v = (j + 1) / divisions * (Math.PI * 2);
  27772. x = Math.sin(v) * r;
  27773. z = Math.cos(v) * r;
  27774. vertices.push(x, 0, z);
  27775. colors.push(color.r, color.g, color.b);
  27776. }
  27777. }
  27778. var geometry = new BufferGeometry();
  27779. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27780. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27781. var material = new LineBasicMaterial({
  27782. vertexColors: true,
  27783. toneMapped: false
  27784. });
  27785. LineSegments.call(this, geometry, material);
  27786. }
  27787. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  27788. PolarGridHelper.prototype.constructor = PolarGridHelper;
  27789. /**
  27790. * @author alteredq / http://alteredqualia.com/
  27791. * @author mrdoob / http://mrdoob.com/
  27792. * @author WestLangley / http://github.com/WestLangley
  27793. */
  27794. var _v1$5 = new Vector3();
  27795. var _v2$3 = new Vector3();
  27796. var _v3$1 = new Vector3();
  27797. function DirectionalLightHelper(light, size, color) {
  27798. Object3D.call(this);
  27799. this.light = light;
  27800. this.light.updateMatrixWorld();
  27801. this.matrix = light.matrixWorld;
  27802. this.matrixAutoUpdate = false;
  27803. this.color = color;
  27804. if (size === undefined) size = 1;
  27805. var geometry = new BufferGeometry();
  27806. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27807. var material = new LineBasicMaterial({
  27808. fog: false,
  27809. toneMapped: false
  27810. });
  27811. this.lightPlane = new Line(geometry, material);
  27812. this.add(this.lightPlane);
  27813. geometry = new BufferGeometry();
  27814. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27815. this.targetLine = new Line(geometry, material);
  27816. this.add(this.targetLine);
  27817. this.update();
  27818. }
  27819. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  27820. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  27821. DirectionalLightHelper.prototype.dispose = function () {
  27822. this.lightPlane.geometry.dispose();
  27823. this.lightPlane.material.dispose();
  27824. this.targetLine.geometry.dispose();
  27825. this.targetLine.material.dispose();
  27826. };
  27827. DirectionalLightHelper.prototype.update = function () {
  27828. _v1$5.setFromMatrixPosition(this.light.matrixWorld);
  27829. _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27830. _v3$1.subVectors(_v2$3, _v1$5);
  27831. this.lightPlane.lookAt(_v2$3);
  27832. if (this.color !== undefined) {
  27833. this.lightPlane.material.color.set(this.color);
  27834. this.targetLine.material.color.set(this.color);
  27835. } else {
  27836. this.lightPlane.material.color.copy(this.light.color);
  27837. this.targetLine.material.color.copy(this.light.color);
  27838. }
  27839. this.targetLine.lookAt(_v2$3);
  27840. this.targetLine.scale.z = _v3$1.length();
  27841. };
  27842. /**
  27843. * @author alteredq / http://alteredqualia.com/
  27844. * @author Mugen87 / https://github.com/Mugen87
  27845. *
  27846. * - shows frustum, line of sight and up of the camera
  27847. * - suitable for fast updates
  27848. * - based on frustum visualization in lightgl.js shadowmap example
  27849. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27850. */
  27851. var _vector$b = new Vector3();
  27852. var _camera = new Camera();
  27853. function CameraHelper(camera) {
  27854. var geometry = new BufferGeometry();
  27855. var material = new LineBasicMaterial({
  27856. color: 0xffffff,
  27857. vertexColors: true,
  27858. toneMapped: false
  27859. });
  27860. var vertices = [];
  27861. var colors = [];
  27862. var pointMap = {}; // colors
  27863. var colorFrustum = new Color(0xffaa00);
  27864. var colorCone = new Color(0xff0000);
  27865. var colorUp = new Color(0x00aaff);
  27866. var colorTarget = new Color(0xffffff);
  27867. var colorCross = new Color(0x333333); // near
  27868. addLine('n1', 'n2', colorFrustum);
  27869. addLine('n2', 'n4', colorFrustum);
  27870. addLine('n4', 'n3', colorFrustum);
  27871. addLine('n3', 'n1', colorFrustum); // far
  27872. addLine('f1', 'f2', colorFrustum);
  27873. addLine('f2', 'f4', colorFrustum);
  27874. addLine('f4', 'f3', colorFrustum);
  27875. addLine('f3', 'f1', colorFrustum); // sides
  27876. addLine('n1', 'f1', colorFrustum);
  27877. addLine('n2', 'f2', colorFrustum);
  27878. addLine('n3', 'f3', colorFrustum);
  27879. addLine('n4', 'f4', colorFrustum); // cone
  27880. addLine('p', 'n1', colorCone);
  27881. addLine('p', 'n2', colorCone);
  27882. addLine('p', 'n3', colorCone);
  27883. addLine('p', 'n4', colorCone); // up
  27884. addLine('u1', 'u2', colorUp);
  27885. addLine('u2', 'u3', colorUp);
  27886. addLine('u3', 'u1', colorUp); // target
  27887. addLine('c', 't', colorTarget);
  27888. addLine('p', 'c', colorCross); // cross
  27889. addLine('cn1', 'cn2', colorCross);
  27890. addLine('cn3', 'cn4', colorCross);
  27891. addLine('cf1', 'cf2', colorCross);
  27892. addLine('cf3', 'cf4', colorCross);
  27893. function addLine(a, b, color) {
  27894. addPoint(a, color);
  27895. addPoint(b, color);
  27896. }
  27897. function addPoint(id, color) {
  27898. vertices.push(0, 0, 0);
  27899. colors.push(color.r, color.g, color.b);
  27900. if (pointMap[id] === undefined) {
  27901. pointMap[id] = [];
  27902. }
  27903. pointMap[id].push(vertices.length / 3 - 1);
  27904. }
  27905. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27906. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27907. LineSegments.call(this, geometry, material);
  27908. this.camera = camera;
  27909. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27910. this.matrix = camera.matrixWorld;
  27911. this.matrixAutoUpdate = false;
  27912. this.pointMap = pointMap;
  27913. this.update();
  27914. }
  27915. CameraHelper.prototype = Object.create(LineSegments.prototype);
  27916. CameraHelper.prototype.constructor = CameraHelper;
  27917. CameraHelper.prototype.update = function () {
  27918. var geometry = this.geometry;
  27919. var pointMap = this.pointMap;
  27920. var w = 1,
  27921. h = 1; // we need just camera projection matrix inverse
  27922. // world matrix must be identity
  27923. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27924. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27925. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27926. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27927. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27928. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27929. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27930. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27931. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27932. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27933. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27934. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27935. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27936. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27937. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27938. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27939. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27940. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27941. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27942. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27943. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27944. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27945. geometry.getAttribute('position').needsUpdate = true;
  27946. };
  27947. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27948. _vector$b.set(x, y, z).unproject(camera);
  27949. var points = pointMap[point];
  27950. if (points !== undefined) {
  27951. var position = geometry.getAttribute('position');
  27952. for (var i = 0, l = points.length; i < l; i++) {
  27953. position.setXYZ(points[i], _vector$b.x, _vector$b.y, _vector$b.z);
  27954. }
  27955. }
  27956. }
  27957. /**
  27958. * @author mrdoob / http://mrdoob.com/
  27959. * @author Mugen87 / http://github.com/Mugen87
  27960. */
  27961. var _box$3 = new Box3();
  27962. function BoxHelper(object, color) {
  27963. this.object = object;
  27964. if (color === undefined) color = 0xffff00;
  27965. 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]);
  27966. var positions = new Float32Array(8 * 3);
  27967. var geometry = new BufferGeometry();
  27968. geometry.setIndex(new BufferAttribute(indices, 1));
  27969. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27970. LineSegments.call(this, geometry, new LineBasicMaterial({
  27971. color: color,
  27972. toneMapped: false
  27973. }));
  27974. this.matrixAutoUpdate = false;
  27975. this.update();
  27976. }
  27977. BoxHelper.prototype = Object.create(LineSegments.prototype);
  27978. BoxHelper.prototype.constructor = BoxHelper;
  27979. BoxHelper.prototype.update = function (object) {
  27980. if (object !== undefined) {
  27981. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27982. }
  27983. if (this.object !== undefined) {
  27984. _box$3.setFromObject(this.object);
  27985. }
  27986. if (_box$3.isEmpty()) return;
  27987. var min = _box$3.min;
  27988. var max = _box$3.max;
  27989. /*
  27990. 5____4
  27991. 1/___0/|
  27992. | 6__|_7
  27993. 2/___3/
  27994. 0: max.x, max.y, max.z
  27995. 1: min.x, max.y, max.z
  27996. 2: min.x, min.y, max.z
  27997. 3: max.x, min.y, max.z
  27998. 4: max.x, max.y, min.z
  27999. 5: min.x, max.y, min.z
  28000. 6: min.x, min.y, min.z
  28001. 7: max.x, min.y, min.z
  28002. */
  28003. var position = this.geometry.attributes.position;
  28004. var array = position.array;
  28005. array[0] = max.x;
  28006. array[1] = max.y;
  28007. array[2] = max.z;
  28008. array[3] = min.x;
  28009. array[4] = max.y;
  28010. array[5] = max.z;
  28011. array[6] = min.x;
  28012. array[7] = min.y;
  28013. array[8] = max.z;
  28014. array[9] = max.x;
  28015. array[10] = min.y;
  28016. array[11] = max.z;
  28017. array[12] = max.x;
  28018. array[13] = max.y;
  28019. array[14] = min.z;
  28020. array[15] = min.x;
  28021. array[16] = max.y;
  28022. array[17] = min.z;
  28023. array[18] = min.x;
  28024. array[19] = min.y;
  28025. array[20] = min.z;
  28026. array[21] = max.x;
  28027. array[22] = min.y;
  28028. array[23] = min.z;
  28029. position.needsUpdate = true;
  28030. this.geometry.computeBoundingSphere();
  28031. };
  28032. BoxHelper.prototype.setFromObject = function (object) {
  28033. this.object = object;
  28034. this.update();
  28035. return this;
  28036. };
  28037. BoxHelper.prototype.copy = function (source) {
  28038. LineSegments.prototype.copy.call(this, source);
  28039. this.object = source.object;
  28040. return this;
  28041. };
  28042. BoxHelper.prototype.clone = function () {
  28043. return new this.constructor().copy(this);
  28044. };
  28045. /**
  28046. * @author WestLangley / http://github.com/WestLangley
  28047. */
  28048. function Box3Helper(box, color) {
  28049. this.type = 'Box3Helper';
  28050. this.box = box;
  28051. color = color || 0xffff00;
  28052. 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]);
  28053. 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];
  28054. var geometry = new BufferGeometry();
  28055. geometry.setIndex(new BufferAttribute(indices, 1));
  28056. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28057. LineSegments.call(this, geometry, new LineBasicMaterial({
  28058. color: color,
  28059. toneMapped: false
  28060. }));
  28061. this.geometry.computeBoundingSphere();
  28062. }
  28063. Box3Helper.prototype = Object.create(LineSegments.prototype);
  28064. Box3Helper.prototype.constructor = Box3Helper;
  28065. Box3Helper.prototype.updateMatrixWorld = function (force) {
  28066. var box = this.box;
  28067. if (box.isEmpty()) return;
  28068. box.getCenter(this.position);
  28069. box.getSize(this.scale);
  28070. this.scale.multiplyScalar(0.5);
  28071. Object3D.prototype.updateMatrixWorld.call(this, force);
  28072. };
  28073. /**
  28074. * @author WestLangley / http://github.com/WestLangley
  28075. */
  28076. function PlaneHelper(plane, size, hex) {
  28077. this.type = 'PlaneHelper';
  28078. this.plane = plane;
  28079. this.size = size === undefined ? 1 : size;
  28080. var color = hex !== undefined ? hex : 0xffff00;
  28081. 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];
  28082. var geometry = new BufferGeometry();
  28083. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28084. geometry.computeBoundingSphere();
  28085. Line.call(this, geometry, new LineBasicMaterial({
  28086. color: color,
  28087. toneMapped: false
  28088. })); //
  28089. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  28090. var geometry2 = new BufferGeometry();
  28091. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  28092. geometry2.computeBoundingSphere();
  28093. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28094. color: color,
  28095. opacity: 0.2,
  28096. transparent: true,
  28097. depthWrite: false,
  28098. toneMapped: false
  28099. })));
  28100. }
  28101. PlaneHelper.prototype = Object.create(Line.prototype);
  28102. PlaneHelper.prototype.constructor = PlaneHelper;
  28103. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  28104. var scale = -this.plane.constant;
  28105. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  28106. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  28107. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28108. this.lookAt(this.plane.normal);
  28109. Object3D.prototype.updateMatrixWorld.call(this, force);
  28110. };
  28111. /**
  28112. * @author WestLangley / http://github.com/WestLangley
  28113. * @author zz85 / http://github.com/zz85
  28114. * @author bhouston / http://clara.io
  28115. *
  28116. * Creates an arrow for visualizing directions
  28117. *
  28118. * Parameters:
  28119. * dir - Vector3
  28120. * origin - Vector3
  28121. * length - Number
  28122. * color - color in hex value
  28123. * headLength - Number
  28124. * headWidth - Number
  28125. */
  28126. var _axis = new Vector3();
  28127. var _lineGeometry, _coneGeometry;
  28128. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  28129. // dir is assumed to be normalized
  28130. Object3D.call(this);
  28131. if (dir === undefined) dir = new Vector3(0, 0, 1);
  28132. if (origin === undefined) origin = new Vector3(0, 0, 0);
  28133. if (length === undefined) length = 1;
  28134. if (color === undefined) color = 0xffff00;
  28135. if (headLength === undefined) headLength = 0.2 * length;
  28136. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28137. if (_lineGeometry === undefined) {
  28138. _lineGeometry = new BufferGeometry();
  28139. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  28140. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  28141. _coneGeometry.translate(0, -0.5, 0);
  28142. }
  28143. this.position.copy(origin);
  28144. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  28145. color: color,
  28146. toneMapped: false
  28147. }));
  28148. this.line.matrixAutoUpdate = false;
  28149. this.add(this.line);
  28150. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28151. color: color,
  28152. toneMapped: false
  28153. }));
  28154. this.cone.matrixAutoUpdate = false;
  28155. this.add(this.cone);
  28156. this.setDirection(dir);
  28157. this.setLength(length, headLength, headWidth);
  28158. }
  28159. ArrowHelper.prototype = Object.create(Object3D.prototype);
  28160. ArrowHelper.prototype.constructor = ArrowHelper;
  28161. ArrowHelper.prototype.setDirection = function (dir) {
  28162. // dir is assumed to be normalized
  28163. if (dir.y > 0.99999) {
  28164. this.quaternion.set(0, 0, 0, 1);
  28165. } else if (dir.y < -0.99999) {
  28166. this.quaternion.set(1, 0, 0, 0);
  28167. } else {
  28168. _axis.set(dir.z, 0, -dir.x).normalize();
  28169. var radians = Math.acos(dir.y);
  28170. this.quaternion.setFromAxisAngle(_axis, radians);
  28171. }
  28172. };
  28173. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  28174. if (headLength === undefined) headLength = 0.2 * length;
  28175. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28176. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28177. this.line.updateMatrix();
  28178. this.cone.scale.set(headWidth, headLength, headWidth);
  28179. this.cone.position.y = length;
  28180. this.cone.updateMatrix();
  28181. };
  28182. ArrowHelper.prototype.setColor = function (color) {
  28183. this.line.material.color.set(color);
  28184. this.cone.material.color.set(color);
  28185. };
  28186. ArrowHelper.prototype.copy = function (source) {
  28187. Object3D.prototype.copy.call(this, source, false);
  28188. this.line.copy(source.line);
  28189. this.cone.copy(source.cone);
  28190. return this;
  28191. };
  28192. ArrowHelper.prototype.clone = function () {
  28193. return new this.constructor().copy(this);
  28194. };
  28195. /**
  28196. * @author sroucheray / http://sroucheray.org/
  28197. * @author mrdoob / http://mrdoob.com/
  28198. */
  28199. function AxesHelper(size) {
  28200. size = size || 1;
  28201. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28202. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28203. var geometry = new BufferGeometry();
  28204. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28205. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28206. var material = new LineBasicMaterial({
  28207. vertexColors: true,
  28208. toneMapped: false
  28209. });
  28210. LineSegments.call(this, geometry, material);
  28211. }
  28212. AxesHelper.prototype = Object.create(LineSegments.prototype);
  28213. AxesHelper.prototype.constructor = AxesHelper;
  28214. /**
  28215. * @author Emmett Lalish / elalish
  28216. *
  28217. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28218. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28219. * blur to be quickly accessed based on material roughness. It is packed into a
  28220. * special CubeUV format that allows us to perform custom interpolation so that
  28221. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28222. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28223. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28224. * higher roughness levels. In this way we maintain resolution to smoothly
  28225. * interpolate diffuse lighting while limiting sampling computation.
  28226. */
  28227. var LOD_MIN = 4;
  28228. var LOD_MAX = 8;
  28229. var SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  28230. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28231. // geometric shadowing function. These sigma values squared must match the
  28232. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28233. var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  28234. var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28235. // samples and exit early, but not recompile the shader.
  28236. var MAX_SAMPLES = 20;
  28237. var ENCODINGS = {
  28238. [LinearEncoding]: 0,
  28239. [sRGBEncoding]: 1,
  28240. [RGBEEncoding]: 2,
  28241. [RGBM7Encoding]: 3,
  28242. [RGBM16Encoding]: 4,
  28243. [RGBDEncoding]: 5,
  28244. [GammaEncoding]: 6
  28245. };
  28246. var _flatCamera = new OrthographicCamera();
  28247. var _blurMaterial = _getBlurShader(MAX_SAMPLES);
  28248. var _equirectShader = null;
  28249. var _cubemapShader = null;
  28250. var {
  28251. _lodPlanes,
  28252. _sizeLods,
  28253. _sigmas
  28254. } = _createPlanes();
  28255. var _pingPongRenderTarget = null;
  28256. var _renderer = null;
  28257. var _oldTarget = null; // Golden Ratio
  28258. var PHI = (1 + Math.sqrt(5)) / 2;
  28259. var INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  28260. // same axis), used as axis directions evenly spread on a sphere.
  28261. var _axisDirections = [new Vector3(1, 1, 1), new Vector3(-1, 1, 1), new Vector3(1, 1, -1), new Vector3(-1, 1, -1), new Vector3(0, PHI, INV_PHI), new Vector3(0, PHI, -INV_PHI), new Vector3(INV_PHI, 0, PHI), new Vector3(-INV_PHI, 0, PHI), new Vector3(PHI, INV_PHI, 0), new Vector3(-PHI, INV_PHI, 0)];
  28262. function PMREMGenerator(renderer) {
  28263. _renderer = renderer;
  28264. _compileMaterial(_blurMaterial);
  28265. }
  28266. PMREMGenerator.prototype = {
  28267. constructor: PMREMGenerator,
  28268. /**
  28269. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28270. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28271. * in radians to be applied to the scene before PMREM generation. Optional near
  28272. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28273. * is placed at the origin).
  28274. */
  28275. fromScene: function (scene, sigma = 0, near = 0.1, far = 100) {
  28276. _oldTarget = _renderer.getRenderTarget();
  28277. var cubeUVRenderTarget = _allocateTargets();
  28278. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  28279. if (sigma > 0) {
  28280. _blur(cubeUVRenderTarget, 0, 0, sigma);
  28281. }
  28282. _applyPMREM(cubeUVRenderTarget);
  28283. _cleanup(cubeUVRenderTarget);
  28284. return cubeUVRenderTarget;
  28285. },
  28286. /**
  28287. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28288. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  28289. * as this matches best with the 256 x 256 cubemap output.
  28290. */
  28291. fromEquirectangular: function (equirectangular) {
  28292. equirectangular.magFilter = NearestFilter;
  28293. equirectangular.minFilter = NearestFilter;
  28294. equirectangular.generateMipmaps = false;
  28295. return this.fromCubemap(equirectangular);
  28296. },
  28297. /**
  28298. * Generates a PMREM from an cubemap texture, which can be either LDR
  28299. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  28300. * as this matches best with the 256 x 256 cubemap output.
  28301. */
  28302. fromCubemap: function (cubemap) {
  28303. _oldTarget = _renderer.getRenderTarget();
  28304. var cubeUVRenderTarget = _allocateTargets(cubemap);
  28305. _textureToCubeUV(cubemap, cubeUVRenderTarget);
  28306. _applyPMREM(cubeUVRenderTarget);
  28307. _cleanup(cubeUVRenderTarget);
  28308. return cubeUVRenderTarget;
  28309. },
  28310. /**
  28311. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28312. * your texture's network fetch for increased concurrency.
  28313. */
  28314. compileCubemapShader: function () {
  28315. if (_cubemapShader == null) {
  28316. _cubemapShader = _getCubemapShader();
  28317. _compileMaterial(_cubemapShader);
  28318. }
  28319. },
  28320. /**
  28321. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28322. * your texture's network fetch for increased concurrency.
  28323. */
  28324. compileEquirectangularShader: function () {
  28325. if (_equirectShader == null) {
  28326. _equirectShader = _getEquirectShader();
  28327. _compileMaterial(_equirectShader);
  28328. }
  28329. },
  28330. /**
  28331. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28332. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28333. * one of them will cause any others to also become unusable.
  28334. */
  28335. dispose: function () {
  28336. _blurMaterial.dispose();
  28337. if (_cubemapShader != null) _cubemapShader.dispose();
  28338. if (_equirectShader != null) _equirectShader.dispose();
  28339. for (var i = 0; i < _lodPlanes.length; i++) {
  28340. _lodPlanes[i].dispose();
  28341. }
  28342. }
  28343. };
  28344. function _createPlanes() {
  28345. var _lodPlanes = [];
  28346. var _sizeLods = [];
  28347. var _sigmas = [];
  28348. var lod = LOD_MAX;
  28349. for (var i = 0; i < TOTAL_LODS; i++) {
  28350. var sizeLod = Math.pow(2, lod);
  28351. _sizeLods.push(sizeLod);
  28352. var sigma = 1.0 / sizeLod;
  28353. if (i > LOD_MAX - LOD_MIN) {
  28354. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  28355. } else if (i == 0) {
  28356. sigma = 0;
  28357. }
  28358. _sigmas.push(sigma);
  28359. var texelSize = 1.0 / (sizeLod - 1);
  28360. var min = -texelSize / 2;
  28361. var max = 1 + texelSize / 2;
  28362. var uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  28363. var cubeFaces = 6;
  28364. var vertices = 6;
  28365. var positionSize = 3;
  28366. var uvSize = 2;
  28367. var faceIndexSize = 1;
  28368. var position = new Float32Array(positionSize * vertices * cubeFaces);
  28369. var uv = new Float32Array(uvSize * vertices * cubeFaces);
  28370. var faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  28371. for (var face = 0; face < cubeFaces; face++) {
  28372. var x = face % 3 * 2 / 3 - 1;
  28373. var y = face > 2 ? 0 : -1;
  28374. var coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  28375. position.set(coordinates, positionSize * vertices * face);
  28376. uv.set(uv1, uvSize * vertices * face);
  28377. var fill = [face, face, face, face, face, face];
  28378. faceIndex.set(fill, faceIndexSize * vertices * face);
  28379. }
  28380. var planes = new BufferGeometry();
  28381. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  28382. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  28383. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  28384. _lodPlanes.push(planes);
  28385. if (lod > LOD_MIN) {
  28386. lod--;
  28387. }
  28388. }
  28389. return {
  28390. _lodPlanes,
  28391. _sizeLods,
  28392. _sigmas
  28393. };
  28394. }
  28395. function _allocateTargets(equirectangular) {
  28396. var params = {
  28397. magFilter: NearestFilter,
  28398. minFilter: NearestFilter,
  28399. generateMipmaps: false,
  28400. type: equirectangular ? equirectangular.type : UnsignedByteType,
  28401. format: equirectangular ? equirectangular.format : RGBEFormat,
  28402. encoding: equirectangular ? equirectangular.encoding : RGBEEncoding,
  28403. depthBuffer: false,
  28404. stencilBuffer: false
  28405. };
  28406. var cubeUVRenderTarget = _createRenderTarget(params);
  28407. cubeUVRenderTarget.depthBuffer = equirectangular ? false : true;
  28408. _pingPongRenderTarget = _createRenderTarget(params);
  28409. return cubeUVRenderTarget;
  28410. }
  28411. function _cleanup(outputTarget) {
  28412. _pingPongRenderTarget.dispose();
  28413. _renderer.setRenderTarget(_oldTarget);
  28414. outputTarget.scissorTest = false; // reset viewport and scissor
  28415. outputTarget.setSize(outputTarget.width, outputTarget.height);
  28416. }
  28417. function _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  28418. var fov = 90;
  28419. var aspect = 1;
  28420. var cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  28421. var upSign = [1, 1, 1, 1, -1, 1];
  28422. var forwardSign = [1, 1, -1, -1, -1, 1];
  28423. var outputEncoding = _renderer.outputEncoding;
  28424. var toneMapping = _renderer.toneMapping;
  28425. var toneMappingExposure = _renderer.toneMappingExposure;
  28426. var clearColor = _renderer.getClearColor();
  28427. var clearAlpha = _renderer.getClearAlpha();
  28428. _renderer.toneMapping = LinearToneMapping;
  28429. _renderer.toneMappingExposure = 1.0;
  28430. _renderer.outputEncoding = LinearEncoding;
  28431. scene.scale.z *= -1;
  28432. var background = scene.background;
  28433. if (background && background.isColor) {
  28434. background.convertSRGBToLinear(); // Convert linear to RGBE
  28435. var maxComponent = Math.max(background.r, background.g, background.b);
  28436. var fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  28437. background = background.multiplyScalar(Math.pow(2.0, -fExp));
  28438. var alpha = (fExp + 128.0) / 255.0;
  28439. _renderer.setClearColor(background, alpha);
  28440. scene.background = null;
  28441. }
  28442. for (var i = 0; i < 6; i++) {
  28443. var col = i % 3;
  28444. if (col == 0) {
  28445. cubeCamera.up.set(0, upSign[i], 0);
  28446. cubeCamera.lookAt(forwardSign[i], 0, 0);
  28447. } else if (col == 1) {
  28448. cubeCamera.up.set(0, 0, upSign[i]);
  28449. cubeCamera.lookAt(0, forwardSign[i], 0);
  28450. } else {
  28451. cubeCamera.up.set(0, upSign[i], 0);
  28452. cubeCamera.lookAt(0, 0, forwardSign[i]);
  28453. }
  28454. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  28455. _renderer.setRenderTarget(cubeUVRenderTarget);
  28456. _renderer.render(scene, cubeCamera);
  28457. }
  28458. _renderer.toneMapping = toneMapping;
  28459. _renderer.toneMappingExposure = toneMappingExposure;
  28460. _renderer.outputEncoding = outputEncoding;
  28461. _renderer.setClearColor(clearColor, clearAlpha);
  28462. scene.scale.z *= -1;
  28463. }
  28464. function _textureToCubeUV(texture, cubeUVRenderTarget) {
  28465. var scene = new Scene();
  28466. if (texture.isCubeTexture) {
  28467. if (_cubemapShader == null) {
  28468. _cubemapShader = _getCubemapShader();
  28469. }
  28470. } else {
  28471. if (_equirectShader == null) {
  28472. _equirectShader = _getEquirectShader();
  28473. }
  28474. }
  28475. var material = texture.isCubeTexture ? _cubemapShader : _equirectShader;
  28476. scene.add(new Mesh(_lodPlanes[0], material));
  28477. var uniforms = material.uniforms;
  28478. uniforms['envMap'].value = texture;
  28479. if (!texture.isCubeTexture) {
  28480. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  28481. }
  28482. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  28483. uniforms['outputEncoding'].value = ENCODINGS[texture.encoding];
  28484. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  28485. _renderer.setRenderTarget(cubeUVRenderTarget);
  28486. _renderer.render(scene, _flatCamera);
  28487. }
  28488. function _compileMaterial(material) {
  28489. var tmpScene = new Scene();
  28490. tmpScene.add(new Mesh(_lodPlanes[0], material));
  28491. _renderer.compile(tmpScene, _flatCamera);
  28492. }
  28493. function _createRenderTarget(params) {
  28494. var cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  28495. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  28496. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  28497. cubeUVRenderTarget.scissorTest = true;
  28498. return cubeUVRenderTarget;
  28499. }
  28500. function _setViewport(target, x, y, width, height) {
  28501. target.viewport.set(x, y, width, height);
  28502. target.scissor.set(x, y, width, height);
  28503. }
  28504. function _applyPMREM(cubeUVRenderTarget) {
  28505. var autoClear = _renderer.autoClear;
  28506. _renderer.autoClear = false;
  28507. for (var i = 1; i < TOTAL_LODS; i++) {
  28508. var sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  28509. var poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  28510. _blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  28511. }
  28512. _renderer.autoClear = autoClear;
  28513. }
  28514. /**
  28515. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  28516. * vertically and horizontally, but this breaks down on a cube. Here we apply
  28517. * the blur latitudinally (around the poles), and then longitudinally (towards
  28518. * the poles) to approximate the orthogonally-separable blur. It is least
  28519. * accurate at the poles, but still does a decent job.
  28520. */
  28521. function _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  28522. _halfBlur(cubeUVRenderTarget, _pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  28523. _halfBlur(_pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  28524. }
  28525. function _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  28526. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  28527. console.error('blur direction must be either latitudinal or longitudinal!');
  28528. } // Number of standard deviations at which to cut off the discrete approximation.
  28529. var STANDARD_DEVIATIONS = 3;
  28530. var blurScene = new Scene();
  28531. blurScene.add(new Mesh(_lodPlanes[lodOut], _blurMaterial));
  28532. var blurUniforms = _blurMaterial.uniforms;
  28533. var pixels = _sizeLods[lodIn] - 1;
  28534. var radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  28535. var sigmaPixels = sigmaRadians / radiansPerPixel;
  28536. var samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  28537. if (samples > MAX_SAMPLES) {
  28538. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  28539. }
  28540. var weights = [];
  28541. var sum = 0;
  28542. for (var i = 0; i < MAX_SAMPLES; ++i) {
  28543. var x = i / sigmaPixels;
  28544. var weight = Math.exp(-x * x / 2);
  28545. weights.push(weight);
  28546. if (i == 0) {
  28547. sum += weight;
  28548. } else if (i < samples) {
  28549. sum += 2 * weight;
  28550. }
  28551. }
  28552. for (var i = 0; i < weights.length; i++) {
  28553. weights[i] = weights[i] / sum;
  28554. }
  28555. blurUniforms['envMap'].value = targetIn.texture;
  28556. blurUniforms['samples'].value = samples;
  28557. blurUniforms['weights'].value = weights;
  28558. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  28559. if (poleAxis) {
  28560. blurUniforms['poleAxis'].value = poleAxis;
  28561. }
  28562. blurUniforms['dTheta'].value = radiansPerPixel;
  28563. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  28564. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  28565. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  28566. var outputSize = _sizeLods[lodOut];
  28567. var x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  28568. var y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  28569. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  28570. _renderer.setRenderTarget(targetOut);
  28571. _renderer.render(blurScene, _flatCamera);
  28572. }
  28573. function _getBlurShader(maxSamples) {
  28574. var weights = new Float32Array(maxSamples);
  28575. var poleAxis = new Vector3(0, 1, 0);
  28576. var shaderMaterial = new RawShaderMaterial({
  28577. defines: {
  28578. 'n': maxSamples
  28579. },
  28580. uniforms: {
  28581. 'envMap': {
  28582. value: null
  28583. },
  28584. 'samples': {
  28585. value: 1
  28586. },
  28587. 'weights': {
  28588. value: weights
  28589. },
  28590. 'latitudinal': {
  28591. value: false
  28592. },
  28593. 'dTheta': {
  28594. value: 0
  28595. },
  28596. 'mipInt': {
  28597. value: 0
  28598. },
  28599. 'poleAxis': {
  28600. value: poleAxis
  28601. },
  28602. 'inputEncoding': {
  28603. value: ENCODINGS[LinearEncoding]
  28604. },
  28605. 'outputEncoding': {
  28606. value: ENCODINGS[LinearEncoding]
  28607. }
  28608. },
  28609. vertexShader: _getCommonVertexShader(),
  28610. fragmentShader: `
  28611. precision mediump float;
  28612. precision mediump int;
  28613. varying vec3 vOutputDirection;
  28614. uniform sampler2D envMap;
  28615. uniform int samples;
  28616. uniform float weights[n];
  28617. uniform bool latitudinal;
  28618. uniform float dTheta;
  28619. uniform float mipInt;
  28620. uniform vec3 poleAxis;
  28621. ${_getEncodings()}
  28622. #define ENVMAP_TYPE_CUBE_UV
  28623. #include <cube_uv_reflection_fragment>
  28624. vec3 getSample(float theta, vec3 axis) {
  28625. float cosTheta = cos(theta);
  28626. // Rodrigues' axis-angle rotation
  28627. vec3 sampleDirection = vOutputDirection * cosTheta
  28628. + cross(axis, vOutputDirection) * sin(theta)
  28629. + axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);
  28630. return bilinearCubeUV(envMap, sampleDirection, mipInt);
  28631. }
  28632. void main() {
  28633. vec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);
  28634. if (all(equal(axis, vec3(0.0))))
  28635. axis = vec3(vOutputDirection.z, 0.0, - vOutputDirection.x);
  28636. axis = normalize(axis);
  28637. gl_FragColor = vec4(0.0);
  28638. gl_FragColor.rgb += weights[0] * getSample(0.0, axis);
  28639. for (int i = 1; i < n; i++) {
  28640. if (i >= samples)
  28641. break;
  28642. float theta = dTheta * float(i);
  28643. gl_FragColor.rgb += weights[i] * getSample(-1.0 * theta, axis);
  28644. gl_FragColor.rgb += weights[i] * getSample(theta, axis);
  28645. }
  28646. gl_FragColor = linearToOutputTexel(gl_FragColor);
  28647. }
  28648. `,
  28649. blending: NoBlending,
  28650. depthTest: false,
  28651. depthWrite: false
  28652. });
  28653. shaderMaterial.type = 'SphericalGaussianBlur';
  28654. return shaderMaterial;
  28655. }
  28656. function _getEquirectShader() {
  28657. var texelSize = new Vector2(1, 1);
  28658. var shaderMaterial = new RawShaderMaterial({
  28659. uniforms: {
  28660. 'envMap': {
  28661. value: null
  28662. },
  28663. 'texelSize': {
  28664. value: texelSize
  28665. },
  28666. 'inputEncoding': {
  28667. value: ENCODINGS[LinearEncoding]
  28668. },
  28669. 'outputEncoding': {
  28670. value: ENCODINGS[LinearEncoding]
  28671. }
  28672. },
  28673. vertexShader: _getCommonVertexShader(),
  28674. fragmentShader: `
  28675. precision mediump float;
  28676. precision mediump int;
  28677. varying vec3 vOutputDirection;
  28678. uniform sampler2D envMap;
  28679. uniform vec2 texelSize;
  28680. ${_getEncodings()}
  28681. #define RECIPROCAL_PI 0.31830988618
  28682. #define RECIPROCAL_PI2 0.15915494
  28683. void main() {
  28684. gl_FragColor = vec4(0.0);
  28685. vec3 outputDirection = normalize(vOutputDirection);
  28686. vec2 uv;
  28687. uv.y = asin(clamp(outputDirection.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;
  28688. uv.x = atan(outputDirection.z, outputDirection.x) * RECIPROCAL_PI2 + 0.5;
  28689. vec2 f = fract(uv / texelSize - 0.5);
  28690. uv -= f * texelSize;
  28691. vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28692. uv.x += texelSize.x;
  28693. vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28694. uv.y += texelSize.y;
  28695. vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28696. uv.x -= texelSize.x;
  28697. vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28698. vec3 tm = mix(tl, tr, f.x);
  28699. vec3 bm = mix(bl, br, f.x);
  28700. gl_FragColor.rgb = mix(tm, bm, f.y);
  28701. gl_FragColor = linearToOutputTexel(gl_FragColor);
  28702. }
  28703. `,
  28704. blending: NoBlending,
  28705. depthTest: false,
  28706. depthWrite: false
  28707. });
  28708. shaderMaterial.type = 'EquirectangularToCubeUV';
  28709. return shaderMaterial;
  28710. }
  28711. function _getCubemapShader() {
  28712. var shaderMaterial = new RawShaderMaterial({
  28713. uniforms: {
  28714. 'envMap': {
  28715. value: null
  28716. },
  28717. 'inputEncoding': {
  28718. value: ENCODINGS[LinearEncoding]
  28719. },
  28720. 'outputEncoding': {
  28721. value: ENCODINGS[LinearEncoding]
  28722. }
  28723. },
  28724. vertexShader: _getCommonVertexShader(),
  28725. fragmentShader: `
  28726. precision mediump float;
  28727. precision mediump int;
  28728. varying vec3 vOutputDirection;
  28729. uniform samplerCube envMap;
  28730. ${_getEncodings()}
  28731. void main() {
  28732. gl_FragColor = vec4(0.0);
  28733. gl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;
  28734. gl_FragColor = linearToOutputTexel(gl_FragColor);
  28735. }
  28736. `,
  28737. blending: NoBlending,
  28738. depthTest: false,
  28739. depthWrite: false
  28740. });
  28741. shaderMaterial.type = 'CubemapToCubeUV';
  28742. return shaderMaterial;
  28743. }
  28744. function _getCommonVertexShader() {
  28745. return `
  28746. precision mediump float;
  28747. precision mediump int;
  28748. attribute vec3 position;
  28749. attribute vec2 uv;
  28750. attribute float faceIndex;
  28751. varying vec3 vOutputDirection;
  28752. vec3 getDirection(vec2 uv, float face) {
  28753. uv = 2.0 * uv - 1.0;
  28754. vec3 direction = vec3(uv, 1.0);
  28755. if (face == 0.0) {
  28756. direction = direction.zyx;
  28757. direction.z *= -1.0;
  28758. } else if (face == 1.0) {
  28759. direction = direction.xzy;
  28760. direction.z *= -1.0;
  28761. } else if (face == 3.0) {
  28762. direction = direction.zyx;
  28763. direction.x *= -1.0;
  28764. } else if (face == 4.0) {
  28765. direction = direction.xzy;
  28766. direction.y *= -1.0;
  28767. } else if (face == 5.0) {
  28768. direction.xz *= -1.0;
  28769. }
  28770. return direction;
  28771. }
  28772. void main() {
  28773. vOutputDirection = getDirection(uv, faceIndex);
  28774. gl_Position = vec4( position, 1.0 );
  28775. }
  28776. `;
  28777. }
  28778. function _getEncodings() {
  28779. return `
  28780. uniform int inputEncoding;
  28781. uniform int outputEncoding;
  28782. #include <encodings_pars_fragment>
  28783. vec4 inputTexelToLinear(vec4 value){
  28784. if(inputEncoding == 0){
  28785. return value;
  28786. }else if(inputEncoding == 1){
  28787. return sRGBToLinear(value);
  28788. }else if(inputEncoding == 2){
  28789. return RGBEToLinear(value);
  28790. }else if(inputEncoding == 3){
  28791. return RGBMToLinear(value, 7.0);
  28792. }else if(inputEncoding == 4){
  28793. return RGBMToLinear(value, 16.0);
  28794. }else if(inputEncoding == 5){
  28795. return RGBDToLinear(value, 256.0);
  28796. }else{
  28797. return GammaToLinear(value, 2.2);
  28798. }
  28799. }
  28800. vec4 linearToOutputTexel(vec4 value){
  28801. if(outputEncoding == 0){
  28802. return value;
  28803. }else if(outputEncoding == 1){
  28804. return LinearTosRGB(value);
  28805. }else if(outputEncoding == 2){
  28806. return LinearToRGBE(value);
  28807. }else if(outputEncoding == 3){
  28808. return LinearToRGBM(value, 7.0);
  28809. }else if(outputEncoding == 4){
  28810. return LinearToRGBM(value, 16.0);
  28811. }else if(outputEncoding == 5){
  28812. return LinearToRGBD(value, 256.0);
  28813. }else{
  28814. return LinearToGamma(value, 2.2);
  28815. }
  28816. }
  28817. vec4 envMapTexelToLinear(vec4 color) {
  28818. return inputTexelToLinear(color);
  28819. }
  28820. `;
  28821. }
  28822. /**
  28823. * @author mrdoob / http://mrdoob.com/
  28824. */
  28825. function Face4(a, b, c, d, normal, color, materialIndex) {
  28826. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  28827. return new Face3(a, b, c, normal, color, materialIndex);
  28828. }
  28829. var LineStrip = 0;
  28830. exports.LineStrip = LineStrip;
  28831. var LinePieces = 1;
  28832. exports.LinePieces = LinePieces;
  28833. var NoColors = 0;
  28834. exports.NoColors = NoColors;
  28835. var FaceColors = 1;
  28836. exports.FaceColors = FaceColors;
  28837. var VertexColors = 2;
  28838. exports.VertexColors = VertexColors;
  28839. function MeshFaceMaterial(materials) {
  28840. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  28841. return materials;
  28842. }
  28843. function MultiMaterial(materials) {
  28844. if (materials === undefined) materials = [];
  28845. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  28846. materials.isMultiMaterial = true;
  28847. materials.materials = materials;
  28848. materials.clone = function () {
  28849. return materials.slice();
  28850. };
  28851. return materials;
  28852. }
  28853. function PointCloud(geometry, material) {
  28854. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  28855. return new Points(geometry, material);
  28856. }
  28857. function Particle(material) {
  28858. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  28859. return new Sprite(material);
  28860. }
  28861. function ParticleSystem(geometry, material) {
  28862. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  28863. return new Points(geometry, material);
  28864. }
  28865. function PointCloudMaterial(parameters) {
  28866. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  28867. return new PointsMaterial(parameters);
  28868. }
  28869. function ParticleBasicMaterial(parameters) {
  28870. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  28871. return new PointsMaterial(parameters);
  28872. }
  28873. function ParticleSystemMaterial(parameters) {
  28874. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  28875. return new PointsMaterial(parameters);
  28876. }
  28877. function Vertex(x, y, z) {
  28878. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  28879. return new Vector3(x, y, z);
  28880. } //
  28881. function DynamicBufferAttribute(array, itemSize) {
  28882. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  28883. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  28884. }
  28885. function Int8Attribute(array, itemSize) {
  28886. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  28887. return new Int8BufferAttribute(array, itemSize);
  28888. }
  28889. function Uint8Attribute(array, itemSize) {
  28890. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  28891. return new Uint8BufferAttribute(array, itemSize);
  28892. }
  28893. function Uint8ClampedAttribute(array, itemSize) {
  28894. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  28895. return new Uint8ClampedBufferAttribute(array, itemSize);
  28896. }
  28897. function Int16Attribute(array, itemSize) {
  28898. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  28899. return new Int16BufferAttribute(array, itemSize);
  28900. }
  28901. function Uint16Attribute(array, itemSize) {
  28902. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  28903. return new Uint16BufferAttribute(array, itemSize);
  28904. }
  28905. function Int32Attribute(array, itemSize) {
  28906. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  28907. return new Int32BufferAttribute(array, itemSize);
  28908. }
  28909. function Uint32Attribute(array, itemSize) {
  28910. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  28911. return new Uint32BufferAttribute(array, itemSize);
  28912. }
  28913. function Float32Attribute(array, itemSize) {
  28914. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28915. return new Float32BufferAttribute(array, itemSize);
  28916. }
  28917. function Float64Attribute(array, itemSize) {
  28918. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28919. return new Float64BufferAttribute(array, itemSize);
  28920. } //
  28921. Curve.create = function (construct, getPoint) {
  28922. console.log('THREE.Curve.create() has been deprecated');
  28923. construct.prototype = Object.create(Curve.prototype);
  28924. construct.prototype.constructor = construct;
  28925. construct.prototype.getPoint = getPoint;
  28926. return construct;
  28927. }; //
  28928. Object.assign(CurvePath.prototype, {
  28929. createPointsGeometry: function (divisions) {
  28930. 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)
  28931. var pts = this.getPoints(divisions);
  28932. return this.createGeometry(pts);
  28933. },
  28934. createSpacedPointsGeometry: function (divisions) {
  28935. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  28936. var pts = this.getSpacedPoints(divisions);
  28937. return this.createGeometry(pts);
  28938. },
  28939. createGeometry: function (points) {
  28940. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  28941. var geometry = new Geometry();
  28942. for (var i = 0, l = points.length; i < l; i++) {
  28943. var point = points[i];
  28944. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  28945. }
  28946. return geometry;
  28947. }
  28948. }); //
  28949. Object.assign(Path.prototype, {
  28950. fromPoints: function (points) {
  28951. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28952. return this.setFromPoints(points);
  28953. }
  28954. }); //
  28955. function ClosedSplineCurve3(points) {
  28956. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  28957. CatmullRomCurve3.call(this, points);
  28958. this.type = 'catmullrom';
  28959. this.closed = true;
  28960. }
  28961. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  28962. function SplineCurve3(points) {
  28963. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  28964. CatmullRomCurve3.call(this, points);
  28965. this.type = 'catmullrom';
  28966. }
  28967. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  28968. function Spline(points) {
  28969. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  28970. CatmullRomCurve3.call(this, points);
  28971. this.type = 'catmullrom';
  28972. }
  28973. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  28974. Object.assign(Spline.prototype, {
  28975. initFromArray: function ()
  28976. /* a */
  28977. {
  28978. console.error('THREE.Spline: .initFromArray() has been removed.');
  28979. },
  28980. getControlPointsArray: function ()
  28981. /* optionalTarget */
  28982. {
  28983. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  28984. },
  28985. reparametrizeByArcLength: function ()
  28986. /* samplingCoef */
  28987. {
  28988. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  28989. }
  28990. }); //
  28991. function AxisHelper(size) {
  28992. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28993. return new AxesHelper(size);
  28994. }
  28995. function BoundingBoxHelper(object, color) {
  28996. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28997. return new BoxHelper(object, color);
  28998. }
  28999. function EdgesHelper(object, hex) {
  29000. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29001. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29002. color: hex !== undefined ? hex : 0xffffff
  29003. }));
  29004. }
  29005. GridHelper.prototype.setColors = function () {
  29006. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29007. };
  29008. SkeletonHelper.prototype.update = function () {
  29009. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29010. };
  29011. function WireframeHelper(object, hex) {
  29012. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29013. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29014. color: hex !== undefined ? hex : 0xffffff
  29015. }));
  29016. } //
  29017. Object.assign(Loader.prototype, {
  29018. extractUrlBase: function (url) {
  29019. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29020. return LoaderUtils.extractUrlBase(url);
  29021. }
  29022. });
  29023. Loader.Handlers = {
  29024. add: function ()
  29025. /* regex, loader */
  29026. {
  29027. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29028. },
  29029. get: function ()
  29030. /* file */
  29031. {
  29032. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29033. }
  29034. };
  29035. function XHRLoader(manager) {
  29036. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29037. return new FileLoader(manager);
  29038. }
  29039. function BinaryTextureLoader(manager) {
  29040. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29041. return new DataTextureLoader(manager);
  29042. }
  29043. Object.assign(ObjectLoader.prototype, {
  29044. setTexturePath: function (value) {
  29045. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  29046. return this.setResourcePath(value);
  29047. }
  29048. }); //
  29049. Object.assign(Box2.prototype, {
  29050. center: function (optionalTarget) {
  29051. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29052. return this.getCenter(optionalTarget);
  29053. },
  29054. empty: function () {
  29055. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29056. return this.isEmpty();
  29057. },
  29058. isIntersectionBox: function (box) {
  29059. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29060. return this.intersectsBox(box);
  29061. },
  29062. size: function (optionalTarget) {
  29063. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29064. return this.getSize(optionalTarget);
  29065. }
  29066. });
  29067. Object.assign(Box3.prototype, {
  29068. center: function (optionalTarget) {
  29069. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29070. return this.getCenter(optionalTarget);
  29071. },
  29072. empty: function () {
  29073. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29074. return this.isEmpty();
  29075. },
  29076. isIntersectionBox: function (box) {
  29077. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29078. return this.intersectsBox(box);
  29079. },
  29080. isIntersectionSphere: function (sphere) {
  29081. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29082. return this.intersectsSphere(sphere);
  29083. },
  29084. size: function (optionalTarget) {
  29085. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29086. return this.getSize(optionalTarget);
  29087. }
  29088. });
  29089. Frustum.prototype.setFromMatrix = function (m) {
  29090. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  29091. return this.setFromProjectionMatrix(m);
  29092. };
  29093. Line3.prototype.center = function (optionalTarget) {
  29094. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29095. return this.getCenter(optionalTarget);
  29096. };
  29097. Object.assign(MathUtils, {
  29098. random16: function () {
  29099. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29100. return Math.random();
  29101. },
  29102. nearestPowerOfTwo: function (value) {
  29103. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29104. return MathUtils.floorPowerOfTwo(value);
  29105. },
  29106. nextPowerOfTwo: function (value) {
  29107. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29108. return MathUtils.ceilPowerOfTwo(value);
  29109. }
  29110. });
  29111. Object.assign(Matrix3.prototype, {
  29112. flattenToArrayOffset: function (array, offset) {
  29113. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29114. return this.toArray(array, offset);
  29115. },
  29116. multiplyVector3: function (vector) {
  29117. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29118. return vector.applyMatrix3(this);
  29119. },
  29120. multiplyVector3Array: function ()
  29121. /* a */
  29122. {
  29123. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29124. },
  29125. applyToBufferAttribute: function (attribute) {
  29126. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  29127. return attribute.applyMatrix3(this);
  29128. },
  29129. applyToVector3Array: function ()
  29130. /* array, offset, length */
  29131. {
  29132. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29133. }
  29134. });
  29135. Object.assign(Matrix4.prototype, {
  29136. extractPosition: function (m) {
  29137. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29138. return this.copyPosition(m);
  29139. },
  29140. flattenToArrayOffset: function (array, offset) {
  29141. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29142. return this.toArray(array, offset);
  29143. },
  29144. getPosition: function () {
  29145. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29146. return new Vector3().setFromMatrixColumn(this, 3);
  29147. },
  29148. setRotationFromQuaternion: function (q) {
  29149. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29150. return this.makeRotationFromQuaternion(q);
  29151. },
  29152. multiplyToArray: function () {
  29153. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29154. },
  29155. multiplyVector3: function (vector) {
  29156. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29157. return vector.applyMatrix4(this);
  29158. },
  29159. multiplyVector4: function (vector) {
  29160. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29161. return vector.applyMatrix4(this);
  29162. },
  29163. multiplyVector3Array: function ()
  29164. /* a */
  29165. {
  29166. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29167. },
  29168. rotateAxis: function (v) {
  29169. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29170. v.transformDirection(this);
  29171. },
  29172. crossVector: function (vector) {
  29173. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29174. return vector.applyMatrix4(this);
  29175. },
  29176. translate: function () {
  29177. console.error('THREE.Matrix4: .translate() has been removed.');
  29178. },
  29179. rotateX: function () {
  29180. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29181. },
  29182. rotateY: function () {
  29183. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29184. },
  29185. rotateZ: function () {
  29186. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29187. },
  29188. rotateByAxis: function () {
  29189. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29190. },
  29191. applyToBufferAttribute: function (attribute) {
  29192. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  29193. return attribute.applyMatrix4(this);
  29194. },
  29195. applyToVector3Array: function ()
  29196. /* array, offset, length */
  29197. {
  29198. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29199. },
  29200. makeFrustum: function (left, right, bottom, top, near, far) {
  29201. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29202. return this.makePerspective(left, right, top, bottom, near, far);
  29203. }
  29204. });
  29205. Plane.prototype.isIntersectionLine = function (line) {
  29206. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29207. return this.intersectsLine(line);
  29208. };
  29209. Quaternion.prototype.multiplyVector3 = function (vector) {
  29210. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29211. return vector.applyQuaternion(this);
  29212. };
  29213. Object.assign(Ray.prototype, {
  29214. isIntersectionBox: function (box) {
  29215. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29216. return this.intersectsBox(box);
  29217. },
  29218. isIntersectionPlane: function (plane) {
  29219. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29220. return this.intersectsPlane(plane);
  29221. },
  29222. isIntersectionSphere: function (sphere) {
  29223. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29224. return this.intersectsSphere(sphere);
  29225. }
  29226. });
  29227. Object.assign(Triangle.prototype, {
  29228. area: function () {
  29229. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29230. return this.getArea();
  29231. },
  29232. barycoordFromPoint: function (point, target) {
  29233. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29234. return this.getBarycoord(point, target);
  29235. },
  29236. midpoint: function (target) {
  29237. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29238. return this.getMidpoint(target);
  29239. },
  29240. normal: function (target) {
  29241. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29242. return this.getNormal(target);
  29243. },
  29244. plane: function (target) {
  29245. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29246. return this.getPlane(target);
  29247. }
  29248. });
  29249. Object.assign(Triangle, {
  29250. barycoordFromPoint: function (point, a, b, c, target) {
  29251. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29252. return Triangle.getBarycoord(point, a, b, c, target);
  29253. },
  29254. normal: function (a, b, c, target) {
  29255. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29256. return Triangle.getNormal(a, b, c, target);
  29257. }
  29258. });
  29259. Object.assign(Shape.prototype, {
  29260. extractAllPoints: function (divisions) {
  29261. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29262. return this.extractPoints(divisions);
  29263. },
  29264. extrude: function (options) {
  29265. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29266. return new ExtrudeGeometry(this, options);
  29267. },
  29268. makeGeometry: function (options) {
  29269. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29270. return new ShapeGeometry(this, options);
  29271. }
  29272. });
  29273. Object.assign(Vector2.prototype, {
  29274. fromAttribute: function (attribute, index, offset) {
  29275. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29276. return this.fromBufferAttribute(attribute, index, offset);
  29277. },
  29278. distanceToManhattan: function (v) {
  29279. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29280. return this.manhattanDistanceTo(v);
  29281. },
  29282. lengthManhattan: function () {
  29283. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29284. return this.manhattanLength();
  29285. }
  29286. });
  29287. Object.assign(Vector3.prototype, {
  29288. setEulerFromRotationMatrix: function () {
  29289. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29290. },
  29291. setEulerFromQuaternion: function () {
  29292. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29293. },
  29294. getPositionFromMatrix: function (m) {
  29295. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29296. return this.setFromMatrixPosition(m);
  29297. },
  29298. getScaleFromMatrix: function (m) {
  29299. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29300. return this.setFromMatrixScale(m);
  29301. },
  29302. getColumnFromMatrix: function (index, matrix) {
  29303. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29304. return this.setFromMatrixColumn(matrix, index);
  29305. },
  29306. applyProjection: function (m) {
  29307. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29308. return this.applyMatrix4(m);
  29309. },
  29310. fromAttribute: function (attribute, index, offset) {
  29311. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29312. return this.fromBufferAttribute(attribute, index, offset);
  29313. },
  29314. distanceToManhattan: function (v) {
  29315. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29316. return this.manhattanDistanceTo(v);
  29317. },
  29318. lengthManhattan: function () {
  29319. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29320. return this.manhattanLength();
  29321. }
  29322. });
  29323. Object.assign(Vector4.prototype, {
  29324. fromAttribute: function (attribute, index, offset) {
  29325. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29326. return this.fromBufferAttribute(attribute, index, offset);
  29327. },
  29328. lengthManhattan: function () {
  29329. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29330. return this.manhattanLength();
  29331. }
  29332. }); //
  29333. Object.assign(Geometry.prototype, {
  29334. computeTangents: function () {
  29335. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29336. },
  29337. computeLineDistances: function () {
  29338. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29339. },
  29340. applyMatrix: function (matrix) {
  29341. console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().');
  29342. return this.applyMatrix4(matrix);
  29343. }
  29344. });
  29345. Object.assign(Object3D.prototype, {
  29346. getChildByName: function (name) {
  29347. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29348. return this.getObjectByName(name);
  29349. },
  29350. renderDepth: function () {
  29351. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29352. },
  29353. translate: function (distance, axis) {
  29354. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29355. return this.translateOnAxis(axis, distance);
  29356. },
  29357. getWorldRotation: function () {
  29358. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29359. },
  29360. applyMatrix: function (matrix) {
  29361. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  29362. return this.applyMatrix4(matrix);
  29363. }
  29364. });
  29365. Object.defineProperties(Object3D.prototype, {
  29366. eulerOrder: {
  29367. get: function () {
  29368. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29369. return this.rotation.order;
  29370. },
  29371. set: function (value) {
  29372. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29373. this.rotation.order = value;
  29374. }
  29375. },
  29376. useQuaternion: {
  29377. get: function () {
  29378. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29379. },
  29380. set: function () {
  29381. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29382. }
  29383. }
  29384. });
  29385. Object.assign(Mesh.prototype, {
  29386. setDrawMode: function () {
  29387. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29388. }
  29389. });
  29390. Object.defineProperties(Mesh.prototype, {
  29391. drawMode: {
  29392. get: function () {
  29393. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  29394. return TrianglesDrawMode;
  29395. },
  29396. set: function () {
  29397. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29398. }
  29399. }
  29400. });
  29401. Object.defineProperties(LOD.prototype, {
  29402. objects: {
  29403. get: function () {
  29404. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29405. return this.levels;
  29406. }
  29407. }
  29408. });
  29409. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  29410. get: function () {
  29411. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29412. },
  29413. set: function () {
  29414. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29415. }
  29416. });
  29417. SkinnedMesh.prototype.initBones = function () {
  29418. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  29419. };
  29420. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  29421. get: function () {
  29422. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29423. return this.arcLengthDivisions;
  29424. },
  29425. set: function (value) {
  29426. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29427. this.arcLengthDivisions = value;
  29428. }
  29429. }); //
  29430. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  29431. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  29432. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  29433. this.setFocalLength(focalLength);
  29434. }; //
  29435. Object.defineProperties(Light.prototype, {
  29436. onlyShadow: {
  29437. set: function () {
  29438. console.warn('THREE.Light: .onlyShadow has been removed.');
  29439. }
  29440. },
  29441. shadowCameraFov: {
  29442. set: function (value) {
  29443. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  29444. this.shadow.camera.fov = value;
  29445. }
  29446. },
  29447. shadowCameraLeft: {
  29448. set: function (value) {
  29449. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  29450. this.shadow.camera.left = value;
  29451. }
  29452. },
  29453. shadowCameraRight: {
  29454. set: function (value) {
  29455. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  29456. this.shadow.camera.right = value;
  29457. }
  29458. },
  29459. shadowCameraTop: {
  29460. set: function (value) {
  29461. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  29462. this.shadow.camera.top = value;
  29463. }
  29464. },
  29465. shadowCameraBottom: {
  29466. set: function (value) {
  29467. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  29468. this.shadow.camera.bottom = value;
  29469. }
  29470. },
  29471. shadowCameraNear: {
  29472. set: function (value) {
  29473. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  29474. this.shadow.camera.near = value;
  29475. }
  29476. },
  29477. shadowCameraFar: {
  29478. set: function (value) {
  29479. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  29480. this.shadow.camera.far = value;
  29481. }
  29482. },
  29483. shadowCameraVisible: {
  29484. set: function () {
  29485. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  29486. }
  29487. },
  29488. shadowBias: {
  29489. set: function (value) {
  29490. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  29491. this.shadow.bias = value;
  29492. }
  29493. },
  29494. shadowDarkness: {
  29495. set: function () {
  29496. console.warn('THREE.Light: .shadowDarkness has been removed.');
  29497. }
  29498. },
  29499. shadowMapWidth: {
  29500. set: function (value) {
  29501. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  29502. this.shadow.mapSize.width = value;
  29503. }
  29504. },
  29505. shadowMapHeight: {
  29506. set: function (value) {
  29507. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  29508. this.shadow.mapSize.height = value;
  29509. }
  29510. }
  29511. }); //
  29512. Object.defineProperties(BufferAttribute.prototype, {
  29513. length: {
  29514. get: function () {
  29515. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  29516. return this.array.length;
  29517. }
  29518. },
  29519. dynamic: {
  29520. get: function () {
  29521. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  29522. return this.usage === DynamicDrawUsage;
  29523. },
  29524. set: function ()
  29525. /* value */
  29526. {
  29527. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  29528. this.setUsage(DynamicDrawUsage);
  29529. }
  29530. }
  29531. });
  29532. Object.assign(BufferAttribute.prototype, {
  29533. setDynamic: function (value) {
  29534. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  29535. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  29536. return this;
  29537. },
  29538. copyIndicesArray: function ()
  29539. /* indices */
  29540. {
  29541. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  29542. },
  29543. setArray: function ()
  29544. /* array */
  29545. {
  29546. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29547. }
  29548. });
  29549. Object.assign(BufferGeometry.prototype, {
  29550. addIndex: function (index) {
  29551. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  29552. this.setIndex(index);
  29553. },
  29554. addAttribute: function (name, attribute) {
  29555. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  29556. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  29557. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  29558. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  29559. }
  29560. if (name === 'index') {
  29561. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  29562. this.setIndex(attribute);
  29563. return this;
  29564. }
  29565. return this.setAttribute(name, attribute);
  29566. },
  29567. addDrawCall: function (start, count, indexOffset) {
  29568. if (indexOffset !== undefined) {
  29569. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  29570. }
  29571. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  29572. this.addGroup(start, count);
  29573. },
  29574. clearDrawCalls: function () {
  29575. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  29576. this.clearGroups();
  29577. },
  29578. computeTangents: function () {
  29579. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  29580. },
  29581. computeOffsets: function () {
  29582. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  29583. },
  29584. removeAttribute: function (name) {
  29585. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  29586. return this.deleteAttribute(name);
  29587. },
  29588. applyMatrix: function (matrix) {
  29589. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  29590. return this.applyMatrix4(matrix);
  29591. }
  29592. });
  29593. Object.defineProperties(BufferGeometry.prototype, {
  29594. drawcalls: {
  29595. get: function () {
  29596. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  29597. return this.groups;
  29598. }
  29599. },
  29600. offsets: {
  29601. get: function () {
  29602. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  29603. return this.groups;
  29604. }
  29605. }
  29606. });
  29607. Object.defineProperties(Raycaster.prototype, {
  29608. linePrecision: {
  29609. get: function () {
  29610. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  29611. return this.params.Line.threshold;
  29612. },
  29613. set: function (value) {
  29614. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  29615. this.params.Line.threshold = value;
  29616. }
  29617. }
  29618. });
  29619. Object.defineProperties(InterleavedBuffer.prototype, {
  29620. dynamic: {
  29621. get: function () {
  29622. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  29623. return this.usage === DynamicDrawUsage;
  29624. },
  29625. set: function (value) {
  29626. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  29627. this.setUsage(value);
  29628. }
  29629. }
  29630. });
  29631. Object.assign(InterleavedBuffer.prototype, {
  29632. setDynamic: function (value) {
  29633. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  29634. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  29635. return this;
  29636. },
  29637. setArray: function ()
  29638. /* array */
  29639. {
  29640. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29641. }
  29642. }); //
  29643. Object.assign(ExtrudeBufferGeometry.prototype, {
  29644. getArrays: function () {
  29645. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  29646. },
  29647. addShapeList: function () {
  29648. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  29649. },
  29650. addShape: function () {
  29651. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  29652. }
  29653. }); //
  29654. Object.defineProperties(Uniform.prototype, {
  29655. dynamic: {
  29656. set: function () {
  29657. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  29658. }
  29659. },
  29660. onUpdate: {
  29661. value: function () {
  29662. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  29663. return this;
  29664. }
  29665. }
  29666. }); //
  29667. Object.defineProperties(Material.prototype, {
  29668. wrapAround: {
  29669. get: function () {
  29670. console.warn('THREE.Material: .wrapAround has been removed.');
  29671. },
  29672. set: function () {
  29673. console.warn('THREE.Material: .wrapAround has been removed.');
  29674. }
  29675. },
  29676. overdraw: {
  29677. get: function () {
  29678. console.warn('THREE.Material: .overdraw has been removed.');
  29679. },
  29680. set: function () {
  29681. console.warn('THREE.Material: .overdraw has been removed.');
  29682. }
  29683. },
  29684. wrapRGB: {
  29685. get: function () {
  29686. console.warn('THREE.Material: .wrapRGB has been removed.');
  29687. return new Color();
  29688. }
  29689. },
  29690. shading: {
  29691. get: function () {
  29692. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29693. },
  29694. set: function (value) {
  29695. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29696. this.flatShading = value === FlatShading;
  29697. }
  29698. },
  29699. stencilMask: {
  29700. get: function () {
  29701. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29702. return this.stencilFuncMask;
  29703. },
  29704. set: function (value) {
  29705. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29706. this.stencilFuncMask = value;
  29707. }
  29708. }
  29709. });
  29710. Object.defineProperties(MeshPhongMaterial.prototype, {
  29711. metal: {
  29712. get: function () {
  29713. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  29714. return false;
  29715. },
  29716. set: function () {
  29717. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  29718. }
  29719. }
  29720. });
  29721. Object.defineProperties(ShaderMaterial.prototype, {
  29722. derivatives: {
  29723. get: function () {
  29724. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29725. return this.extensions.derivatives;
  29726. },
  29727. set: function (value) {
  29728. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29729. this.extensions.derivatives = value;
  29730. }
  29731. }
  29732. }); //
  29733. Object.assign(WebGLRenderer.prototype, {
  29734. clearTarget: function (renderTarget, color, depth, stencil) {
  29735. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  29736. this.setRenderTarget(renderTarget);
  29737. this.clear(color, depth, stencil);
  29738. },
  29739. animate: function (callback) {
  29740. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  29741. this.setAnimationLoop(callback);
  29742. },
  29743. getCurrentRenderTarget: function () {
  29744. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  29745. return this.getRenderTarget();
  29746. },
  29747. getMaxAnisotropy: function () {
  29748. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  29749. return this.capabilities.getMaxAnisotropy();
  29750. },
  29751. getPrecision: function () {
  29752. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  29753. return this.capabilities.precision;
  29754. },
  29755. resetGLState: function () {
  29756. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  29757. return this.state.reset();
  29758. },
  29759. supportsFloatTextures: function () {
  29760. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  29761. return this.extensions.get('OES_texture_float');
  29762. },
  29763. supportsHalfFloatTextures: function () {
  29764. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  29765. return this.extensions.get('OES_texture_half_float');
  29766. },
  29767. supportsStandardDerivatives: function () {
  29768. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  29769. return this.extensions.get('OES_standard_derivatives');
  29770. },
  29771. supportsCompressedTextureS3TC: function () {
  29772. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  29773. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  29774. },
  29775. supportsCompressedTexturePVRTC: function () {
  29776. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  29777. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  29778. },
  29779. supportsBlendMinMax: function () {
  29780. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  29781. return this.extensions.get('EXT_blend_minmax');
  29782. },
  29783. supportsVertexTextures: function () {
  29784. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  29785. return this.capabilities.vertexTextures;
  29786. },
  29787. supportsInstancedArrays: function () {
  29788. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  29789. return this.extensions.get('ANGLE_instanced_arrays');
  29790. },
  29791. enableScissorTest: function (boolean) {
  29792. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  29793. this.setScissorTest(boolean);
  29794. },
  29795. initMaterial: function () {
  29796. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  29797. },
  29798. addPrePlugin: function () {
  29799. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  29800. },
  29801. addPostPlugin: function () {
  29802. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  29803. },
  29804. updateShadowMap: function () {
  29805. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  29806. },
  29807. setFaceCulling: function () {
  29808. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  29809. },
  29810. allocTextureUnit: function () {
  29811. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  29812. },
  29813. setTexture: function () {
  29814. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  29815. },
  29816. setTexture2D: function () {
  29817. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  29818. },
  29819. setTextureCube: function () {
  29820. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  29821. },
  29822. getActiveMipMapLevel: function () {
  29823. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  29824. return this.getActiveMipmapLevel();
  29825. }
  29826. });
  29827. Object.defineProperties(WebGLRenderer.prototype, {
  29828. shadowMapEnabled: {
  29829. get: function () {
  29830. return this.shadowMap.enabled;
  29831. },
  29832. set: function (value) {
  29833. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  29834. this.shadowMap.enabled = value;
  29835. }
  29836. },
  29837. shadowMapType: {
  29838. get: function () {
  29839. return this.shadowMap.type;
  29840. },
  29841. set: function (value) {
  29842. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  29843. this.shadowMap.type = value;
  29844. }
  29845. },
  29846. shadowMapCullFace: {
  29847. get: function () {
  29848. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29849. return undefined;
  29850. },
  29851. set: function ()
  29852. /* value */
  29853. {
  29854. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29855. }
  29856. },
  29857. context: {
  29858. get: function () {
  29859. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  29860. return this.getContext();
  29861. }
  29862. },
  29863. vr: {
  29864. get: function () {
  29865. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  29866. return this.xr;
  29867. }
  29868. },
  29869. gammaInput: {
  29870. get: function () {
  29871. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29872. return false;
  29873. },
  29874. set: function () {
  29875. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29876. }
  29877. },
  29878. gammaOutput: {
  29879. get: function () {
  29880. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29881. return false;
  29882. },
  29883. set: function (value) {
  29884. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29885. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  29886. }
  29887. }
  29888. });
  29889. Object.defineProperties(WebGLShadowMap.prototype, {
  29890. cullFace: {
  29891. get: function () {
  29892. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29893. return undefined;
  29894. },
  29895. set: function ()
  29896. /* cullFace */
  29897. {
  29898. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29899. }
  29900. },
  29901. renderReverseSided: {
  29902. get: function () {
  29903. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29904. return undefined;
  29905. },
  29906. set: function () {
  29907. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29908. }
  29909. },
  29910. renderSingleSided: {
  29911. get: function () {
  29912. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29913. return undefined;
  29914. },
  29915. set: function () {
  29916. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29917. }
  29918. }
  29919. });
  29920. function WebGLRenderTargetCube(width, height, options) {
  29921. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  29922. return new WebGLCubeRenderTarget(width, options);
  29923. } //
  29924. Object.defineProperties(WebGLRenderTarget.prototype, {
  29925. wrapS: {
  29926. get: function () {
  29927. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29928. return this.texture.wrapS;
  29929. },
  29930. set: function (value) {
  29931. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29932. this.texture.wrapS = value;
  29933. }
  29934. },
  29935. wrapT: {
  29936. get: function () {
  29937. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29938. return this.texture.wrapT;
  29939. },
  29940. set: function (value) {
  29941. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29942. this.texture.wrapT = value;
  29943. }
  29944. },
  29945. magFilter: {
  29946. get: function () {
  29947. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29948. return this.texture.magFilter;
  29949. },
  29950. set: function (value) {
  29951. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29952. this.texture.magFilter = value;
  29953. }
  29954. },
  29955. minFilter: {
  29956. get: function () {
  29957. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29958. return this.texture.minFilter;
  29959. },
  29960. set: function (value) {
  29961. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29962. this.texture.minFilter = value;
  29963. }
  29964. },
  29965. anisotropy: {
  29966. get: function () {
  29967. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29968. return this.texture.anisotropy;
  29969. },
  29970. set: function (value) {
  29971. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29972. this.texture.anisotropy = value;
  29973. }
  29974. },
  29975. offset: {
  29976. get: function () {
  29977. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29978. return this.texture.offset;
  29979. },
  29980. set: function (value) {
  29981. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29982. this.texture.offset = value;
  29983. }
  29984. },
  29985. repeat: {
  29986. get: function () {
  29987. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29988. return this.texture.repeat;
  29989. },
  29990. set: function (value) {
  29991. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29992. this.texture.repeat = value;
  29993. }
  29994. },
  29995. format: {
  29996. get: function () {
  29997. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29998. return this.texture.format;
  29999. },
  30000. set: function (value) {
  30001. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30002. this.texture.format = value;
  30003. }
  30004. },
  30005. type: {
  30006. get: function () {
  30007. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30008. return this.texture.type;
  30009. },
  30010. set: function (value) {
  30011. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30012. this.texture.type = value;
  30013. }
  30014. },
  30015. generateMipmaps: {
  30016. get: function () {
  30017. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30018. return this.texture.generateMipmaps;
  30019. },
  30020. set: function (value) {
  30021. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30022. this.texture.generateMipmaps = value;
  30023. }
  30024. }
  30025. }); //
  30026. Object.defineProperties(Audio.prototype, {
  30027. load: {
  30028. value: function (file) {
  30029. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30030. var scope = this;
  30031. var audioLoader = new AudioLoader();
  30032. audioLoader.load(file, function (buffer) {
  30033. scope.setBuffer(buffer);
  30034. });
  30035. return this;
  30036. }
  30037. },
  30038. startTime: {
  30039. set: function () {
  30040. console.warn('THREE.Audio: .startTime is now .play( delay ).');
  30041. }
  30042. }
  30043. });
  30044. AudioAnalyser.prototype.getData = function () {
  30045. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30046. return this.getFrequencyData();
  30047. }; //
  30048. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30049. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30050. return this.update(renderer, scene);
  30051. }; //
  30052. var GeometryUtils = {
  30053. merge: function (geometry1, geometry2, materialIndexOffset) {
  30054. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30055. var matrix;
  30056. if (geometry2.isMesh) {
  30057. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30058. matrix = geometry2.matrix;
  30059. geometry2 = geometry2.geometry;
  30060. }
  30061. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30062. },
  30063. center: function (geometry) {
  30064. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30065. return geometry.center();
  30066. }
  30067. };
  30068. exports.GeometryUtils = GeometryUtils;
  30069. ImageUtils.crossOrigin = undefined;
  30070. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30071. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30072. var loader = new TextureLoader();
  30073. loader.setCrossOrigin(this.crossOrigin);
  30074. var texture = loader.load(url, onLoad, undefined, onError);
  30075. if (mapping) texture.mapping = mapping;
  30076. return texture;
  30077. };
  30078. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30079. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30080. var loader = new CubeTextureLoader();
  30081. loader.setCrossOrigin(this.crossOrigin);
  30082. var texture = loader.load(urls, onLoad, undefined, onError);
  30083. if (mapping) texture.mapping = mapping;
  30084. return texture;
  30085. };
  30086. ImageUtils.loadCompressedTexture = function () {
  30087. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30088. };
  30089. ImageUtils.loadCompressedTextureCube = function () {
  30090. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30091. }; //
  30092. function CanvasRenderer() {
  30093. console.error('THREE.CanvasRenderer has been removed');
  30094. } //
  30095. function JSONLoader() {
  30096. console.error('THREE.JSONLoader has been removed.');
  30097. } //
  30098. var SceneUtils = {
  30099. createMultiMaterialObject: function ()
  30100. /* geometry, materials */
  30101. {
  30102. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30103. },
  30104. detach: function ()
  30105. /* child, parent, scene */
  30106. {
  30107. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30108. },
  30109. attach: function ()
  30110. /* child, scene, parent */
  30111. {
  30112. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30113. }
  30114. }; //
  30115. exports.SceneUtils = SceneUtils;
  30116. function LensFlare() {
  30117. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  30118. }
  30119. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30120. /* eslint-disable no-undef */
  30121. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30122. detail: {
  30123. revision: REVISION
  30124. }
  30125. }));
  30126. /* eslint-enable no-undef */
  30127. }
  30128. },{}],"../node_modules/process/browser.js":[function(require,module,exports) {
  30129. // shim for using process in browser
  30130. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  30131. // don't break things. But we need to wrap it in a try catch in case it is
  30132. // wrapped in strict mode code which doesn't define any globals. It's inside a
  30133. // function because try/catches deoptimize in certain engines.
  30134. var cachedSetTimeout;
  30135. var cachedClearTimeout;
  30136. function defaultSetTimout() {
  30137. throw new Error('setTimeout has not been defined');
  30138. }
  30139. function defaultClearTimeout() {
  30140. throw new Error('clearTimeout has not been defined');
  30141. }
  30142. (function () {
  30143. try {
  30144. if (typeof setTimeout === 'function') {
  30145. cachedSetTimeout = setTimeout;
  30146. } else {
  30147. cachedSetTimeout = defaultSetTimout;
  30148. }
  30149. } catch (e) {
  30150. cachedSetTimeout = defaultSetTimout;
  30151. }
  30152. try {
  30153. if (typeof clearTimeout === 'function') {
  30154. cachedClearTimeout = clearTimeout;
  30155. } else {
  30156. cachedClearTimeout = defaultClearTimeout;
  30157. }
  30158. } catch (e) {
  30159. cachedClearTimeout = defaultClearTimeout;
  30160. }
  30161. })();
  30162. function runTimeout(fun) {
  30163. if (cachedSetTimeout === setTimeout) {
  30164. //normal enviroments in sane situations
  30165. return setTimeout(fun, 0);
  30166. } // if setTimeout wasn't available but was latter defined
  30167. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  30168. cachedSetTimeout = setTimeout;
  30169. return setTimeout(fun, 0);
  30170. }
  30171. try {
  30172. // when when somebody has screwed with setTimeout but no I.E. maddness
  30173. return cachedSetTimeout(fun, 0);
  30174. } catch (e) {
  30175. try {
  30176. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30177. return cachedSetTimeout.call(null, fun, 0);
  30178. } catch (e) {
  30179. // 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
  30180. return cachedSetTimeout.call(this, fun, 0);
  30181. }
  30182. }
  30183. }
  30184. function runClearTimeout(marker) {
  30185. if (cachedClearTimeout === clearTimeout) {
  30186. //normal enviroments in sane situations
  30187. return clearTimeout(marker);
  30188. } // if clearTimeout wasn't available but was latter defined
  30189. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  30190. cachedClearTimeout = clearTimeout;
  30191. return clearTimeout(marker);
  30192. }
  30193. try {
  30194. // when when somebody has screwed with setTimeout but no I.E. maddness
  30195. return cachedClearTimeout(marker);
  30196. } catch (e) {
  30197. try {
  30198. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30199. return cachedClearTimeout.call(null, marker);
  30200. } catch (e) {
  30201. // 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.
  30202. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  30203. return cachedClearTimeout.call(this, marker);
  30204. }
  30205. }
  30206. }
  30207. var queue = [];
  30208. var draining = false;
  30209. var currentQueue;
  30210. var queueIndex = -1;
  30211. function cleanUpNextTick() {
  30212. if (!draining || !currentQueue) {
  30213. return;
  30214. }
  30215. draining = false;
  30216. if (currentQueue.length) {
  30217. queue = currentQueue.concat(queue);
  30218. } else {
  30219. queueIndex = -1;
  30220. }
  30221. if (queue.length) {
  30222. drainQueue();
  30223. }
  30224. }
  30225. function drainQueue() {
  30226. if (draining) {
  30227. return;
  30228. }
  30229. var timeout = runTimeout(cleanUpNextTick);
  30230. draining = true;
  30231. var len = queue.length;
  30232. while (len) {
  30233. currentQueue = queue;
  30234. queue = [];
  30235. while (++queueIndex < len) {
  30236. if (currentQueue) {
  30237. currentQueue[queueIndex].run();
  30238. }
  30239. }
  30240. queueIndex = -1;
  30241. len = queue.length;
  30242. }
  30243. currentQueue = null;
  30244. draining = false;
  30245. runClearTimeout(timeout);
  30246. }
  30247. process.nextTick = function (fun) {
  30248. var args = new Array(arguments.length - 1);
  30249. if (arguments.length > 1) {
  30250. for (var i = 1; i < arguments.length; i++) {
  30251. args[i - 1] = arguments[i];
  30252. }
  30253. }
  30254. queue.push(new Item(fun, args));
  30255. if (queue.length === 1 && !draining) {
  30256. runTimeout(drainQueue);
  30257. }
  30258. }; // v8 likes predictible objects
  30259. function Item(fun, array) {
  30260. this.fun = fun;
  30261. this.array = array;
  30262. }
  30263. Item.prototype.run = function () {
  30264. this.fun.apply(null, this.array);
  30265. };
  30266. process.title = 'browser';
  30267. process.env = {};
  30268. process.argv = [];
  30269. process.version = ''; // empty string to avoid regexp issues
  30270. process.versions = {};
  30271. function noop() {}
  30272. process.on = noop;
  30273. process.addListener = noop;
  30274. process.once = noop;
  30275. process.off = noop;
  30276. process.removeListener = noop;
  30277. process.removeAllListeners = noop;
  30278. process.emit = noop;
  30279. process.prependListener = noop;
  30280. process.prependOnceListener = noop;
  30281. process.listeners = function (name) {
  30282. return [];
  30283. };
  30284. process.binding = function (name) {
  30285. throw new Error('process.binding is not supported');
  30286. };
  30287. process.cwd = function () {
  30288. return '/';
  30289. };
  30290. process.chdir = function (dir) {
  30291. throw new Error('process.chdir is not supported');
  30292. };
  30293. process.umask = function () {
  30294. return 0;
  30295. };
  30296. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  30297. var process = require("process");
  30298. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  30299. // backported and transplited with Babel, with backwards-compat fixes
  30300. // Copyright Joyent, Inc. and other Node contributors.
  30301. //
  30302. // Permission is hereby granted, free of charge, to any person obtaining a
  30303. // copy of this software and associated documentation files (the
  30304. // "Software"), to deal in the Software without restriction, including
  30305. // without limitation the rights to use, copy, modify, merge, publish,
  30306. // distribute, sublicense, and/or sell copies of the Software, and to permit
  30307. // persons to whom the Software is furnished to do so, subject to the
  30308. // following conditions:
  30309. //
  30310. // The above copyright notice and this permission notice shall be included
  30311. // in all copies or substantial portions of the Software.
  30312. //
  30313. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30314. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30315. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  30316. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  30317. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  30318. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  30319. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  30320. // resolves . and .. elements in a path array with directory names there
  30321. // must be no slashes, empty elements, or device names (c:\) in the array
  30322. // (so also no leading and trailing slashes - it does not distinguish
  30323. // relative and absolute paths)
  30324. function normalizeArray(parts, allowAboveRoot) {
  30325. // if the path tries to go above the root, `up` ends up > 0
  30326. var up = 0;
  30327. for (var i = parts.length - 1; i >= 0; i--) {
  30328. var last = parts[i];
  30329. if (last === '.') {
  30330. parts.splice(i, 1);
  30331. } else if (last === '..') {
  30332. parts.splice(i, 1);
  30333. up++;
  30334. } else if (up) {
  30335. parts.splice(i, 1);
  30336. up--;
  30337. }
  30338. }
  30339. // if the path is allowed to go above the root, restore leading ..s
  30340. if (allowAboveRoot) {
  30341. for (; up--; up) {
  30342. parts.unshift('..');
  30343. }
  30344. }
  30345. return parts;
  30346. }
  30347. // path.resolve([from ...], to)
  30348. // posix version
  30349. exports.resolve = function() {
  30350. var resolvedPath = '',
  30351. resolvedAbsolute = false;
  30352. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  30353. var path = (i >= 0) ? arguments[i] : process.cwd();
  30354. // Skip empty and invalid entries
  30355. if (typeof path !== 'string') {
  30356. throw new TypeError('Arguments to path.resolve must be strings');
  30357. } else if (!path) {
  30358. continue;
  30359. }
  30360. resolvedPath = path + '/' + resolvedPath;
  30361. resolvedAbsolute = path.charAt(0) === '/';
  30362. }
  30363. // At this point the path should be resolved to a full absolute path, but
  30364. // handle relative paths to be safe (might happen when process.cwd() fails)
  30365. // Normalize the path
  30366. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  30367. return !!p;
  30368. }), !resolvedAbsolute).join('/');
  30369. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  30370. };
  30371. // path.normalize(path)
  30372. // posix version
  30373. exports.normalize = function(path) {
  30374. var isAbsolute = exports.isAbsolute(path),
  30375. trailingSlash = substr(path, -1) === '/';
  30376. // Normalize the path
  30377. path = normalizeArray(filter(path.split('/'), function(p) {
  30378. return !!p;
  30379. }), !isAbsolute).join('/');
  30380. if (!path && !isAbsolute) {
  30381. path = '.';
  30382. }
  30383. if (path && trailingSlash) {
  30384. path += '/';
  30385. }
  30386. return (isAbsolute ? '/' : '') + path;
  30387. };
  30388. // posix version
  30389. exports.isAbsolute = function(path) {
  30390. return path.charAt(0) === '/';
  30391. };
  30392. // posix version
  30393. exports.join = function() {
  30394. var paths = Array.prototype.slice.call(arguments, 0);
  30395. return exports.normalize(filter(paths, function(p, index) {
  30396. if (typeof p !== 'string') {
  30397. throw new TypeError('Arguments to path.join must be strings');
  30398. }
  30399. return p;
  30400. }).join('/'));
  30401. };
  30402. // path.relative(from, to)
  30403. // posix version
  30404. exports.relative = function(from, to) {
  30405. from = exports.resolve(from).substr(1);
  30406. to = exports.resolve(to).substr(1);
  30407. function trim(arr) {
  30408. var start = 0;
  30409. for (; start < arr.length; start++) {
  30410. if (arr[start] !== '') break;
  30411. }
  30412. var end = arr.length - 1;
  30413. for (; end >= 0; end--) {
  30414. if (arr[end] !== '') break;
  30415. }
  30416. if (start > end) return [];
  30417. return arr.slice(start, end - start + 1);
  30418. }
  30419. var fromParts = trim(from.split('/'));
  30420. var toParts = trim(to.split('/'));
  30421. var length = Math.min(fromParts.length, toParts.length);
  30422. var samePartsLength = length;
  30423. for (var i = 0; i < length; i++) {
  30424. if (fromParts[i] !== toParts[i]) {
  30425. samePartsLength = i;
  30426. break;
  30427. }
  30428. }
  30429. var outputParts = [];
  30430. for (var i = samePartsLength; i < fromParts.length; i++) {
  30431. outputParts.push('..');
  30432. }
  30433. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  30434. return outputParts.join('/');
  30435. };
  30436. exports.sep = '/';
  30437. exports.delimiter = ':';
  30438. exports.dirname = function (path) {
  30439. if (typeof path !== 'string') path = path + '';
  30440. if (path.length === 0) return '.';
  30441. var code = path.charCodeAt(0);
  30442. var hasRoot = code === 47 /*/*/;
  30443. var end = -1;
  30444. var matchedSlash = true;
  30445. for (var i = path.length - 1; i >= 1; --i) {
  30446. code = path.charCodeAt(i);
  30447. if (code === 47 /*/*/) {
  30448. if (!matchedSlash) {
  30449. end = i;
  30450. break;
  30451. }
  30452. } else {
  30453. // We saw the first non-path separator
  30454. matchedSlash = false;
  30455. }
  30456. }
  30457. if (end === -1) return hasRoot ? '/' : '.';
  30458. if (hasRoot && end === 1) {
  30459. // return '//';
  30460. // Backwards-compat fix:
  30461. return '/';
  30462. }
  30463. return path.slice(0, end);
  30464. };
  30465. function basename(path) {
  30466. if (typeof path !== 'string') path = path + '';
  30467. var start = 0;
  30468. var end = -1;
  30469. var matchedSlash = true;
  30470. var i;
  30471. for (i = path.length - 1; i >= 0; --i) {
  30472. if (path.charCodeAt(i) === 47 /*/*/) {
  30473. // If we reached a path separator that was not part of a set of path
  30474. // separators at the end of the string, stop now
  30475. if (!matchedSlash) {
  30476. start = i + 1;
  30477. break;
  30478. }
  30479. } else if (end === -1) {
  30480. // We saw the first non-path separator, mark this as the end of our
  30481. // path component
  30482. matchedSlash = false;
  30483. end = i + 1;
  30484. }
  30485. }
  30486. if (end === -1) return '';
  30487. return path.slice(start, end);
  30488. }
  30489. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  30490. // in new Node.js versions, so only basename() above is backported here
  30491. exports.basename = function (path, ext) {
  30492. var f = basename(path);
  30493. if (ext && f.substr(-1 * ext.length) === ext) {
  30494. f = f.substr(0, f.length - ext.length);
  30495. }
  30496. return f;
  30497. };
  30498. exports.extname = function (path) {
  30499. if (typeof path !== 'string') path = path + '';
  30500. var startDot = -1;
  30501. var startPart = 0;
  30502. var end = -1;
  30503. var matchedSlash = true;
  30504. // Track the state of characters (if any) we see before our first dot and
  30505. // after any path separator we find
  30506. var preDotState = 0;
  30507. for (var i = path.length - 1; i >= 0; --i) {
  30508. var code = path.charCodeAt(i);
  30509. if (code === 47 /*/*/) {
  30510. // If we reached a path separator that was not part of a set of path
  30511. // separators at the end of the string, stop now
  30512. if (!matchedSlash) {
  30513. startPart = i + 1;
  30514. break;
  30515. }
  30516. continue;
  30517. }
  30518. if (end === -1) {
  30519. // We saw the first non-path separator, mark this as the end of our
  30520. // extension
  30521. matchedSlash = false;
  30522. end = i + 1;
  30523. }
  30524. if (code === 46 /*.*/) {
  30525. // If this is our first dot, mark it as the start of our extension
  30526. if (startDot === -1)
  30527. startDot = i;
  30528. else if (preDotState !== 1)
  30529. preDotState = 1;
  30530. } else if (startDot !== -1) {
  30531. // We saw a non-dot and non-path separator before our dot, so we should
  30532. // have a good chance at having a non-empty extension
  30533. preDotState = -1;
  30534. }
  30535. }
  30536. if (startDot === -1 || end === -1 ||
  30537. // We saw a non-dot character immediately before the dot
  30538. preDotState === 0 ||
  30539. // The (right-most) trimmed path component is exactly '..'
  30540. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  30541. return '';
  30542. }
  30543. return path.slice(startDot, end);
  30544. };
  30545. function filter (xs, f) {
  30546. if (xs.filter) return xs.filter(f);
  30547. var res = [];
  30548. for (var i = 0; i < xs.length; i++) {
  30549. if (f(xs[i], i, xs)) res.push(xs[i]);
  30550. }
  30551. return res;
  30552. }
  30553. // String.prototype.substr - negative index don't work in IE8
  30554. var substr = 'ab'.substr(-1) === 'b'
  30555. ? function (str, start, len) { return str.substr(start, len) }
  30556. : function (str, start, len) {
  30557. if (start < 0) start = str.length + start;
  30558. return str.substr(start, len);
  30559. }
  30560. ;
  30561. },{"process":"../node_modules/process/browser.js"}],"../src/utilities/LRUCache.js":[function(require,module,exports) {
  30562. "use strict";
  30563. Object.defineProperty(exports, "__esModule", {
  30564. value: true
  30565. });
  30566. exports.LRUCache = void 0;
  30567. // TODO: can we remove the use of `indexOf` here because it's potentially slow? Possibly use time and sort as needed?
  30568. // Keep a used list that we can sort as needed when it's dirty, a map of item to last used time, and a binary search
  30569. // of the array to find an item that needs to be removed
  30570. // Fires at the end of the frame and before the next one
  30571. function enqueueMicrotask(callback) {
  30572. Promise.resolve().then(callback);
  30573. }
  30574. class LRUCache {
  30575. constructor() {
  30576. // options
  30577. this.maxSize = 800;
  30578. this.minSize = 600;
  30579. this.unloadPercent = 0.05;
  30580. this.usedSet = new Set();
  30581. this.itemSet = new Set();
  30582. this.itemList = [];
  30583. this.callbacks = new Map();
  30584. this.sortCallback = null;
  30585. } // Returns whether or not the cache has reached the maximum size
  30586. isFull() {
  30587. return this.itemSet.size >= this.maxSize;
  30588. }
  30589. add(item, removeCb) {
  30590. const itemSet = this.itemSet;
  30591. if (itemSet.has(item)) {
  30592. return false;
  30593. }
  30594. if (this.isFull()) {
  30595. return false;
  30596. }
  30597. const usedSet = this.usedSet;
  30598. const itemList = this.itemList;
  30599. const callbacks = this.callbacks;
  30600. itemList.push(item);
  30601. usedSet.add(item);
  30602. itemSet.add(item);
  30603. callbacks.set(item, removeCb);
  30604. return true;
  30605. }
  30606. remove(item) {
  30607. const usedSet = this.usedSet;
  30608. const itemSet = this.itemSet;
  30609. const itemList = this.itemList;
  30610. const callbacks = this.callbacks;
  30611. if (itemSet.has(item)) {
  30612. callbacks.get(item)(item);
  30613. const index = itemList.indexOf(item);
  30614. itemList.splice(index, 1);
  30615. usedSet.delete(item);
  30616. itemSet.delete(item);
  30617. callbacks.delete(item);
  30618. return true;
  30619. }
  30620. return false;
  30621. }
  30622. markUsed(item) {
  30623. const itemSet = this.itemSet;
  30624. const usedSet = this.usedSet;
  30625. if (itemSet.has(item) && !usedSet.has(item)) {
  30626. const itemList = this.itemList;
  30627. const index = itemList.indexOf(item);
  30628. itemList.splice(index, 1);
  30629. itemList.push(item);
  30630. usedSet.add(item);
  30631. }
  30632. }
  30633. markAllUnused() {
  30634. this.usedSet.clear();
  30635. } // TODO: this should be renamed because it's not necessarily unloading all unused content
  30636. // Maybe call it "cleanup" or "unloadToMinSize"
  30637. unloadUnusedContent() {
  30638. const unloadPercent = this.unloadPercent;
  30639. const targetSize = this.minSize;
  30640. const itemList = this.itemList;
  30641. const itemSet = this.itemSet;
  30642. const usedSet = this.usedSet;
  30643. const callbacks = this.callbacks;
  30644. const unused = itemList.length - usedSet.size;
  30645. const excess = itemList.length - targetSize;
  30646. const prioritySortCb = this.sortCallback;
  30647. if (excess > 0 && unused > 0) {
  30648. if (prioritySortCb) {
  30649. // used items should be at the end of the array
  30650. itemList.sort((a, b) => {
  30651. const usedA = usedSet.has(a);
  30652. const usedB = usedSet.has(b);
  30653. if (usedA && usedB) {
  30654. // If they're both used then don't bother moving them
  30655. return 0;
  30656. } else if (!usedA && !usedB) {
  30657. // Use the sort function otherwise
  30658. return prioritySortCb(a, b);
  30659. } else {
  30660. // If one is used and the other is not move the used one towards the end of the array
  30661. return usedA ? 1 : -1;
  30662. }
  30663. });
  30664. } // address corner cases where the minSize might be zero or smaller than maxSize - minSize,
  30665. // which would result in a very small or no items being unloaded.
  30666. const unusedExcess = Math.min(excess, unused);
  30667. const maxUnload = Math.max(targetSize * unloadPercent, unusedExcess * unloadPercent);
  30668. let nodesToUnload = Math.min(maxUnload, unused);
  30669. nodesToUnload = Math.ceil(nodesToUnload);
  30670. const removedItems = itemList.splice(0, nodesToUnload);
  30671. for (let i = 0, l = removedItems.length; i < l; i++) {
  30672. const item = removedItems[i];
  30673. callbacks.get(item)(item);
  30674. itemSet.delete(item);
  30675. callbacks.delete(item);
  30676. }
  30677. }
  30678. }
  30679. scheduleUnload(markAllUnused = true) {
  30680. if (!this.scheduled) {
  30681. this.scheduled = true;
  30682. enqueueMicrotask(() => {
  30683. this.scheduled = false;
  30684. this.unloadUnusedContent();
  30685. if (markAllUnused) {
  30686. this.markAllUnused();
  30687. }
  30688. });
  30689. }
  30690. }
  30691. }
  30692. exports.LRUCache = LRUCache;
  30693. },{}],"../src/utilities/PriorityQueue.js":[function(require,module,exports) {
  30694. "use strict";
  30695. Object.defineProperty(exports, "__esModule", {
  30696. value: true
  30697. });
  30698. exports.PriorityQueue = void 0;
  30699. class PriorityQueue {
  30700. constructor() {
  30701. // options
  30702. this.maxJobs = 6;
  30703. this.items = [];
  30704. this.currJobs = 0;
  30705. this.scheduled = false;
  30706. }
  30707. add(item, priority, callback) {
  30708. return new Promise((resolve, reject) => {
  30709. const prCallback = (...args) => callback(...args).then(resolve).catch(reject);
  30710. const items = this.items;
  30711. for (let i = 0, l = items.length; i < l; i++) {
  30712. const thisItem = items[i];
  30713. if (thisItem.priority > priority) {
  30714. items.splice(i, 0, {
  30715. priority,
  30716. item,
  30717. callback: prCallback
  30718. });
  30719. this.scheduleJobRun();
  30720. return;
  30721. }
  30722. }
  30723. items.push({
  30724. priority,
  30725. item,
  30726. callback: prCallback
  30727. });
  30728. this.scheduleJobRun();
  30729. });
  30730. }
  30731. remove(item) {
  30732. const items = this.items;
  30733. for (let i = 0, l = items.length; i < l; i++) {
  30734. const thisItem = items[i];
  30735. if (thisItem.item === item) {
  30736. items.splice(i, 1);
  30737. break;
  30738. }
  30739. }
  30740. }
  30741. tryRunJobs() {
  30742. const items = this.items;
  30743. const maxJobs = this.maxJobs;
  30744. while (maxJobs > this.currJobs && items.length > 0) {
  30745. this.currJobs++;
  30746. const {
  30747. item,
  30748. priority,
  30749. callback
  30750. } = items.pop();
  30751. callback(item, priority).then(() => {
  30752. this.currJobs--;
  30753. this.scheduleJobRun();
  30754. }).catch(() => {
  30755. this.currJobs--;
  30756. this.scheduleJobRun();
  30757. });
  30758. }
  30759. }
  30760. scheduleJobRun() {
  30761. if (!this.scheduled) {
  30762. Promise.resolve().then(() => {
  30763. this.tryRunJobs();
  30764. this.scheduled = false;
  30765. });
  30766. this.scheduled = true;
  30767. }
  30768. }
  30769. }
  30770. exports.PriorityQueue = PriorityQueue;
  30771. },{}],"../src/base/constants.js":[function(require,module,exports) {
  30772. "use strict";
  30773. Object.defineProperty(exports, "__esModule", {
  30774. value: true
  30775. });
  30776. exports.FAILED = exports.LOADED = exports.PARSING = exports.LOADING = exports.UNLOADED = void 0;
  30777. const UNLOADED = 0;
  30778. exports.UNLOADED = UNLOADED;
  30779. const LOADING = 1;
  30780. exports.LOADING = LOADING;
  30781. const PARSING = 2;
  30782. exports.PARSING = PARSING;
  30783. const LOADED = 3;
  30784. exports.LOADED = LOADED;
  30785. const FAILED = 4;
  30786. exports.FAILED = FAILED;
  30787. },{}],"../src/base/traverseFunctions.js":[function(require,module,exports) {
  30788. "use strict";
  30789. Object.defineProperty(exports, "__esModule", {
  30790. value: true
  30791. });
  30792. exports.traverseSet = traverseSet;
  30793. exports.determineFrustumSet = determineFrustumSet;
  30794. exports.markUsedSetLeaves = markUsedSetLeaves;
  30795. exports.skipTraversal = skipTraversal;
  30796. exports.toggleTiles = toggleTiles;
  30797. var _constants = require("./constants.js");
  30798. // Checks whether this tile was last used on the given frame.
  30799. function isUsedThisFrame(tile, frameCount) {
  30800. return tile.__lastFrameVisited === frameCount && tile.__used;
  30801. } // Resets the frame frame information for the given tile
  30802. function resetFrameState(tile, frameCount) {
  30803. if (tile.__lastFrameVisited !== frameCount) {
  30804. tile.__lastFrameVisited = frameCount;
  30805. tile.__used = false;
  30806. tile.__inFrustum = false;
  30807. tile.__isLeaf = false;
  30808. tile.__visible = false;
  30809. tile.__active = false;
  30810. tile.__error = 0;
  30811. tile.__childrenWereVisible = false;
  30812. }
  30813. } // Recursively mark tiles used down to the next tile with content
  30814. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  30815. resetFrameState(tile, frameCount);
  30816. tile.__used = true;
  30817. lruCache.markUsed(tile);
  30818. if (tile.__contentEmpty) {
  30819. const children = tile.children;
  30820. for (let i = 0, l = children.length; i < l; i++) {
  30821. recursivelyMarkUsed(children[i], frameCount, lruCache);
  30822. }
  30823. }
  30824. } // Helper function for recursively traversing a tileset. If `beforeCb` returns `true` then the
  30825. // traversal will end early.
  30826. function traverseSet(tile, beforeCb = null, afterCb = null, parent = null, depth = 0) {
  30827. if (beforeCb && beforeCb(tile, parent, depth)) {
  30828. if (afterCb) {
  30829. afterCb(tile, parent, depth);
  30830. }
  30831. return;
  30832. }
  30833. const children = tile.children;
  30834. for (let i = 0, l = children.length; i < l; i++) {
  30835. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  30836. }
  30837. if (afterCb) {
  30838. afterCb(tile, parent, depth);
  30839. }
  30840. } // Determine which tiles are within the camera frustum.
  30841. // TODO: include frustum mask here?
  30842. // TODO: this is marking items as used in the lrucache, which means some data is
  30843. // being kept around that isn't being used -- is that okay?
  30844. function determineFrustumSet(tile, renderer) {
  30845. const stats = renderer.stats;
  30846. const frameCount = renderer.frameCount;
  30847. const errorTarget = renderer.errorTarget;
  30848. const maxDepth = renderer.maxDepth;
  30849. const loadSiblings = renderer.loadSiblings;
  30850. const lruCache = renderer.lruCache;
  30851. resetFrameState(tile, frameCount); // Early out if this tile is not within view.
  30852. const inFrustum = renderer.tileInView(tile);
  30853. if (inFrustum === false) {
  30854. return false;
  30855. }
  30856. tile.__used = true;
  30857. lruCache.markUsed(tile);
  30858. tile.__inFrustum = true;
  30859. stats.inFrustum++; // Early out if this tile has less error than we're targeting.
  30860. if (!tile.__contentEmpty) {
  30861. const error = renderer.calculateError(tile);
  30862. tile.__error = error;
  30863. if (error <= errorTarget) {
  30864. return true;
  30865. }
  30866. } // Early out if we've reached the maximum allowed depth.
  30867. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  30868. return true;
  30869. } // Traverse children and see if any children are in view.
  30870. let anyChildrenUsed = false;
  30871. const children = tile.children;
  30872. for (let i = 0, l = children.length; i < l; i++) {
  30873. const c = children[i];
  30874. const r = determineFrustumSet(c, renderer);
  30875. anyChildrenUsed = anyChildrenUsed || r;
  30876. } // If there are children within view and we are loading siblings then mark
  30877. // all sibling tiles as used, as well.
  30878. if (anyChildrenUsed && loadSiblings) {
  30879. for (let i = 0, l = children.length; i < l; i++) {
  30880. const c = children[i];
  30881. recursivelyMarkUsed(c, frameCount, lruCache);
  30882. }
  30883. }
  30884. return true;
  30885. } // Traverse and mark the tiles that are at the leaf nodes of the "used" tree.
  30886. function markUsedSetLeaves(tile, renderer) {
  30887. const stats = renderer.stats;
  30888. const frameCount = renderer.frameCount;
  30889. if (!isUsedThisFrame(tile, frameCount)) {
  30890. return;
  30891. }
  30892. stats.used++; // This tile is a leaf if none of the children had been used.
  30893. const children = tile.children;
  30894. let anyChildrenUsed = false;
  30895. for (let i = 0, l = children.length; i < l; i++) {
  30896. const c = children[i];
  30897. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  30898. }
  30899. if (!anyChildrenUsed) {
  30900. // TODO: This isn't necessarily right because it's possible that a parent tile is considered in the
  30901. // frustum while the child tiles are not, making them unused. If all children have loaded and were properly
  30902. // considered to be in the used set then we shouldn't set ourselves to a leaf here.
  30903. tile.__isLeaf = true; // TODO: stats
  30904. } else {
  30905. let childrenWereVisible = false;
  30906. for (let i = 0, l = children.length; i < l; i++) {
  30907. const c = children[i];
  30908. markUsedSetLeaves(c, renderer);
  30909. childrenWereVisible = childrenWereVisible || c.__wasSetVisible || c.__childrenWereVisible;
  30910. }
  30911. tile.__childrenWereVisible = childrenWereVisible;
  30912. }
  30913. } // Skip past tiles we consider unrenderable because they are outside the error threshold.
  30914. function skipTraversal(tile, renderer) {
  30915. const stats = renderer.stats;
  30916. const frameCount = renderer.frameCount;
  30917. if (!isUsedThisFrame(tile, frameCount)) {
  30918. return;
  30919. } // Request the tile contents or mark it as visible if we've found a leaf.
  30920. const lruCache = renderer.lruCache;
  30921. if (tile.__isLeaf) {
  30922. if (tile.__loadingState === _constants.LOADED) {
  30923. if (tile.__inFrustum) {
  30924. tile.__visible = true;
  30925. stats.visible++;
  30926. }
  30927. tile.__active = true;
  30928. stats.active++;
  30929. } else if (!lruCache.isFull()) {
  30930. renderer.requestTileContents(tile);
  30931. }
  30932. return;
  30933. }
  30934. const errorRequirement = (renderer.errorTarget + 1) * renderer.errorThreshold;
  30935. const meetsSSE = tile.__error <= errorRequirement;
  30936. const hasContent = !tile.__contentEmpty;
  30937. const loadedContent = tile.__loadingState === _constants.LOADED && !tile.__contentEmpty;
  30938. const childrenWereVisible = tile.__childrenWereVisible;
  30939. const children = tile.children;
  30940. let allChildrenHaveContent = true;
  30941. for (let i = 0, l = children.length; i < l; i++) {
  30942. const c = children[i];
  30943. if (isUsedThisFrame(c, frameCount)) {
  30944. // TODO: This doesn't seem right -- we should check down to the next children with content?
  30945. const childContent = c.__loadingState === _constants.LOADED || tile.__contentEmpty;
  30946. allChildrenHaveContent = allChildrenHaveContent && childContent;
  30947. }
  30948. } // If we've met the SSE requirements and we can load content then fire a fetch.
  30949. if (meetsSSE && !loadedContent && !lruCache.isFull() && hasContent) {
  30950. renderer.requestTileContents(tile);
  30951. } // Only mark this tile as visible if it meets the screen space error requirements, has loaded content, not
  30952. // all children have loaded yet, and if no children were visible last frame. We want to keep children visible
  30953. // that _were_ visible to avoid a pop in level of detail as the camera moves around and parent / sibling tiles
  30954. // load in.
  30955. if (meetsSSE && !allChildrenHaveContent && !childrenWereVisible) {
  30956. if (loadedContent) {
  30957. if (tile.__inFrustum) {
  30958. tile.__visible = true;
  30959. stats.visible++;
  30960. }
  30961. tile.__active = true;
  30962. stats.active++; // load the child content if we've found that we've been loaded so we can move down to the next tile
  30963. // layer when the data has loaded.
  30964. for (let i = 0, l = children.length; i < l; i++) {
  30965. const c = children[i];
  30966. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  30967. renderer.requestTileContents(c);
  30968. }
  30969. }
  30970. }
  30971. return;
  30972. }
  30973. for (let i = 0, l = children.length; i < l; i++) {
  30974. const c = children[i];
  30975. if (isUsedThisFrame(c, frameCount)) {
  30976. skipTraversal(c, renderer);
  30977. }
  30978. }
  30979. } // Final traverse to toggle tile visibility.
  30980. function toggleTiles(tile, renderer) {
  30981. const frameCount = renderer.frameCount;
  30982. const isUsed = isUsedThisFrame(tile, frameCount);
  30983. if (isUsed || tile.__usedLastFrame) {
  30984. let setActive = false;
  30985. let setVisible = false;
  30986. if (isUsed) {
  30987. // enable visibility if active due to shadows
  30988. setActive = tile.__active;
  30989. if (renderer.displayActiveTiles) {
  30990. setVisible = tile.__active || tile.__visible;
  30991. } else {
  30992. setVisible = tile.__visible;
  30993. }
  30994. } // If the active or visible state changed then call the functions.
  30995. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  30996. if (tile.__wasSetActive !== setActive) {
  30997. renderer.setTileActive(tile, setActive);
  30998. }
  30999. if (tile.__wasSetVisible !== setVisible) {
  31000. renderer.setTileVisible(tile, setVisible);
  31001. }
  31002. }
  31003. tile.__wasSetActive = setActive;
  31004. tile.__wasSetVisible = setVisible;
  31005. tile.__usedLastFrame = isUsed;
  31006. const children = tile.children;
  31007. for (let i = 0, l = children.length; i < l; i++) {
  31008. const c = children[i];
  31009. toggleTiles(c, renderer);
  31010. }
  31011. }
  31012. }
  31013. },{"./constants.js":"../src/base/constants.js"}],"../src/base/TilesRendererBase.js":[function(require,module,exports) {
  31014. "use strict";
  31015. Object.defineProperty(exports, "__esModule", {
  31016. value: true
  31017. });
  31018. exports.TilesRendererBase = void 0;
  31019. var _path = _interopRequireDefault(require("path"));
  31020. var _LRUCache = require("../utilities/LRUCache.js");
  31021. var _PriorityQueue = require("../utilities/PriorityQueue.js");
  31022. var _traverseFunctions = require("./traverseFunctions.js");
  31023. var _constants = require("./constants.js");
  31024. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31025. // TODO: Address the issue of too many promises, garbage collection
  31026. // TODO: See if using classes improves performance
  31027. // TODO: See if declaring function inline improves performance
  31028. // TODO: Make sure active state works as expected
  31029. // Function for sorting the evicted LRU items. We should evict the shallowest depth first.
  31030. const lruSort = (a, b) => a.__depth - b.__depth;
  31031. class TilesRendererBase {
  31032. get rootTileSet() {
  31033. const tileSet = this.tileSets[this.rootURL];
  31034. if (!tileSet || tileSet instanceof Promise) {
  31035. return null;
  31036. } else {
  31037. return tileSet;
  31038. }
  31039. }
  31040. get root() {
  31041. const tileSet = this.rootTileSet;
  31042. return tileSet ? tileSet.root : null;
  31043. }
  31044. constructor(url) {
  31045. // state
  31046. this.tileSets = {};
  31047. this.rootURL = url;
  31048. this.fetchOptions = {};
  31049. const lruCache = new _LRUCache.LRUCache();
  31050. lruCache.sortCallback = lruSort;
  31051. const downloadQueue = new _PriorityQueue.PriorityQueue();
  31052. downloadQueue.maxJobs = 4;
  31053. const parseQueue = new _PriorityQueue.PriorityQueue();
  31054. parseQueue.maxJobs = 1;
  31055. this.lruCache = lruCache;
  31056. this.downloadQueue = downloadQueue;
  31057. this.parseQueue = parseQueue;
  31058. this.stats = {
  31059. parsing: 0,
  31060. downloading: 0,
  31061. inFrustum: 0,
  31062. used: 0,
  31063. active: 0,
  31064. visible: 0
  31065. };
  31066. this.frameCount = 0; // options
  31067. this.errorTarget = 6.0;
  31068. this.errorThreshold = Infinity;
  31069. this.loadSiblings = true;
  31070. this.displayActiveTiles = false;
  31071. this.maxDepth = Infinity;
  31072. }
  31073. traverse(beforecb, aftercb) {
  31074. const tileSets = this.tileSets;
  31075. const rootTileSet = tileSets[this.rootURL];
  31076. if (!rootTileSet || !rootTileSet.root) return;
  31077. (0, _traverseFunctions.traverseSet)(rootTileSet.root, beforecb, aftercb);
  31078. } // Public API
  31079. update() {
  31080. const stats = this.stats;
  31081. const lruCache = this.lruCache;
  31082. const tileSets = this.tileSets;
  31083. const rootTileSet = tileSets[this.rootURL];
  31084. if (!(this.rootURL in tileSets)) {
  31085. this.loadTileSet(this.rootURL);
  31086. return;
  31087. } else if (!rootTileSet || !rootTileSet.root) {
  31088. return;
  31089. }
  31090. const root = rootTileSet.root;
  31091. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  31092. (0, _traverseFunctions.determineFrustumSet)(root, this);
  31093. (0, _traverseFunctions.markUsedSetLeaves)(root, this);
  31094. (0, _traverseFunctions.skipTraversal)(root, this);
  31095. (0, _traverseFunctions.toggleTiles)(root, this); // TODO: We may want to add this function in the requestTileContents function
  31096. lruCache.scheduleUnload();
  31097. } // Overrideable
  31098. parseTile(buffer, tile, extension) {
  31099. return null;
  31100. }
  31101. disposeTile(tile) {}
  31102. preprocessNode(tile, parentTile, tileSetDir) {
  31103. if (tile.content) {
  31104. // Fix old file formats
  31105. if (!('uri' in tile.content) && 'url' in tile.content) {
  31106. tile.content.uri = tile.content.url;
  31107. delete tile.content.url;
  31108. }
  31109. if (tile.content.uri) {
  31110. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  31111. } // TODO: fix for some cases where tilesets provide the bounding volume
  31112. // but volumes are not present.
  31113. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  31114. delete tile.content.boundingVolume;
  31115. }
  31116. }
  31117. tile.parent = parentTile;
  31118. tile.children = tile.children || [];
  31119. tile.__contentEmpty = !tile.content || !tile.content.uri;
  31120. tile.__error = 0.0;
  31121. tile.__inFrustum = false;
  31122. tile.__isLeaf = false;
  31123. tile.__usedLastFrame = false;
  31124. tile.__used = false;
  31125. tile.__wasSetVisible = false;
  31126. tile.__visible = false;
  31127. tile.__childrenWereVisible = false;
  31128. tile.__wasSetActive = false;
  31129. tile.__active = false;
  31130. tile.__loadingState = _constants.UNLOADED;
  31131. tile.__loadIndex = 0;
  31132. tile.__loadAbort = null;
  31133. if (parentTile === null) {
  31134. tile.__depth = 0;
  31135. } else {
  31136. tile.__depth = parentTile.__depth + 1;
  31137. }
  31138. }
  31139. setTileActive(tile, state) {}
  31140. setTileVisible(tile, state) {}
  31141. calculateError(tile) {
  31142. return 0;
  31143. }
  31144. tileInView(tile) {
  31145. return true;
  31146. } // Private Functions
  31147. loadTileSet(url) {
  31148. const tileSets = this.tileSets;
  31149. if (!(url in tileSets)) {
  31150. const pr = fetch(url, this.fetchOptions).then(res => {
  31151. if (res.ok) {
  31152. return res.json();
  31153. } else {
  31154. throw new Error(`Status ${res.status} (${res.statusText})`);
  31155. }
  31156. }).then(json => {
  31157. // TODO: Add version query?
  31158. const version = json.asset.version;
  31159. console.assert(version === '1.0' || version === '0.0');
  31160. const basePath = _path.default.dirname(url);
  31161. (0, _traverseFunctions.traverseSet)(json.root, (node, parent) => this.preprocessNode(node, parent, basePath));
  31162. tileSets[url] = json;
  31163. });
  31164. pr.catch(e => {
  31165. console.error(`TilesLoader: Failed to load tile set json "${url}"`);
  31166. console.error(e);
  31167. delete tileSets[url];
  31168. });
  31169. tileSets[url] = pr;
  31170. }
  31171. return Promise.resolve(tileSets[url]);
  31172. }
  31173. requestTileContents(tile) {
  31174. // If the tile is already being loaded then don't
  31175. // start it again.
  31176. if (tile.__loadingState !== _constants.UNLOADED) {
  31177. return;
  31178. } // TODO: reuse the functions created here?
  31179. const lruCache = this.lruCache;
  31180. const downloadQueue = this.downloadQueue;
  31181. const parseQueue = this.parseQueue;
  31182. lruCache.add(tile, t => {
  31183. if (t.__loadingState === _constants.LOADING) {
  31184. t.__loadAbort.abort();
  31185. t.__loadAbort = null;
  31186. } else {
  31187. this.disposeTile(t);
  31188. }
  31189. if (t.__loadingState === _constants.LOADING) {
  31190. stats.downloading--;
  31191. } else if (t.__loadingState === _constants.PARSING) {
  31192. stats.parsing--;
  31193. }
  31194. t.__loadingState = _constants.UNLOADED;
  31195. t.__loadIndex++; // TODO: Removing from the queues here is slow?
  31196. parseQueue.remove(t);
  31197. downloadQueue.remove(t);
  31198. });
  31199. tile.__loadIndex++;
  31200. const loadIndex = tile.__loadIndex;
  31201. const priority = 1 / (tile.__depth + 1);
  31202. const stats = this.stats;
  31203. const controller = new AbortController();
  31204. const signal = controller.signal;
  31205. stats.downloading++;
  31206. tile.__loadAbort = controller;
  31207. tile.__loadingState = _constants.LOADING;
  31208. downloadQueue.add(tile, priority, tile => {
  31209. if (tile.__loadIndex !== loadIndex) {
  31210. return Promise.resolve();
  31211. }
  31212. return fetch(tile.content.uri, Object.assign({
  31213. signal
  31214. }, this.fetchOptions));
  31215. }).then(res => {
  31216. if (tile.__loadIndex !== loadIndex) {
  31217. return;
  31218. }
  31219. if (res.ok) {
  31220. return res.arrayBuffer();
  31221. } else {
  31222. throw new Error(`Failed to load model with error code ${res.status}`);
  31223. }
  31224. }).then(buffer => {
  31225. // if it has been unloaded then the tile has been disposed
  31226. if (tile.__loadIndex !== loadIndex) {
  31227. return;
  31228. }
  31229. stats.downloading--;
  31230. stats.parsing++;
  31231. tile.__loadAbort = null;
  31232. tile.__loadingState = _constants.PARSING;
  31233. return parseQueue.add(buffer, priority, buffer => {
  31234. // if it has been unloaded then the tile has been disposed
  31235. if (tile.__loadIndex !== loadIndex) {
  31236. return Promise.resolve();
  31237. }
  31238. const uri = tile.content.uri;
  31239. const extension = uri.split(/\./g).pop();
  31240. return this.parseTile(buffer, tile, extension);
  31241. });
  31242. }).then(() => {
  31243. // if it has been unloaded then the tile has been disposed
  31244. if (tile.__loadIndex !== loadIndex) {
  31245. return;
  31246. }
  31247. stats.parsing--;
  31248. tile.__loadingState = _constants.LOADED;
  31249. if (tile.__wasSetVisible) {
  31250. this.setTileVisible(tile, true);
  31251. }
  31252. if (tile.__wasSetActive) {
  31253. this.setTileActive(tile, true);
  31254. }
  31255. }).catch(e => {
  31256. // if it has been unloaded then the tile has been disposed
  31257. if (tile.__loadIndex !== loadIndex) {
  31258. return;
  31259. }
  31260. if (e.name !== 'AbortError') {
  31261. console.error('TilesRenderer : Failed to load tile.');
  31262. console.error(e);
  31263. tile.__loadingState = _constants.FAILED;
  31264. } else {
  31265. lruCache.remove(tile);
  31266. }
  31267. });
  31268. }
  31269. }
  31270. exports.TilesRendererBase = TilesRendererBase;
  31271. },{"path":"../node_modules/path-browserify/index.js","../utilities/LRUCache.js":"../src/utilities/LRUCache.js","../utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js","./traverseFunctions.js":"../src/base/traverseFunctions.js","./constants.js":"../src/base/constants.js"}],"../src/base/B3DMLoaderBase.js":[function(require,module,exports) {
  31272. "use strict";
  31273. Object.defineProperty(exports, "__esModule", {
  31274. value: true
  31275. });
  31276. exports.B3DMLoaderBase = void 0;
  31277. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  31278. // convert an array of numbers to a string
  31279. function arrayToString(array) {
  31280. let str = '';
  31281. for (let i = 0, l = array.length; i < l; i++) {
  31282. str += String.fromCharCode(array[i]);
  31283. }
  31284. return str;
  31285. }
  31286. class B3DMLoaderBase {
  31287. constructor() {
  31288. this.fetchOptions = {};
  31289. }
  31290. load(url) {
  31291. return fetch(url, this.fetchOptions).then(res => res.arrayBuffer()).then(buffer => this.parse(buffer));
  31292. }
  31293. parse(buffer) {
  31294. const dataView = new DataView(buffer); // 28-byte header
  31295. // 4 bytes
  31296. const magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  31297. console.assert(magic === 'b3dm'); // 4 bytes
  31298. const version = dataView.getUint32(4, true);
  31299. console.assert(version === 1); // 4 bytes
  31300. const byteLength = dataView.getUint32(8, true);
  31301. console.assert(byteLength === buffer.byteLength); // 4 bytes
  31302. const featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  31303. const featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  31304. const batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  31305. const batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  31306. const featureTableStart = 28;
  31307. const jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  31308. const jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData));
  31309. const featureTable = { ...jsonFeatureTable
  31310. }; // const binFeatureTableData = new Uint8Array( buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength );
  31311. // TODO: dereference the json feature table data in to the binary array.
  31312. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  31313. // TODO: The feature table contains data with implicit stride and data types, which means we can't parse it into arrays
  31314. // unless they are specified ahead of time?s
  31315. // Batch Table
  31316. const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  31317. const jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  31318. const jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData));
  31319. const batchTable = { ...jsonBatchTable
  31320. }; // dereference the json batch table data in to the binary array.
  31321. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  31322. // const binBatchTableData = new Uint8Array( buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength );
  31323. const batchLength = jsonFeatureTable.BATCH_LENGTH;
  31324. for (const key in jsonBatchTable) {
  31325. const feature = jsonBatchTable[key];
  31326. if (Array.isArray(feature)) {
  31327. batchTable[key] = {
  31328. type: 'SCALAR',
  31329. stride: 1,
  31330. data: feature
  31331. };
  31332. } else {
  31333. let stride;
  31334. let data;
  31335. const arrayStart = batchTableStart + batchTableJSONByteLength;
  31336. const arrayLength = batchLength * stride + feature.byteOffset;
  31337. switch (feature.type) {
  31338. case 'SCALAR':
  31339. stride = 1;
  31340. break;
  31341. case 'VEC2':
  31342. stride = 2;
  31343. break;
  31344. case 'VEC3':
  31345. stride = 3;
  31346. break;
  31347. case 'VEC4':
  31348. stride = 4;
  31349. break;
  31350. }
  31351. switch (feature.componentType) {
  31352. case 'BYTE':
  31353. data = new Int8Array(buffer, arrayStart, arrayLength);
  31354. break;
  31355. case 'UNSIGNED_BYTE':
  31356. data = new Uint8Array(buffer, arrayStart, arrayLength);
  31357. break;
  31358. case 'SHORT':
  31359. data = new Int16Array(buffer, arrayStart, arrayLength);
  31360. break;
  31361. case 'UNSIGNED_SHORT':
  31362. data = new Uint16Array(buffer, arrayStart, arrayLength);
  31363. break;
  31364. case 'INT':
  31365. data = new Int32Array(buffer, arrayStart, arrayLength);
  31366. break;
  31367. case 'UNSIGNED_INT':
  31368. data = new Uint32Array(buffer, arrayStart, arrayLength);
  31369. break;
  31370. case 'FLOAT':
  31371. data = new Float32Array(buffer, arrayStart, arrayLength);
  31372. break;
  31373. case 'DOUBLE':
  31374. data = new Float64Array(buffer, arrayStart, arrayLength);
  31375. break;
  31376. }
  31377. batchTable[key] = {
  31378. type: feature.type,
  31379. stride,
  31380. data
  31381. };
  31382. }
  31383. }
  31384. const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  31385. const glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  31386. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  31387. return {
  31388. version,
  31389. featureTable,
  31390. batchTable,
  31391. glbBytes
  31392. };
  31393. }
  31394. }
  31395. exports.B3DMLoaderBase = B3DMLoaderBase;
  31396. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  31397. "use strict";
  31398. Object.defineProperty(exports, "__esModule", {
  31399. value: true
  31400. });
  31401. exports.GLTFLoader = void 0;
  31402. var _threeModule = require("../../../build/three.module.js");
  31403. /**
  31404. * @author Rich Tibbett / https://github.com/richtr
  31405. * @author mrdoob / http://mrdoob.com/
  31406. * @author Tony Parisi / http://www.tonyparisi.com/
  31407. * @author Takahiro / https://github.com/takahirox
  31408. * @author Don McCurdy / https://www.donmccurdy.com
  31409. */
  31410. var GLTFLoader = function () {
  31411. function GLTFLoader(manager) {
  31412. _threeModule.Loader.call(this, manager);
  31413. this.dracoLoader = null;
  31414. this.ddsLoader = null;
  31415. }
  31416. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  31417. constructor: GLTFLoader,
  31418. load: function (url, onLoad, onProgress, onError) {
  31419. var scope = this;
  31420. var resourcePath;
  31421. if (this.resourcePath !== '') {
  31422. resourcePath = this.resourcePath;
  31423. } else if (this.path !== '') {
  31424. resourcePath = this.path;
  31425. } else {
  31426. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  31427. } // Tells the LoadingManager to track an extra item, which resolves after
  31428. // the model is fully loaded. This means the count of items loaded will
  31429. // be incorrect, but ensures manager.onLoad() does not fire early.
  31430. scope.manager.itemStart(url);
  31431. var _onError = function (e) {
  31432. if (onError) {
  31433. onError(e);
  31434. } else {
  31435. console.error(e);
  31436. }
  31437. scope.manager.itemError(url);
  31438. scope.manager.itemEnd(url);
  31439. };
  31440. var loader = new _threeModule.FileLoader(scope.manager);
  31441. loader.setPath(this.path);
  31442. loader.setResponseType('arraybuffer');
  31443. if (scope.crossOrigin === 'use-credentials') {
  31444. loader.setWithCredentials(true);
  31445. }
  31446. loader.load(url, function (data) {
  31447. try {
  31448. scope.parse(data, resourcePath, function (gltf) {
  31449. onLoad(gltf);
  31450. scope.manager.itemEnd(url);
  31451. }, _onError);
  31452. } catch (e) {
  31453. _onError(e);
  31454. }
  31455. }, onProgress, _onError);
  31456. },
  31457. setDRACOLoader: function (dracoLoader) {
  31458. this.dracoLoader = dracoLoader;
  31459. return this;
  31460. },
  31461. setDDSLoader: function (ddsLoader) {
  31462. this.ddsLoader = ddsLoader;
  31463. return this;
  31464. },
  31465. parse: function (data, path, onLoad, onError) {
  31466. var content;
  31467. var extensions = {};
  31468. if (typeof data === 'string') {
  31469. content = data;
  31470. } else {
  31471. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  31472. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  31473. try {
  31474. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  31475. } catch (error) {
  31476. if (onError) onError(error);
  31477. return;
  31478. }
  31479. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  31480. } else {
  31481. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  31482. }
  31483. }
  31484. var json = JSON.parse(content);
  31485. if (json.asset === undefined || json.asset.version[0] < 2) {
  31486. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.'));
  31487. return;
  31488. }
  31489. if (json.extensionsUsed) {
  31490. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  31491. var extensionName = json.extensionsUsed[i];
  31492. var extensionsRequired = json.extensionsRequired || [];
  31493. switch (extensionName) {
  31494. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  31495. extensions[extensionName] = new GLTFLightsExtension(json);
  31496. break;
  31497. case EXTENSIONS.KHR_MATERIALS_CLEARCOAT:
  31498. extensions[extensionName] = new GLTFMaterialsClearcoatExtension();
  31499. break;
  31500. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  31501. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  31502. break;
  31503. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  31504. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  31505. break;
  31506. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  31507. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  31508. break;
  31509. case EXTENSIONS.MSFT_TEXTURE_DDS:
  31510. extensions[extensionName] = new GLTFTextureDDSExtension(this.ddsLoader);
  31511. break;
  31512. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  31513. extensions[extensionName] = new GLTFTextureTransformExtension();
  31514. break;
  31515. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  31516. extensions[extensionName] = new GLTFMeshQuantizationExtension();
  31517. break;
  31518. default:
  31519. if (extensionsRequired.indexOf(extensionName) >= 0) {
  31520. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  31521. }
  31522. }
  31523. }
  31524. }
  31525. var parser = new GLTFParser(json, extensions, {
  31526. path: path || this.resourcePath || '',
  31527. crossOrigin: this.crossOrigin,
  31528. manager: this.manager
  31529. });
  31530. parser.parse(onLoad, onError);
  31531. }
  31532. });
  31533. /* GLTFREGISTRY */
  31534. function GLTFRegistry() {
  31535. var objects = {};
  31536. return {
  31537. get: function (key) {
  31538. return objects[key];
  31539. },
  31540. add: function (key, object) {
  31541. objects[key] = object;
  31542. },
  31543. remove: function (key) {
  31544. delete objects[key];
  31545. },
  31546. removeAll: function () {
  31547. objects = {};
  31548. }
  31549. };
  31550. }
  31551. /*********************************/
  31552. /********** EXTENSIONS ***********/
  31553. /*********************************/
  31554. var EXTENSIONS = {
  31555. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  31556. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  31557. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  31558. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  31559. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  31560. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  31561. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  31562. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  31563. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  31564. };
  31565. /**
  31566. * DDS Texture Extension
  31567. *
  31568. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  31569. *
  31570. */
  31571. function GLTFTextureDDSExtension(ddsLoader) {
  31572. if (!ddsLoader) {
  31573. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  31574. }
  31575. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  31576. this.ddsLoader = ddsLoader;
  31577. }
  31578. /**
  31579. * Punctual Lights Extension
  31580. *
  31581. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  31582. */
  31583. function GLTFLightsExtension(json) {
  31584. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  31585. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  31586. this.lightDefs = extension.lights || [];
  31587. }
  31588. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  31589. var lightDef = this.lightDefs[lightIndex];
  31590. var lightNode;
  31591. var color = new _threeModule.Color(0xffffff);
  31592. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  31593. var range = lightDef.range !== undefined ? lightDef.range : 0;
  31594. switch (lightDef.type) {
  31595. case 'directional':
  31596. lightNode = new _threeModule.DirectionalLight(color);
  31597. lightNode.target.position.set(0, 0, -1);
  31598. lightNode.add(lightNode.target);
  31599. break;
  31600. case 'point':
  31601. lightNode = new _threeModule.PointLight(color);
  31602. lightNode.distance = range;
  31603. break;
  31604. case 'spot':
  31605. lightNode = new _threeModule.SpotLight(color);
  31606. lightNode.distance = range; // Handle spotlight properties.
  31607. lightDef.spot = lightDef.spot || {};
  31608. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  31609. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  31610. lightNode.angle = lightDef.spot.outerConeAngle;
  31611. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  31612. lightNode.target.position.set(0, 0, -1);
  31613. lightNode.add(lightNode.target);
  31614. break;
  31615. default:
  31616. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  31617. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  31618. // here, because node-level parsing will only override position if explicitly specified.
  31619. lightNode.position.set(0, 0, 0);
  31620. lightNode.decay = 2;
  31621. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  31622. lightNode.name = lightDef.name || 'light_' + lightIndex;
  31623. return Promise.resolve(lightNode);
  31624. };
  31625. /**
  31626. * Unlit Materials Extension
  31627. *
  31628. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  31629. */
  31630. function GLTFMaterialsUnlitExtension() {
  31631. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  31632. }
  31633. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  31634. return _threeModule.MeshBasicMaterial;
  31635. };
  31636. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  31637. var pending = [];
  31638. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31639. materialParams.opacity = 1.0;
  31640. var metallicRoughness = materialDef.pbrMetallicRoughness;
  31641. if (metallicRoughness) {
  31642. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31643. var array = metallicRoughness.baseColorFactor;
  31644. materialParams.color.fromArray(array);
  31645. materialParams.opacity = array[3];
  31646. }
  31647. if (metallicRoughness.baseColorTexture !== undefined) {
  31648. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31649. }
  31650. }
  31651. return Promise.all(pending);
  31652. };
  31653. /**
  31654. * Clearcoat Materials Extension
  31655. *
  31656. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  31657. */
  31658. function GLTFMaterialsClearcoatExtension() {
  31659. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  31660. }
  31661. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function () {
  31662. return _threeModule.MeshPhysicalMaterial;
  31663. };
  31664. GLTFMaterialsClearcoatExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  31665. var pending = [];
  31666. var extension = materialDef.extensions[this.name];
  31667. if (extension.clearcoatFactor !== undefined) {
  31668. materialParams.clearcoat = extension.clearcoatFactor;
  31669. }
  31670. if (extension.clearcoatTexture !== undefined) {
  31671. pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture));
  31672. }
  31673. if (extension.clearcoatRoughnessFactor !== undefined) {
  31674. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  31675. }
  31676. if (extension.clearcoatRoughnessTexture !== undefined) {
  31677. pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture));
  31678. }
  31679. if (extension.clearcoatNormalTexture !== undefined) {
  31680. pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture));
  31681. if (extension.clearcoatNormalTexture.scale !== undefined) {
  31682. var scale = extension.clearcoatNormalTexture.scale;
  31683. materialParams.clearcoatNormalScale = new _threeModule.Vector2(scale, scale);
  31684. }
  31685. }
  31686. return Promise.all(pending);
  31687. };
  31688. /* BINARY EXTENSION */
  31689. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  31690. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  31691. var BINARY_EXTENSION_CHUNK_TYPES = {
  31692. JSON: 0x4E4F534A,
  31693. BIN: 0x004E4942
  31694. };
  31695. function GLTFBinaryExtension(data) {
  31696. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  31697. this.content = null;
  31698. this.body = null;
  31699. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  31700. this.header = {
  31701. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  31702. version: headerView.getUint32(4, true),
  31703. length: headerView.getUint32(8, true)
  31704. };
  31705. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  31706. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  31707. } else if (this.header.version < 2.0) {
  31708. throw new Error('THREE.GLTFLoader: Legacy binary file detected.');
  31709. }
  31710. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  31711. var chunkIndex = 0;
  31712. while (chunkIndex < chunkView.byteLength) {
  31713. var chunkLength = chunkView.getUint32(chunkIndex, true);
  31714. chunkIndex += 4;
  31715. var chunkType = chunkView.getUint32(chunkIndex, true);
  31716. chunkIndex += 4;
  31717. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  31718. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  31719. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  31720. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  31721. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  31722. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  31723. } // Clients must ignore chunks with unknown types.
  31724. chunkIndex += chunkLength;
  31725. }
  31726. if (this.content === null) {
  31727. throw new Error('THREE.GLTFLoader: JSON content not found.');
  31728. }
  31729. }
  31730. /**
  31731. * DRACO Mesh Compression Extension
  31732. *
  31733. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  31734. */
  31735. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  31736. if (!dracoLoader) {
  31737. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  31738. }
  31739. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  31740. this.json = json;
  31741. this.dracoLoader = dracoLoader;
  31742. this.dracoLoader.preload();
  31743. }
  31744. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  31745. var json = this.json;
  31746. var dracoLoader = this.dracoLoader;
  31747. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  31748. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  31749. var threeAttributeMap = {};
  31750. var attributeNormalizedMap = {};
  31751. var attributeTypeMap = {};
  31752. for (var attributeName in gltfAttributeMap) {
  31753. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  31754. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  31755. }
  31756. for (attributeName in primitive.attributes) {
  31757. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  31758. if (gltfAttributeMap[attributeName] !== undefined) {
  31759. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  31760. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  31761. attributeTypeMap[threeAttributeName] = componentType;
  31762. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  31763. }
  31764. }
  31765. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  31766. return new Promise(function (resolve) {
  31767. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  31768. for (var attributeName in geometry.attributes) {
  31769. var attribute = geometry.attributes[attributeName];
  31770. var normalized = attributeNormalizedMap[attributeName];
  31771. if (normalized !== undefined) attribute.normalized = normalized;
  31772. }
  31773. resolve(geometry);
  31774. }, threeAttributeMap, attributeTypeMap);
  31775. });
  31776. });
  31777. };
  31778. /**
  31779. * Texture Transform Extension
  31780. *
  31781. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  31782. */
  31783. function GLTFTextureTransformExtension() {
  31784. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  31785. }
  31786. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  31787. texture = texture.clone();
  31788. if (transform.offset !== undefined) {
  31789. texture.offset.fromArray(transform.offset);
  31790. }
  31791. if (transform.rotation !== undefined) {
  31792. texture.rotation = transform.rotation;
  31793. }
  31794. if (transform.scale !== undefined) {
  31795. texture.repeat.fromArray(transform.scale);
  31796. }
  31797. if (transform.texCoord !== undefined) {
  31798. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  31799. }
  31800. texture.needsUpdate = true;
  31801. return texture;
  31802. };
  31803. /**
  31804. * Specular-Glossiness Extension
  31805. *
  31806. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  31807. */
  31808. /**
  31809. * A sub class of StandardMaterial with some of the functionality
  31810. * changed via the `onBeforeCompile` callback
  31811. * @pailhead
  31812. */
  31813. function GLTFMeshStandardSGMaterial(params) {
  31814. _threeModule.MeshStandardMaterial.call(this);
  31815. this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing
  31816. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  31817. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  31818. 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');
  31819. 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');
  31820. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 );// 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.specularRoughness += geometryRoughness;', 'material.specularRoughness = min( material.specularRoughness, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n');
  31821. var uniforms = {
  31822. specular: {
  31823. value: new _threeModule.Color().setHex(0xffffff)
  31824. },
  31825. glossiness: {
  31826. value: 1
  31827. },
  31828. specularMap: {
  31829. value: null
  31830. },
  31831. glossinessMap: {
  31832. value: null
  31833. }
  31834. };
  31835. this._extraUniforms = uniforms; // please see #14031 or #13198 for an alternate approach
  31836. this.onBeforeCompile = function (shader) {
  31837. for (var uniformName in uniforms) {
  31838. shader.uniforms[uniformName] = uniforms[uniformName];
  31839. }
  31840. shader.fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;');
  31841. shader.fragmentShader = shader.fragmentShader.replace('uniform float metalness;', 'uniform float glossiness;');
  31842. shader.fragmentShader = shader.fragmentShader.replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk);
  31843. shader.fragmentShader = shader.fragmentShader.replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk);
  31844. shader.fragmentShader = shader.fragmentShader.replace('#include <roughnessmap_fragment>', specularMapFragmentChunk);
  31845. shader.fragmentShader = shader.fragmentShader.replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk);
  31846. shader.fragmentShader = shader.fragmentShader.replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk);
  31847. };
  31848. /*eslint-disable*/
  31849. Object.defineProperties(this, {
  31850. specular: {
  31851. get: function () {
  31852. return uniforms.specular.value;
  31853. },
  31854. set: function (v) {
  31855. uniforms.specular.value = v;
  31856. }
  31857. },
  31858. specularMap: {
  31859. get: function () {
  31860. return uniforms.specularMap.value;
  31861. },
  31862. set: function (v) {
  31863. uniforms.specularMap.value = v;
  31864. }
  31865. },
  31866. glossiness: {
  31867. get: function () {
  31868. return uniforms.glossiness.value;
  31869. },
  31870. set: function (v) {
  31871. uniforms.glossiness.value = v;
  31872. }
  31873. },
  31874. glossinessMap: {
  31875. get: function () {
  31876. return uniforms.glossinessMap.value;
  31877. },
  31878. set: function (v) {
  31879. uniforms.glossinessMap.value = v; //how about something like this - @pailhead
  31880. if (v) {
  31881. this.defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  31882. this.defines.USE_ROUGHNESSMAP = '';
  31883. } else {
  31884. delete this.defines.USE_ROUGHNESSMAP;
  31885. delete this.defines.USE_GLOSSINESSMAP;
  31886. }
  31887. }
  31888. }
  31889. });
  31890. /*eslint-enable*/
  31891. delete this.metalness;
  31892. delete this.roughness;
  31893. delete this.metalnessMap;
  31894. delete this.roughnessMap;
  31895. this.setValues(params);
  31896. }
  31897. GLTFMeshStandardSGMaterial.prototype = Object.create(_threeModule.MeshStandardMaterial.prototype);
  31898. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  31899. GLTFMeshStandardSGMaterial.prototype.copy = function (source) {
  31900. _threeModule.MeshStandardMaterial.prototype.copy.call(this, source);
  31901. this.specularMap = source.specularMap;
  31902. this.specular.copy(source.specular);
  31903. this.glossinessMap = source.glossinessMap;
  31904. this.glossiness = source.glossiness;
  31905. delete this.metalness;
  31906. delete this.roughness;
  31907. delete this.metalnessMap;
  31908. delete this.roughnessMap;
  31909. return this;
  31910. };
  31911. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  31912. return {
  31913. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  31914. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'normalMapType', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  31915. getMaterialType: function () {
  31916. return GLTFMeshStandardSGMaterial;
  31917. },
  31918. extendParams: function (materialParams, materialDef, parser) {
  31919. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  31920. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31921. materialParams.opacity = 1.0;
  31922. var pending = [];
  31923. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  31924. var array = pbrSpecularGlossiness.diffuseFactor;
  31925. materialParams.color.fromArray(array);
  31926. materialParams.opacity = array[3];
  31927. }
  31928. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  31929. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  31930. }
  31931. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  31932. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  31933. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  31934. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  31935. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  31936. }
  31937. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  31938. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  31939. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  31940. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  31941. }
  31942. return Promise.all(pending);
  31943. },
  31944. createMaterial: function (materialParams) {
  31945. var material = new GLTFMeshStandardSGMaterial(materialParams);
  31946. material.fog = true;
  31947. material.color = materialParams.color;
  31948. material.map = materialParams.map === undefined ? null : materialParams.map;
  31949. material.lightMap = null;
  31950. material.lightMapIntensity = 1.0;
  31951. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  31952. material.aoMapIntensity = 1.0;
  31953. material.emissive = materialParams.emissive;
  31954. material.emissiveIntensity = 1.0;
  31955. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  31956. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  31957. material.bumpScale = 1;
  31958. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  31959. material.normalMapType = _threeModule.TangentSpaceNormalMap;
  31960. if (materialParams.normalScale) material.normalScale = materialParams.normalScale;
  31961. material.displacementMap = null;
  31962. material.displacementScale = 1;
  31963. material.displacementBias = 0;
  31964. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  31965. material.specular = materialParams.specular;
  31966. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  31967. material.glossiness = materialParams.glossiness;
  31968. material.alphaMap = null;
  31969. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  31970. material.envMapIntensity = 1.0;
  31971. material.refractionRatio = 0.98;
  31972. return material;
  31973. }
  31974. };
  31975. }
  31976. /**
  31977. * Mesh Quantization Extension
  31978. *
  31979. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  31980. */
  31981. function GLTFMeshQuantizationExtension() {
  31982. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  31983. }
  31984. /*********************************/
  31985. /********** INTERPOLATION ********/
  31986. /*********************************/
  31987. // Spline Interpolation
  31988. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  31989. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  31990. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  31991. }
  31992. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  31993. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  31994. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  31995. // Copies a sample value to the result buffer. See description of glTF
  31996. // CUBICSPLINE values layout in interpolate_() function below.
  31997. var result = this.resultBuffer,
  31998. values = this.sampleValues,
  31999. valueSize = this.valueSize,
  32000. offset = index * valueSize * 3 + valueSize;
  32001. for (var i = 0; i !== valueSize; i++) {
  32002. result[i] = values[offset + i];
  32003. }
  32004. return result;
  32005. };
  32006. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  32007. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  32008. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  32009. var result = this.resultBuffer;
  32010. var values = this.sampleValues;
  32011. var stride = this.valueSize;
  32012. var stride2 = stride * 2;
  32013. var stride3 = stride * 3;
  32014. var td = t1 - t0;
  32015. var p = (t - t0) / td;
  32016. var pp = p * p;
  32017. var ppp = pp * p;
  32018. var offset1 = i1 * stride3;
  32019. var offset0 = offset1 - stride3;
  32020. var s2 = -2 * ppp + 3 * pp;
  32021. var s3 = ppp - pp;
  32022. var s0 = 1 - s2;
  32023. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  32024. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  32025. for (var i = 0; i !== stride; i++) {
  32026. var p0 = values[offset0 + i + stride]; // splineVertex_k
  32027. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  32028. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  32029. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  32030. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  32031. }
  32032. return result;
  32033. };
  32034. /*********************************/
  32035. /********** INTERNALS ************/
  32036. /*********************************/
  32037. /* CONSTANTS */
  32038. var WEBGL_CONSTANTS = {
  32039. FLOAT: 5126,
  32040. //FLOAT_MAT2: 35674,
  32041. FLOAT_MAT3: 35675,
  32042. FLOAT_MAT4: 35676,
  32043. FLOAT_VEC2: 35664,
  32044. FLOAT_VEC3: 35665,
  32045. FLOAT_VEC4: 35666,
  32046. LINEAR: 9729,
  32047. REPEAT: 10497,
  32048. SAMPLER_2D: 35678,
  32049. POINTS: 0,
  32050. LINES: 1,
  32051. LINE_LOOP: 2,
  32052. LINE_STRIP: 3,
  32053. TRIANGLES: 4,
  32054. TRIANGLE_STRIP: 5,
  32055. TRIANGLE_FAN: 6,
  32056. UNSIGNED_BYTE: 5121,
  32057. UNSIGNED_SHORT: 5123
  32058. };
  32059. var WEBGL_COMPONENT_TYPES = {
  32060. 5120: Int8Array,
  32061. 5121: Uint8Array,
  32062. 5122: Int16Array,
  32063. 5123: Uint16Array,
  32064. 5125: Uint32Array,
  32065. 5126: Float32Array
  32066. };
  32067. var WEBGL_FILTERS = {
  32068. 9728: _threeModule.NearestFilter,
  32069. 9729: _threeModule.LinearFilter,
  32070. 9984: _threeModule.NearestMipmapNearestFilter,
  32071. 9985: _threeModule.LinearMipmapNearestFilter,
  32072. 9986: _threeModule.NearestMipmapLinearFilter,
  32073. 9987: _threeModule.LinearMipmapLinearFilter
  32074. };
  32075. var WEBGL_WRAPPINGS = {
  32076. 33071: _threeModule.ClampToEdgeWrapping,
  32077. 33648: _threeModule.MirroredRepeatWrapping,
  32078. 10497: _threeModule.RepeatWrapping
  32079. };
  32080. var WEBGL_TYPE_SIZES = {
  32081. 'SCALAR': 1,
  32082. 'VEC2': 2,
  32083. 'VEC3': 3,
  32084. 'VEC4': 4,
  32085. 'MAT2': 4,
  32086. 'MAT3': 9,
  32087. 'MAT4': 16
  32088. };
  32089. var ATTRIBUTES = {
  32090. POSITION: 'position',
  32091. NORMAL: 'normal',
  32092. TANGENT: 'tangent',
  32093. TEXCOORD_0: 'uv',
  32094. TEXCOORD_1: 'uv2',
  32095. COLOR_0: 'color',
  32096. WEIGHTS_0: 'skinWeight',
  32097. JOINTS_0: 'skinIndex'
  32098. };
  32099. var PATH_PROPERTIES = {
  32100. scale: 'scale',
  32101. translation: 'position',
  32102. rotation: 'quaternion',
  32103. weights: 'morphTargetInfluences'
  32104. };
  32105. var INTERPOLATION = {
  32106. CUBICSPLINE: undefined,
  32107. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  32108. // keyframe track will be initialized with a default interpolation type, then modified.
  32109. LINEAR: _threeModule.InterpolateLinear,
  32110. STEP: _threeModule.InterpolateDiscrete
  32111. };
  32112. var ALPHA_MODES = {
  32113. OPAQUE: 'OPAQUE',
  32114. MASK: 'MASK',
  32115. BLEND: 'BLEND'
  32116. };
  32117. var MIME_TYPE_FORMATS = {
  32118. 'image/png': _threeModule.RGBAFormat,
  32119. 'image/jpeg': _threeModule.RGBFormat
  32120. };
  32121. /* UTILITY FUNCTIONS */
  32122. function resolveURL(url, path) {
  32123. // Invalid URL
  32124. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  32125. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  32126. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  32127. } // Absolute URL http://,https://,//
  32128. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  32129. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  32130. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  32131. return path + url;
  32132. }
  32133. /**
  32134. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  32135. */
  32136. function createDefaultMaterial(cache) {
  32137. if (cache['DefaultMaterial'] === undefined) {
  32138. cache['DefaultMaterial'] = new _threeModule.MeshStandardMaterial({
  32139. color: 0xFFFFFF,
  32140. emissive: 0x000000,
  32141. metalness: 1,
  32142. roughness: 1,
  32143. transparent: false,
  32144. depthTest: true,
  32145. side: _threeModule.FrontSide
  32146. });
  32147. }
  32148. return cache['DefaultMaterial'];
  32149. }
  32150. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  32151. // Add unknown glTF extensions to an object's userData.
  32152. for (var name in objectDef.extensions) {
  32153. if (knownExtensions[name] === undefined) {
  32154. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  32155. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  32156. }
  32157. }
  32158. }
  32159. /**
  32160. * @param {Object3D|Material|BufferGeometry} object
  32161. * @param {GLTF.definition} gltfDef
  32162. */
  32163. function assignExtrasToUserData(object, gltfDef) {
  32164. if (gltfDef.extras !== undefined) {
  32165. if (typeof gltfDef.extras === 'object') {
  32166. Object.assign(object.userData, gltfDef.extras);
  32167. } else {
  32168. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  32169. }
  32170. }
  32171. }
  32172. /**
  32173. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  32174. *
  32175. * @param {BufferGeometry} geometry
  32176. * @param {Array<GLTF.Target>} targets
  32177. * @param {GLTFParser} parser
  32178. * @return {Promise<BufferGeometry>}
  32179. */
  32180. function addMorphTargets(geometry, targets, parser) {
  32181. var hasMorphPosition = false;
  32182. var hasMorphNormal = false;
  32183. for (var i = 0, il = targets.length; i < il; i++) {
  32184. var target = targets[i];
  32185. if (target.POSITION !== undefined) hasMorphPosition = true;
  32186. if (target.NORMAL !== undefined) hasMorphNormal = true;
  32187. if (hasMorphPosition && hasMorphNormal) break;
  32188. }
  32189. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  32190. var pendingPositionAccessors = [];
  32191. var pendingNormalAccessors = [];
  32192. for (var i = 0, il = targets.length; i < il; i++) {
  32193. var target = targets[i];
  32194. if (hasMorphPosition) {
  32195. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  32196. pendingPositionAccessors.push(pendingAccessor);
  32197. }
  32198. if (hasMorphNormal) {
  32199. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  32200. pendingNormalAccessors.push(pendingAccessor);
  32201. }
  32202. }
  32203. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  32204. var morphPositions = accessors[0];
  32205. var morphNormals = accessors[1];
  32206. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  32207. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  32208. geometry.morphTargetsRelative = true;
  32209. return geometry;
  32210. });
  32211. }
  32212. /**
  32213. * @param {Mesh} mesh
  32214. * @param {GLTF.Mesh} meshDef
  32215. */
  32216. function updateMorphTargets(mesh, meshDef) {
  32217. mesh.updateMorphTargets();
  32218. if (meshDef.weights !== undefined) {
  32219. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  32220. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  32221. }
  32222. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  32223. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  32224. var targetNames = meshDef.extras.targetNames;
  32225. if (mesh.morphTargetInfluences.length === targetNames.length) {
  32226. mesh.morphTargetDictionary = {};
  32227. for (var i = 0, il = targetNames.length; i < il; i++) {
  32228. mesh.morphTargetDictionary[targetNames[i]] = i;
  32229. }
  32230. } else {
  32231. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  32232. }
  32233. }
  32234. }
  32235. function createPrimitiveKey(primitiveDef) {
  32236. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  32237. var geometryKey;
  32238. if (dracoExtension) {
  32239. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  32240. } else {
  32241. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  32242. }
  32243. return geometryKey;
  32244. }
  32245. function createAttributesKey(attributes) {
  32246. var attributesKey = '';
  32247. var keys = Object.keys(attributes).sort();
  32248. for (var i = 0, il = keys.length; i < il; i++) {
  32249. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  32250. }
  32251. return attributesKey;
  32252. }
  32253. /* GLTF PARSER */
  32254. function GLTFParser(json, extensions, options) {
  32255. this.json = json || {};
  32256. this.extensions = extensions || {};
  32257. this.options = options || {}; // loader object cache
  32258. this.cache = new GLTFRegistry(); // BufferGeometry caching
  32259. this.primitiveCache = {};
  32260. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  32261. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  32262. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  32263. this.fileLoader.setResponseType('arraybuffer');
  32264. if (this.options.crossOrigin === 'use-credentials') {
  32265. this.fileLoader.setWithCredentials(true);
  32266. }
  32267. }
  32268. GLTFParser.prototype.parse = function (onLoad, onError) {
  32269. var parser = this;
  32270. var json = this.json;
  32271. var extensions = this.extensions; // Clear the loader cache
  32272. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  32273. this.markDefs();
  32274. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  32275. var result = {
  32276. scene: dependencies[0][json.scene || 0],
  32277. scenes: dependencies[0],
  32278. animations: dependencies[1],
  32279. cameras: dependencies[2],
  32280. asset: json.asset,
  32281. parser: parser,
  32282. userData: {}
  32283. };
  32284. addUnknownExtensionsToUserData(extensions, result, json);
  32285. assignExtrasToUserData(result, json);
  32286. onLoad(result);
  32287. }).catch(onError);
  32288. };
  32289. /**
  32290. * Marks the special nodes/meshes in json for efficient parse.
  32291. */
  32292. GLTFParser.prototype.markDefs = function () {
  32293. var nodeDefs = this.json.nodes || [];
  32294. var skinDefs = this.json.skins || [];
  32295. var meshDefs = this.json.meshes || [];
  32296. var meshReferences = {};
  32297. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  32298. // Object3D. Use the skins' joint references to mark bones.
  32299. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  32300. var joints = skinDefs[skinIndex].joints;
  32301. for (var i = 0, il = joints.length; i < il; i++) {
  32302. nodeDefs[joints[i]].isBone = true;
  32303. }
  32304. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  32305. // avoid having more than one Mesh with the same name, count
  32306. // references and rename instances below.
  32307. //
  32308. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  32309. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  32310. var nodeDef = nodeDefs[nodeIndex];
  32311. if (nodeDef.mesh !== undefined) {
  32312. if (meshReferences[nodeDef.mesh] === undefined) {
  32313. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  32314. }
  32315. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  32316. // a SkinnedMesh or Mesh. Use the node's mesh reference
  32317. // to mark SkinnedMesh if node has skin.
  32318. if (nodeDef.skin !== undefined) {
  32319. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  32320. }
  32321. }
  32322. }
  32323. this.json.meshReferences = meshReferences;
  32324. this.json.meshUses = meshUses;
  32325. };
  32326. /**
  32327. * Requests the specified dependency asynchronously, with caching.
  32328. * @param {string} type
  32329. * @param {number} index
  32330. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  32331. */
  32332. GLTFParser.prototype.getDependency = function (type, index) {
  32333. var cacheKey = type + ':' + index;
  32334. var dependency = this.cache.get(cacheKey);
  32335. if (!dependency) {
  32336. switch (type) {
  32337. case 'scene':
  32338. dependency = this.loadScene(index);
  32339. break;
  32340. case 'node':
  32341. dependency = this.loadNode(index);
  32342. break;
  32343. case 'mesh':
  32344. dependency = this.loadMesh(index);
  32345. break;
  32346. case 'accessor':
  32347. dependency = this.loadAccessor(index);
  32348. break;
  32349. case 'bufferView':
  32350. dependency = this.loadBufferView(index);
  32351. break;
  32352. case 'buffer':
  32353. dependency = this.loadBuffer(index);
  32354. break;
  32355. case 'material':
  32356. dependency = this.loadMaterial(index);
  32357. break;
  32358. case 'texture':
  32359. dependency = this.loadTexture(index);
  32360. break;
  32361. case 'skin':
  32362. dependency = this.loadSkin(index);
  32363. break;
  32364. case 'animation':
  32365. dependency = this.loadAnimation(index);
  32366. break;
  32367. case 'camera':
  32368. dependency = this.loadCamera(index);
  32369. break;
  32370. case 'light':
  32371. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  32372. break;
  32373. default:
  32374. throw new Error('Unknown type: ' + type);
  32375. }
  32376. this.cache.add(cacheKey, dependency);
  32377. }
  32378. return dependency;
  32379. };
  32380. /**
  32381. * Requests all dependencies of the specified type asynchronously, with caching.
  32382. * @param {string} type
  32383. * @return {Promise<Array<Object>>}
  32384. */
  32385. GLTFParser.prototype.getDependencies = function (type) {
  32386. var dependencies = this.cache.get(type);
  32387. if (!dependencies) {
  32388. var parser = this;
  32389. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  32390. dependencies = Promise.all(defs.map(function (def, index) {
  32391. return parser.getDependency(type, index);
  32392. }));
  32393. this.cache.add(type, dependencies);
  32394. }
  32395. return dependencies;
  32396. };
  32397. /**
  32398. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  32399. * @param {number} bufferIndex
  32400. * @return {Promise<ArrayBuffer>}
  32401. */
  32402. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  32403. var bufferDef = this.json.buffers[bufferIndex];
  32404. var loader = this.fileLoader;
  32405. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  32406. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  32407. } // If present, GLB container is required to be the first buffer.
  32408. if (bufferDef.uri === undefined && bufferIndex === 0) {
  32409. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  32410. }
  32411. var options = this.options;
  32412. return new Promise(function (resolve, reject) {
  32413. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  32414. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  32415. });
  32416. });
  32417. };
  32418. /**
  32419. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  32420. * @param {number} bufferViewIndex
  32421. * @return {Promise<ArrayBuffer>}
  32422. */
  32423. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  32424. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  32425. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  32426. var byteLength = bufferViewDef.byteLength || 0;
  32427. var byteOffset = bufferViewDef.byteOffset || 0;
  32428. return buffer.slice(byteOffset, byteOffset + byteLength);
  32429. });
  32430. };
  32431. /**
  32432. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  32433. * @param {number} accessorIndex
  32434. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  32435. */
  32436. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  32437. var parser = this;
  32438. var json = this.json;
  32439. var accessorDef = this.json.accessors[accessorIndex];
  32440. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  32441. // Ignore empty accessors, which may be used to declare runtime
  32442. // information about attributes coming from another source (e.g. Draco
  32443. // compression extension).
  32444. return Promise.resolve(null);
  32445. }
  32446. var pendingBufferViews = [];
  32447. if (accessorDef.bufferView !== undefined) {
  32448. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  32449. } else {
  32450. pendingBufferViews.push(null);
  32451. }
  32452. if (accessorDef.sparse !== undefined) {
  32453. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  32454. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  32455. }
  32456. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  32457. var bufferView = bufferViews[0];
  32458. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  32459. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  32460. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  32461. var itemBytes = elementBytes * itemSize;
  32462. var byteOffset = accessorDef.byteOffset || 0;
  32463. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  32464. var normalized = accessorDef.normalized === true;
  32465. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  32466. if (byteStride && byteStride !== itemBytes) {
  32467. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  32468. // This makes sure that IBA.count reflects accessor.count properly
  32469. var ibSlice = Math.floor(byteOffset / byteStride);
  32470. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  32471. var ib = parser.cache.get(ibCacheKey);
  32472. if (!ib) {
  32473. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  32474. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  32475. parser.cache.add(ibCacheKey, ib);
  32476. }
  32477. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  32478. } else {
  32479. if (bufferView === null) {
  32480. array = new TypedArray(accessorDef.count * itemSize);
  32481. } else {
  32482. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  32483. }
  32484. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  32485. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  32486. if (accessorDef.sparse !== undefined) {
  32487. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  32488. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  32489. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  32490. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  32491. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  32492. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  32493. if (bufferView !== null) {
  32494. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  32495. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  32496. }
  32497. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  32498. var index = sparseIndices[i];
  32499. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  32500. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  32501. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  32502. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  32503. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  32504. }
  32505. }
  32506. return bufferAttribute;
  32507. });
  32508. };
  32509. /**
  32510. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  32511. * @param {number} textureIndex
  32512. * @return {Promise<THREE.Texture>}
  32513. */
  32514. GLTFParser.prototype.loadTexture = function (textureIndex) {
  32515. var parser = this;
  32516. var json = this.json;
  32517. var options = this.options;
  32518. var textureLoader = this.textureLoader;
  32519. var URL = self.URL || self.webkitURL;
  32520. var textureDef = json.textures[textureIndex];
  32521. var textureExtensions = textureDef.extensions || {};
  32522. var source;
  32523. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  32524. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  32525. } else {
  32526. source = json.images[textureDef.source];
  32527. }
  32528. var sourceURI = source.uri;
  32529. var isObjectURL = false;
  32530. if (source.bufferView !== undefined) {
  32531. // Load binary image data from bufferView, if provided.
  32532. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  32533. isObjectURL = true;
  32534. var blob = new Blob([bufferView], {
  32535. type: source.mimeType
  32536. });
  32537. sourceURI = URL.createObjectURL(blob);
  32538. return sourceURI;
  32539. });
  32540. }
  32541. return Promise.resolve(sourceURI).then(function (sourceURI) {
  32542. // Load Texture resource.
  32543. var loader = options.manager.getHandler(sourceURI);
  32544. if (!loader) {
  32545. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  32546. }
  32547. return new Promise(function (resolve, reject) {
  32548. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  32549. });
  32550. }).then(function (texture) {
  32551. // Clean up resources and configure Texture.
  32552. if (isObjectURL === true) {
  32553. URL.revokeObjectURL(sourceURI);
  32554. }
  32555. texture.flipY = false;
  32556. if (textureDef.name) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  32557. if (source.mimeType in MIME_TYPE_FORMATS) {
  32558. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  32559. }
  32560. var samplers = json.samplers || {};
  32561. var sampler = samplers[textureDef.sampler] || {};
  32562. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  32563. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  32564. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  32565. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  32566. return texture;
  32567. });
  32568. };
  32569. /**
  32570. * Asynchronously assigns a texture to the given material parameters.
  32571. * @param {Object} materialParams
  32572. * @param {string} mapName
  32573. * @param {Object} mapDef
  32574. * @return {Promise}
  32575. */
  32576. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  32577. var parser = this;
  32578. return this.getDependency('texture', mapDef.index).then(function (texture) {
  32579. if (!texture.isCompressedTexture) {
  32580. switch (mapName) {
  32581. case 'aoMap':
  32582. case 'emissiveMap':
  32583. case 'metalnessMap':
  32584. case 'normalMap':
  32585. case 'roughnessMap':
  32586. texture.format = _threeModule.RGBFormat;
  32587. break;
  32588. }
  32589. } // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  32590. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  32591. if (mapDef.texCoord !== undefined && mapDef.texCoord != 0 && !(mapName === 'aoMap' && mapDef.texCoord == 1)) {
  32592. console.warn('THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.');
  32593. }
  32594. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  32595. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  32596. if (transform) {
  32597. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  32598. }
  32599. }
  32600. materialParams[mapName] = texture;
  32601. });
  32602. };
  32603. /**
  32604. * Assigns final material to a Mesh, Line, or Points instance. The instance
  32605. * already has a material (generated from the glTF material options alone)
  32606. * but reuse of the same glTF material may require multiple threejs materials
  32607. * to accomodate different primitive types, defines, etc. New materials will
  32608. * be created if necessary, and reused from a cache.
  32609. * @param {Object3D} mesh Mesh, Line, or Points instance.
  32610. */
  32611. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  32612. var geometry = mesh.geometry;
  32613. var material = mesh.material;
  32614. var useVertexTangents = geometry.attributes.tangent !== undefined;
  32615. var useVertexColors = geometry.attributes.color !== undefined;
  32616. var useFlatShading = geometry.attributes.normal === undefined;
  32617. var useSkinning = mesh.isSkinnedMesh === true;
  32618. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  32619. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  32620. if (mesh.isPoints) {
  32621. var cacheKey = 'PointsMaterial:' + material.uuid;
  32622. var pointsMaterial = this.cache.get(cacheKey);
  32623. if (!pointsMaterial) {
  32624. pointsMaterial = new _threeModule.PointsMaterial();
  32625. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  32626. pointsMaterial.color.copy(material.color);
  32627. pointsMaterial.map = material.map;
  32628. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  32629. this.cache.add(cacheKey, pointsMaterial);
  32630. }
  32631. material = pointsMaterial;
  32632. } else if (mesh.isLine) {
  32633. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  32634. var lineMaterial = this.cache.get(cacheKey);
  32635. if (!lineMaterial) {
  32636. lineMaterial = new _threeModule.LineBasicMaterial();
  32637. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  32638. lineMaterial.color.copy(material.color);
  32639. this.cache.add(cacheKey, lineMaterial);
  32640. }
  32641. material = lineMaterial;
  32642. } // Clone the material if it will be modified
  32643. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  32644. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  32645. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  32646. if (useSkinning) cacheKey += 'skinning:';
  32647. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  32648. if (useVertexColors) cacheKey += 'vertex-colors:';
  32649. if (useFlatShading) cacheKey += 'flat-shading:';
  32650. if (useMorphTargets) cacheKey += 'morph-targets:';
  32651. if (useMorphNormals) cacheKey += 'morph-normals:';
  32652. var cachedMaterial = this.cache.get(cacheKey);
  32653. if (!cachedMaterial) {
  32654. cachedMaterial = material.clone();
  32655. if (useSkinning) cachedMaterial.skinning = true;
  32656. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  32657. if (useVertexColors) cachedMaterial.vertexColors = true;
  32658. if (useFlatShading) cachedMaterial.flatShading = true;
  32659. if (useMorphTargets) cachedMaterial.morphTargets = true;
  32660. if (useMorphNormals) cachedMaterial.morphNormals = true;
  32661. this.cache.add(cacheKey, cachedMaterial);
  32662. }
  32663. material = cachedMaterial;
  32664. } // workarounds for mesh and geometry
  32665. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  32666. geometry.setAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  32667. } // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  32668. if (material.normalScale && !useVertexTangents) {
  32669. material.normalScale.y = -material.normalScale.y;
  32670. }
  32671. if (material.clearcoatNormalScale && !useVertexTangents) {
  32672. material.clearcoatNormalScale.y = -material.clearcoatNormalScale.y;
  32673. }
  32674. mesh.material = material;
  32675. };
  32676. /**
  32677. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  32678. * @param {number} materialIndex
  32679. * @return {Promise<Material>}
  32680. */
  32681. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  32682. var parser = this;
  32683. var json = this.json;
  32684. var extensions = this.extensions;
  32685. var materialDef = json.materials[materialIndex];
  32686. var materialType;
  32687. var materialParams = {};
  32688. var materialExtensions = materialDef.extensions || {};
  32689. var pending = [];
  32690. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  32691. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  32692. materialType = sgExtension.getMaterialType();
  32693. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  32694. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  32695. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  32696. materialType = kmuExtension.getMaterialType();
  32697. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  32698. } else {
  32699. // Specification:
  32700. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  32701. materialType = _threeModule.MeshStandardMaterial;
  32702. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  32703. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  32704. materialParams.opacity = 1.0;
  32705. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  32706. var array = metallicRoughness.baseColorFactor;
  32707. materialParams.color.fromArray(array);
  32708. materialParams.opacity = array[3];
  32709. }
  32710. if (metallicRoughness.baseColorTexture !== undefined) {
  32711. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  32712. }
  32713. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  32714. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  32715. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  32716. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  32717. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  32718. }
  32719. }
  32720. if (materialDef.doubleSided === true) {
  32721. materialParams.side = _threeModule.DoubleSide;
  32722. }
  32723. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  32724. if (alphaMode === ALPHA_MODES.BLEND) {
  32725. materialParams.transparent = true; // See: https://github.com/mrdoob/three.js/issues/17706
  32726. materialParams.depthWrite = false;
  32727. } else {
  32728. materialParams.transparent = false;
  32729. if (alphaMode === ALPHA_MODES.MASK) {
  32730. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  32731. }
  32732. }
  32733. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32734. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  32735. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  32736. if (materialDef.normalTexture.scale !== undefined) {
  32737. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  32738. }
  32739. }
  32740. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32741. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  32742. if (materialDef.occlusionTexture.strength !== undefined) {
  32743. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  32744. }
  32745. }
  32746. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32747. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  32748. }
  32749. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32750. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  32751. }
  32752. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_CLEARCOAT]) {
  32753. var clearcoatExtension = extensions[EXTENSIONS.KHR_MATERIALS_CLEARCOAT];
  32754. materialType = clearcoatExtension.getMaterialType();
  32755. pending.push(clearcoatExtension.extendParams(materialParams, {
  32756. extensions: materialExtensions
  32757. }, parser));
  32758. }
  32759. return Promise.all(pending).then(function () {
  32760. var material;
  32761. if (materialType === GLTFMeshStandardSGMaterial) {
  32762. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  32763. } else {
  32764. material = new materialType(materialParams);
  32765. }
  32766. if (materialDef.name) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  32767. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  32768. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  32769. assignExtrasToUserData(material, materialDef);
  32770. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  32771. return material;
  32772. });
  32773. };
  32774. /**
  32775. * @param {BufferGeometry} geometry
  32776. * @param {GLTF.Primitive} primitiveDef
  32777. * @param {GLTFParser} parser
  32778. */
  32779. function computeBounds(geometry, primitiveDef, parser) {
  32780. var attributes = primitiveDef.attributes;
  32781. var box = new _threeModule.Box3();
  32782. if (attributes.POSITION !== undefined) {
  32783. var accessor = parser.json.accessors[attributes.POSITION];
  32784. var min = accessor.min;
  32785. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  32786. if (min !== undefined && max !== undefined) {
  32787. box.set(new _threeModule.Vector3(min[0], min[1], min[2]), new _threeModule.Vector3(max[0], max[1], max[2]));
  32788. } else {
  32789. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  32790. return;
  32791. }
  32792. } else {
  32793. return;
  32794. }
  32795. var targets = primitiveDef.targets;
  32796. if (targets !== undefined) {
  32797. var maxDisplacement = new _threeModule.Vector3();
  32798. var vector = new _threeModule.Vector3();
  32799. for (var i = 0, il = targets.length; i < il; i++) {
  32800. var target = targets[i];
  32801. if (target.POSITION !== undefined) {
  32802. var accessor = parser.json.accessors[target.POSITION];
  32803. var min = accessor.min;
  32804. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  32805. if (min !== undefined && max !== undefined) {
  32806. // we need to get max of absolute components because target weight is [-1,1]
  32807. vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0])));
  32808. vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1])));
  32809. vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2]))); // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  32810. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  32811. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  32812. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  32813. maxDisplacement.max(vector);
  32814. } else {
  32815. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  32816. }
  32817. }
  32818. } // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  32819. box.expandByVector(maxDisplacement);
  32820. }
  32821. geometry.boundingBox = box;
  32822. var sphere = new _threeModule.Sphere();
  32823. box.getCenter(sphere.center);
  32824. sphere.radius = box.min.distanceTo(box.max) / 2;
  32825. geometry.boundingSphere = sphere;
  32826. }
  32827. /**
  32828. * @param {BufferGeometry} geometry
  32829. * @param {GLTF.Primitive} primitiveDef
  32830. * @param {GLTFParser} parser
  32831. * @return {Promise<BufferGeometry>}
  32832. */
  32833. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  32834. var attributes = primitiveDef.attributes;
  32835. var pending = [];
  32836. function assignAttributeAccessor(accessorIndex, attributeName) {
  32837. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  32838. geometry.setAttribute(attributeName, accessor);
  32839. });
  32840. }
  32841. for (var gltfAttributeName in attributes) {
  32842. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  32843. if (threeAttributeName in geometry.attributes) continue;
  32844. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  32845. }
  32846. if (primitiveDef.indices !== undefined && !geometry.index) {
  32847. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  32848. geometry.setIndex(accessor);
  32849. });
  32850. pending.push(accessor);
  32851. }
  32852. assignExtrasToUserData(geometry, primitiveDef);
  32853. computeBounds(geometry, primitiveDef, parser);
  32854. return Promise.all(pending).then(function () {
  32855. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  32856. });
  32857. }
  32858. /**
  32859. * @param {BufferGeometry} geometry
  32860. * @param {Number} drawMode
  32861. * @return {BufferGeometry}
  32862. */
  32863. function toTrianglesDrawMode(geometry, drawMode) {
  32864. var index = geometry.getIndex(); // generate index if not present
  32865. if (index === null) {
  32866. var indices = [];
  32867. var position = geometry.getAttribute('position');
  32868. if (position !== undefined) {
  32869. for (var i = 0; i < position.count; i++) {
  32870. indices.push(i);
  32871. }
  32872. geometry.setIndex(indices);
  32873. index = geometry.getIndex();
  32874. } else {
  32875. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  32876. return geometry;
  32877. }
  32878. } //
  32879. var numberOfTriangles = index.count - 2;
  32880. var newIndices = [];
  32881. if (drawMode === _threeModule.TriangleFanDrawMode) {
  32882. // gl.TRIANGLE_FAN
  32883. for (var i = 1; i <= numberOfTriangles; i++) {
  32884. newIndices.push(index.getX(0));
  32885. newIndices.push(index.getX(i));
  32886. newIndices.push(index.getX(i + 1));
  32887. }
  32888. } else {
  32889. // gl.TRIANGLE_STRIP
  32890. for (var i = 0; i < numberOfTriangles; i++) {
  32891. if (i % 2 === 0) {
  32892. newIndices.push(index.getX(i));
  32893. newIndices.push(index.getX(i + 1));
  32894. newIndices.push(index.getX(i + 2));
  32895. } else {
  32896. newIndices.push(index.getX(i + 2));
  32897. newIndices.push(index.getX(i + 1));
  32898. newIndices.push(index.getX(i));
  32899. }
  32900. }
  32901. }
  32902. if (newIndices.length / 3 !== numberOfTriangles) {
  32903. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  32904. } // build final geometry
  32905. var newGeometry = geometry.clone();
  32906. newGeometry.setIndex(newIndices);
  32907. return newGeometry;
  32908. }
  32909. /**
  32910. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  32911. *
  32912. * Creates BufferGeometries from primitives.
  32913. *
  32914. * @param {Array<GLTF.Primitive>} primitives
  32915. * @return {Promise<Array<BufferGeometry>>}
  32916. */
  32917. GLTFParser.prototype.loadGeometries = function (primitives) {
  32918. var parser = this;
  32919. var extensions = this.extensions;
  32920. var cache = this.primitiveCache;
  32921. function createDracoPrimitive(primitive) {
  32922. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  32923. return addPrimitiveAttributes(geometry, primitive, parser);
  32924. });
  32925. }
  32926. var pending = [];
  32927. for (var i = 0, il = primitives.length; i < il; i++) {
  32928. var primitive = primitives[i];
  32929. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  32930. var cached = cache[cacheKey];
  32931. if (cached) {
  32932. // Use the cached geometry if it exists
  32933. pending.push(cached.promise);
  32934. } else {
  32935. var geometryPromise;
  32936. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  32937. // Use DRACO geometry if available
  32938. geometryPromise = createDracoPrimitive(primitive);
  32939. } else {
  32940. // Otherwise create a new geometry
  32941. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  32942. } // Cache this geometry
  32943. cache[cacheKey] = {
  32944. primitive: primitive,
  32945. promise: geometryPromise
  32946. };
  32947. pending.push(geometryPromise);
  32948. }
  32949. }
  32950. return Promise.all(pending);
  32951. };
  32952. /**
  32953. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  32954. * @param {number} meshIndex
  32955. * @return {Promise<Group|Mesh|SkinnedMesh>}
  32956. */
  32957. GLTFParser.prototype.loadMesh = function (meshIndex) {
  32958. var parser = this;
  32959. var json = this.json;
  32960. var meshDef = json.meshes[meshIndex];
  32961. var primitives = meshDef.primitives;
  32962. var pending = [];
  32963. for (var i = 0, il = primitives.length; i < il; i++) {
  32964. var material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency('material', primitives[i].material);
  32965. pending.push(material);
  32966. }
  32967. pending.push(parser.loadGeometries(primitives));
  32968. return Promise.all(pending).then(function (results) {
  32969. var materials = results.slice(0, results.length - 1);
  32970. var geometries = results[results.length - 1];
  32971. var meshes = [];
  32972. for (var i = 0, il = geometries.length; i < il; i++) {
  32973. var geometry = geometries[i];
  32974. var primitive = primitives[i]; // 1. create Mesh
  32975. var mesh;
  32976. var material = materials[i];
  32977. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  32978. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  32979. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  32980. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  32981. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  32982. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  32983. mesh.normalizeSkinWeights();
  32984. }
  32985. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  32986. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleStripDrawMode);
  32987. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  32988. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleFanDrawMode);
  32989. }
  32990. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  32991. mesh = new _threeModule.LineSegments(geometry, material);
  32992. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  32993. mesh = new _threeModule.Line(geometry, material);
  32994. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  32995. mesh = new _threeModule.LineLoop(geometry, material);
  32996. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  32997. mesh = new _threeModule.Points(geometry, material);
  32998. } else {
  32999. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  33000. }
  33001. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  33002. updateMorphTargets(mesh, meshDef);
  33003. }
  33004. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  33005. if (geometries.length > 1) mesh.name += '_' + i;
  33006. assignExtrasToUserData(mesh, meshDef);
  33007. parser.assignFinalMaterial(mesh);
  33008. meshes.push(mesh);
  33009. }
  33010. if (meshes.length === 1) {
  33011. return meshes[0];
  33012. }
  33013. var group = new _threeModule.Group();
  33014. for (var i = 0, il = meshes.length; i < il; i++) {
  33015. group.add(meshes[i]);
  33016. }
  33017. return group;
  33018. });
  33019. };
  33020. /**
  33021. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  33022. * @param {number} cameraIndex
  33023. * @return {Promise<THREE.Camera>}
  33024. */
  33025. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  33026. var camera;
  33027. var cameraDef = this.json.cameras[cameraIndex];
  33028. var params = cameraDef[cameraDef.type];
  33029. if (!params) {
  33030. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  33031. return;
  33032. }
  33033. if (cameraDef.type === 'perspective') {
  33034. camera = new _threeModule.PerspectiveCamera(_threeModule.MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  33035. } else if (cameraDef.type === 'orthographic') {
  33036. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  33037. }
  33038. if (cameraDef.name) camera.name = cameraDef.name;
  33039. assignExtrasToUserData(camera, cameraDef);
  33040. return Promise.resolve(camera);
  33041. };
  33042. /**
  33043. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  33044. * @param {number} skinIndex
  33045. * @return {Promise<Object>}
  33046. */
  33047. GLTFParser.prototype.loadSkin = function (skinIndex) {
  33048. var skinDef = this.json.skins[skinIndex];
  33049. var skinEntry = {
  33050. joints: skinDef.joints
  33051. };
  33052. if (skinDef.inverseBindMatrices === undefined) {
  33053. return Promise.resolve(skinEntry);
  33054. }
  33055. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  33056. skinEntry.inverseBindMatrices = accessor;
  33057. return skinEntry;
  33058. });
  33059. };
  33060. /**
  33061. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  33062. * @param {number} animationIndex
  33063. * @return {Promise<AnimationClip>}
  33064. */
  33065. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  33066. var json = this.json;
  33067. var animationDef = json.animations[animationIndex];
  33068. var pendingNodes = [];
  33069. var pendingInputAccessors = [];
  33070. var pendingOutputAccessors = [];
  33071. var pendingSamplers = [];
  33072. var pendingTargets = [];
  33073. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  33074. var channel = animationDef.channels[i];
  33075. var sampler = animationDef.samplers[channel.sampler];
  33076. var target = channel.target;
  33077. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  33078. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  33079. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  33080. pendingNodes.push(this.getDependency('node', name));
  33081. pendingInputAccessors.push(this.getDependency('accessor', input));
  33082. pendingOutputAccessors.push(this.getDependency('accessor', output));
  33083. pendingSamplers.push(sampler);
  33084. pendingTargets.push(target);
  33085. }
  33086. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  33087. var nodes = dependencies[0];
  33088. var inputAccessors = dependencies[1];
  33089. var outputAccessors = dependencies[2];
  33090. var samplers = dependencies[3];
  33091. var targets = dependencies[4];
  33092. var tracks = [];
  33093. for (var i = 0, il = nodes.length; i < il; i++) {
  33094. var node = nodes[i];
  33095. var inputAccessor = inputAccessors[i];
  33096. var outputAccessor = outputAccessors[i];
  33097. var sampler = samplers[i];
  33098. var target = targets[i];
  33099. if (node === undefined) continue;
  33100. node.updateMatrix();
  33101. node.matrixAutoUpdate = true;
  33102. var TypedKeyframeTrack;
  33103. switch (PATH_PROPERTIES[target.path]) {
  33104. case PATH_PROPERTIES.weights:
  33105. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  33106. break;
  33107. case PATH_PROPERTIES.rotation:
  33108. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  33109. break;
  33110. case PATH_PROPERTIES.position:
  33111. case PATH_PROPERTIES.scale:
  33112. default:
  33113. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  33114. break;
  33115. }
  33116. var targetName = node.name ? node.name : node.uuid;
  33117. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  33118. var targetNames = [];
  33119. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  33120. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  33121. node.traverse(function (object) {
  33122. if (object.isMesh === true && object.morphTargetInfluences) {
  33123. targetNames.push(object.name ? object.name : object.uuid);
  33124. }
  33125. });
  33126. } else {
  33127. targetNames.push(targetName);
  33128. }
  33129. var outputArray = outputAccessor.array;
  33130. if (outputAccessor.normalized) {
  33131. var scale;
  33132. if (outputArray.constructor === Int8Array) {
  33133. scale = 1 / 127;
  33134. } else if (outputArray.constructor === Uint8Array) {
  33135. scale = 1 / 255;
  33136. } else if (outputArray.constructor == Int16Array) {
  33137. scale = 1 / 32767;
  33138. } else if (outputArray.constructor === Uint16Array) {
  33139. scale = 1 / 65535;
  33140. } else {
  33141. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  33142. }
  33143. var scaled = new Float32Array(outputArray.length);
  33144. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  33145. scaled[j] = outputArray[j] * scale;
  33146. }
  33147. outputArray = scaled;
  33148. }
  33149. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  33150. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  33151. if (sampler.interpolation === 'CUBICSPLINE') {
  33152. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  33153. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  33154. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  33155. // must be divided by three to get the interpolant's sampleSize argument.
  33156. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  33157. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  33158. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  33159. }
  33160. tracks.push(track);
  33161. }
  33162. }
  33163. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  33164. return new _threeModule.AnimationClip(name, undefined, tracks);
  33165. });
  33166. };
  33167. /**
  33168. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  33169. * @param {number} nodeIndex
  33170. * @return {Promise<Object3D>}
  33171. */
  33172. GLTFParser.prototype.loadNode = function (nodeIndex) {
  33173. var json = this.json;
  33174. var extensions = this.extensions;
  33175. var parser = this;
  33176. var meshReferences = json.meshReferences;
  33177. var meshUses = json.meshUses;
  33178. var nodeDef = json.nodes[nodeIndex];
  33179. return function () {
  33180. var pending = [];
  33181. if (nodeDef.mesh !== undefined) {
  33182. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  33183. var node;
  33184. if (meshReferences[nodeDef.mesh] > 1) {
  33185. var instanceNum = meshUses[nodeDef.mesh]++;
  33186. node = mesh.clone();
  33187. node.name += '_instance_' + instanceNum;
  33188. } else {
  33189. node = mesh;
  33190. } // if weights are provided on the node, override weights on the mesh.
  33191. if (nodeDef.weights !== undefined) {
  33192. node.traverse(function (o) {
  33193. if (!o.isMesh) return;
  33194. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  33195. o.morphTargetInfluences[i] = nodeDef.weights[i];
  33196. }
  33197. });
  33198. }
  33199. return node;
  33200. }));
  33201. }
  33202. if (nodeDef.camera !== undefined) {
  33203. pending.push(parser.getDependency('camera', nodeDef.camera));
  33204. }
  33205. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  33206. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  33207. }
  33208. return Promise.all(pending);
  33209. }().then(function (objects) {
  33210. var node; // .isBone isn't in glTF spec. See .markDefs
  33211. if (nodeDef.isBone === true) {
  33212. node = new _threeModule.Bone();
  33213. } else if (objects.length > 1) {
  33214. node = new _threeModule.Group();
  33215. } else if (objects.length === 1) {
  33216. node = objects[0];
  33217. } else {
  33218. node = new _threeModule.Object3D();
  33219. }
  33220. if (node !== objects[0]) {
  33221. for (var i = 0, il = objects.length; i < il; i++) {
  33222. node.add(objects[i]);
  33223. }
  33224. }
  33225. if (nodeDef.name) {
  33226. node.userData.name = nodeDef.name;
  33227. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  33228. }
  33229. assignExtrasToUserData(node, nodeDef);
  33230. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  33231. if (nodeDef.matrix !== undefined) {
  33232. var matrix = new _threeModule.Matrix4();
  33233. matrix.fromArray(nodeDef.matrix);
  33234. node.applyMatrix4(matrix);
  33235. } else {
  33236. if (nodeDef.translation !== undefined) {
  33237. node.position.fromArray(nodeDef.translation);
  33238. }
  33239. if (nodeDef.rotation !== undefined) {
  33240. node.quaternion.fromArray(nodeDef.rotation);
  33241. }
  33242. if (nodeDef.scale !== undefined) {
  33243. node.scale.fromArray(nodeDef.scale);
  33244. }
  33245. }
  33246. return node;
  33247. });
  33248. };
  33249. /**
  33250. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  33251. * @param {number} sceneIndex
  33252. * @return {Promise<Group>}
  33253. */
  33254. GLTFParser.prototype.loadScene = function () {
  33255. // scene node hierachy builder
  33256. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  33257. var nodeDef = json.nodes[nodeId];
  33258. return parser.getDependency('node', nodeId).then(function (node) {
  33259. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  33260. var skinEntry;
  33261. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  33262. skinEntry = skin;
  33263. var pendingJoints = [];
  33264. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  33265. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  33266. }
  33267. return Promise.all(pendingJoints);
  33268. }).then(function (jointNodes) {
  33269. node.traverse(function (mesh) {
  33270. if (!mesh.isMesh) return;
  33271. var bones = [];
  33272. var boneInverses = [];
  33273. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  33274. var jointNode = jointNodes[j];
  33275. if (jointNode) {
  33276. bones.push(jointNode);
  33277. var mat = new _threeModule.Matrix4();
  33278. if (skinEntry.inverseBindMatrices !== undefined) {
  33279. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  33280. }
  33281. boneInverses.push(mat);
  33282. } else {
  33283. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  33284. }
  33285. }
  33286. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  33287. });
  33288. return node;
  33289. });
  33290. }).then(function (node) {
  33291. // build node hierachy
  33292. parentObject.add(node);
  33293. var pending = [];
  33294. if (nodeDef.children) {
  33295. var children = nodeDef.children;
  33296. for (var i = 0, il = children.length; i < il; i++) {
  33297. var child = children[i];
  33298. pending.push(buildNodeHierachy(child, node, json, parser));
  33299. }
  33300. }
  33301. return Promise.all(pending);
  33302. });
  33303. }
  33304. return function loadScene(sceneIndex) {
  33305. var json = this.json;
  33306. var extensions = this.extensions;
  33307. var sceneDef = this.json.scenes[sceneIndex];
  33308. var parser = this; // Loader returns Group, not Scene.
  33309. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  33310. var scene = new _threeModule.Group();
  33311. if (sceneDef.name) scene.name = sceneDef.name;
  33312. assignExtrasToUserData(scene, sceneDef);
  33313. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  33314. var nodeIds = sceneDef.nodes || [];
  33315. var pending = [];
  33316. for (var i = 0, il = nodeIds.length; i < il; i++) {
  33317. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  33318. }
  33319. return Promise.all(pending).then(function () {
  33320. return scene;
  33321. });
  33322. };
  33323. }();
  33324. return GLTFLoader;
  33325. }();
  33326. exports.GLTFLoader = GLTFLoader;
  33327. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/B3DMLoader.js":[function(require,module,exports) {
  33328. "use strict";
  33329. Object.defineProperty(exports, "__esModule", {
  33330. value: true
  33331. });
  33332. exports.B3DMLoader = void 0;
  33333. var _B3DMLoaderBase = require("../base/B3DMLoaderBase.js");
  33334. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  33335. class B3DMLoader extends _B3DMLoaderBase.B3DMLoaderBase {
  33336. constructor(manager) {
  33337. super();
  33338. this.manager = manager;
  33339. }
  33340. parse(buffer) {
  33341. const b3dm = super.parse(buffer);
  33342. const gltfBuffer = b3dm.glbBytes.slice().buffer;
  33343. return new Promise((resolve, reject) => {
  33344. const manager = this.manager;
  33345. new _GLTFLoader.GLTFLoader(manager).parse(gltfBuffer, null, model => {
  33346. model.batchTable = b3dm.batchTable;
  33347. model.featureTable = b3dm.featureTable;
  33348. resolve(model);
  33349. }, reject);
  33350. });
  33351. }
  33352. }
  33353. exports.B3DMLoader = B3DMLoader;
  33354. },{"../base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/three/TilesGroup.js":[function(require,module,exports) {
  33355. "use strict";
  33356. Object.defineProperty(exports, "__esModule", {
  33357. value: true
  33358. });
  33359. exports.TilesGroup = void 0;
  33360. var _three = require("three");
  33361. // Specialization of "Group" that only updates world matrices of children if
  33362. // the transform has changed since the last update and ignores the "force"
  33363. // parameter under the assumption that the children tiles will not move.
  33364. const tempMat = new _three.Matrix4();
  33365. class TilesGroup extends _three.Group {
  33366. constructor(tilesRenderer) {
  33367. super();
  33368. this.tilesRenderer = tilesRenderer;
  33369. }
  33370. raycast(raycaster, intersects) {
  33371. this.tilesRenderer.raycast(raycaster, intersects);
  33372. }
  33373. updateMatrixWorld(force) {
  33374. if (this.matrixAutoUpdate) {
  33375. this.updateMatrix();
  33376. }
  33377. if (this.matrixWorldNeedsUpdate || force) {
  33378. if (this.parent === null) {
  33379. tempMat.copy(this.matrix);
  33380. } else {
  33381. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  33382. }
  33383. this.matrixWorldNeedsUpdate = false;
  33384. const elA = tempMat.elements;
  33385. const elB = this.matrixWorld.elements;
  33386. let isDifferent = false;
  33387. for (let i = 0; i < 16; i++) {
  33388. const itemA = elA[i];
  33389. const itemB = elB[i];
  33390. const diff = Math.abs(itemA - itemB);
  33391. if (diff > Number.EPSILON) {
  33392. isDifferent = true;
  33393. break;
  33394. }
  33395. }
  33396. if (isDifferent) {
  33397. this.matrixWorld.copy(tempMat); // update children
  33398. // the children will not have to change unless the parent group has updated
  33399. const children = this.children;
  33400. for (let i = 0, l = children.length; i < l; i++) {
  33401. children[i].updateMatrixWorld();
  33402. }
  33403. }
  33404. }
  33405. }
  33406. }
  33407. exports.TilesGroup = TilesGroup;
  33408. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/raycastTraverse.js":[function(require,module,exports) {
  33409. "use strict";
  33410. Object.defineProperty(exports, "__esModule", {
  33411. value: true
  33412. });
  33413. exports.raycastTraverseFirstHit = raycastTraverseFirstHit;
  33414. exports.raycastTraverse = raycastTraverse;
  33415. var _three = require("three");
  33416. const _sphere = new _three.Sphere();
  33417. const _mat = new _three.Matrix4();
  33418. const _vec = new _three.Vector3();
  33419. const _vec2 = new _three.Vector3();
  33420. const _ray = new _three.Ray();
  33421. const _hitArray = [];
  33422. function distanceSort(a, b) {
  33423. return a.distance - b.distance;
  33424. }
  33425. function intersectTileScene(scene, raycaster, intersects) {
  33426. // Don't intersect the box3 helpers because those are used for debugging
  33427. scene.traverse(c => {
  33428. if (!(c instanceof _three.Box3Helper)) {
  33429. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  33430. }
  33431. });
  33432. } // Returns the closest hit when traversing the tree
  33433. function raycastTraverseFirstHit(root, group, activeTiles, raycaster) {
  33434. // If the root is active make sure we've checked it
  33435. if (activeTiles.has(root)) {
  33436. intersectTileScene(root.cached.scene, raycaster, _hitArray);
  33437. if (_hitArray.length > 0) {
  33438. if (_hitArray.length > 1) {
  33439. _hitArray.sort(distanceSort);
  33440. }
  33441. _hitArray.length = 0;
  33442. return _hitArray[0];
  33443. } else {
  33444. return null;
  33445. }
  33446. } // TODO: see if we can avoid creating a new array here every time to save on memory
  33447. const array = [];
  33448. const children = root.children;
  33449. for (let i = 0, l = children.length; i < l; i++) {
  33450. const tile = children[i];
  33451. const cached = tile.cached;
  33452. const groupMatrixWorld = group.matrixWorld;
  33453. _mat.copy(groupMatrixWorld); // if we don't hit the sphere then early out
  33454. const sphere = cached.sphere;
  33455. if (sphere) {
  33456. _sphere.copy(sphere);
  33457. _sphere.applyMatrix4(_mat);
  33458. if (!raycaster.ray.intersectsSphere(_sphere)) {
  33459. continue;
  33460. }
  33461. } // TODO: check region
  33462. const boundingBox = cached.box;
  33463. const obbMat = cached.boxTransform;
  33464. if (boundingBox) {
  33465. _mat.multiply(obbMat);
  33466. _mat.getInverse(_mat);
  33467. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  33468. if (_ray.intersectBox(boundingBox, _vec)) {
  33469. // account for tile scale
  33470. let invScale;
  33471. _vec2.setFromMatrixScale(_mat);
  33472. invScale = _vec2.x;
  33473. if (Math.abs(Math.max(_vec2.x - _vec2.y, _vec2.x - _vec2.z)) > 1e-6) {
  33474. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when raycasting.');
  33475. } // if we intersect the box save the distance to the tile bounds
  33476. let data = {
  33477. distance: Infinity,
  33478. tile: null
  33479. };
  33480. array.push(data);
  33481. data.distance = _vec.distanceToSquared(_ray.origin) * invScale * invScale;
  33482. data.tile = tile;
  33483. } else {
  33484. continue;
  33485. }
  33486. }
  33487. } // sort them by ascending distance
  33488. array.sort(distanceSort); // traverse until we find the best hit and early out if a tile bounds
  33489. // couldn't possible include a best hit
  33490. let bestDistanceSquared = Infinity;
  33491. let bestHit = null;
  33492. for (let i = 0, l = array.length; i < l; i++) {
  33493. const data = array[i];
  33494. const distanceSquared = data.distance;
  33495. if (distanceSquared > bestDistanceSquared) {
  33496. break;
  33497. } else {
  33498. const tile = data.tile;
  33499. const scene = tile.cached.scene;
  33500. let hit = null;
  33501. if (activeTiles.has(tile)) {
  33502. // save the hit if it's closer
  33503. intersectTileScene(scene, raycaster, _hitArray);
  33504. if (_hitArray.length > 0) {
  33505. if (_hitArray.length > 1) {
  33506. _hitArray.sort(distanceSort);
  33507. }
  33508. hit = _hitArray[0];
  33509. }
  33510. } else {
  33511. hit = raycastTraverseFirstHit(tile, group, activeTiles, raycaster);
  33512. }
  33513. if (hit) {
  33514. const hitDistanceSquared = hit.distance * hit.distance;
  33515. if (hitDistanceSquared < bestDistanceSquared) {
  33516. bestDistanceSquared = hitDistanceSquared;
  33517. bestHit = hit;
  33518. }
  33519. _hitArray.length = 0;
  33520. }
  33521. }
  33522. }
  33523. return bestHit;
  33524. }
  33525. function raycastTraverse(tile, group, activeTiles, raycaster, intersects) {
  33526. const cached = tile.cached;
  33527. const groupMatrixWorld = group.matrixWorld;
  33528. _mat.copy(groupMatrixWorld);
  33529. const sphere = cached.sphere;
  33530. if (sphere) {
  33531. _sphere.copy(sphere);
  33532. _sphere.applyMatrix4(_mat);
  33533. if (!raycaster.ray.intersectsSphere(_sphere)) {
  33534. return;
  33535. }
  33536. }
  33537. const boundingBox = cached.box;
  33538. const obbMat = cached.boxTransform;
  33539. if (boundingBox) {
  33540. _mat.multiply(obbMat);
  33541. _mat.getInverse(_mat);
  33542. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  33543. if (!_ray.intersectsBox(boundingBox)) {
  33544. return;
  33545. }
  33546. } // TODO: check region
  33547. const scene = cached.scene;
  33548. if (activeTiles.has(tile)) {
  33549. scene.traverse(c => {
  33550. if (!(c instanceof _three.Box3Helper)) {
  33551. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  33552. }
  33553. });
  33554. return;
  33555. }
  33556. const children = tile.children;
  33557. for (let i = 0, l = children.length; i < l; i++) {
  33558. raycastTraverse(children[i], group, activeTiles, raycaster, intersects);
  33559. }
  33560. }
  33561. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/TilesRenderer.js":[function(require,module,exports) {
  33562. "use strict";
  33563. Object.defineProperty(exports, "__esModule", {
  33564. value: true
  33565. });
  33566. exports.TilesRenderer = void 0;
  33567. var _TilesRendererBase = require("../base/TilesRendererBase.js");
  33568. var _B3DMLoader = require("./B3DMLoader.js");
  33569. var _TilesGroup = require("./TilesGroup.js");
  33570. var _three = require("three");
  33571. var _raycastTraverse = require("./raycastTraverse.js");
  33572. const DEG2RAD = _three.Math.DEG2RAD;
  33573. const tempMat = new _three.Matrix4();
  33574. const tempMat2 = new _three.Matrix4();
  33575. const tempVector = new _three.Vector3();
  33576. const vecX = new _three.Vector3();
  33577. const vecY = new _three.Vector3();
  33578. const vecZ = new _three.Vector3();
  33579. const X_AXIS = new _three.Vector3(1, 0, 0);
  33580. const Y_AXIS = new _three.Vector3(0, 1, 0);
  33581. const useImageBitmap = typeof createImageBitmap !== 'undefined';
  33582. function emptyRaycast() {}
  33583. class TilesRenderer extends _TilesRendererBase.TilesRendererBase {
  33584. constructor(...args) {
  33585. super(...args);
  33586. this.group = new _TilesGroup.TilesGroup(this);
  33587. this.cameras = [];
  33588. this.cameraMap = new Map();
  33589. this.resolution = new _three.Vector2();
  33590. this.cameraInfo = [];
  33591. this.activeTiles = new Set();
  33592. this.visibleTiles = new Set();
  33593. }
  33594. /* Public API */
  33595. getBounds(box) {
  33596. if (!this.root) {
  33597. return false;
  33598. }
  33599. const cached = this.root.cached;
  33600. const boundingBox = cached.box;
  33601. const obbMat = cached.boxTransform;
  33602. if (boundingBox) {
  33603. box.copy(boundingBox);
  33604. box.applyMatrix4(obbMat);
  33605. return true;
  33606. } else {
  33607. return false;
  33608. }
  33609. }
  33610. raycast(raycaster, intersects) {
  33611. if (!this.root) {
  33612. return;
  33613. }
  33614. if (raycaster.firstHitOnly) {
  33615. const hit = (0, _raycastTraverse.raycastTraverseFirstHit)(this.root, this.group, this.activeTiles, raycaster);
  33616. if (hit) {
  33617. intersects.push(hit);
  33618. }
  33619. } else {
  33620. (0, _raycastTraverse.raycastTraverse)(this.root, this.group, this.activeTiles, raycaster, intersects);
  33621. }
  33622. }
  33623. hasCamera(camera) {
  33624. return this.cameraMap.has(camera);
  33625. }
  33626. setCamera(camera) {
  33627. const cameras = this.cameras;
  33628. const cameraMap = this.cameraMap;
  33629. if (!cameraMap.has(camera)) {
  33630. cameraMap.set(camera, new _three.Vector2());
  33631. cameras.push(camera);
  33632. return true;
  33633. }
  33634. return false;
  33635. }
  33636. setResolution(camera, xOrVec, y) {
  33637. const cameraMap = this.cameraMap;
  33638. if (!cameraMap.has(camera)) {
  33639. return false;
  33640. }
  33641. if (xOrVec instanceof _three.Vector2) {
  33642. cameraMap.get(camera).copy(xOrVec);
  33643. } else {
  33644. cameraMap.get(camera).set(xOrVec, y);
  33645. }
  33646. return true;
  33647. }
  33648. setResolutionFromRenderer(camera, renderer) {
  33649. const cameraMap = this.cameraMap;
  33650. if (!cameraMap.has(camera)) {
  33651. return false;
  33652. }
  33653. const resolution = cameraMap.get(camera);
  33654. renderer.getSize(resolution);
  33655. resolution.multiplyScalar(renderer.getPixelRatio());
  33656. return true;
  33657. }
  33658. deleteCamera(camera) {
  33659. const cameras = this.cameras;
  33660. const cameraMap = this.cameraMap;
  33661. if (cameraMap.has(camera)) {
  33662. const index = cameras.indexOf(camera);
  33663. cameras.splice(index, 1);
  33664. cameraMap.delete(camera);
  33665. return true;
  33666. }
  33667. return false;
  33668. }
  33669. /* Overriden */
  33670. update() {
  33671. const group = this.group;
  33672. const cameras = this.cameras;
  33673. const cameraMap = this.cameraMap;
  33674. const cameraInfo = this.cameraInfo;
  33675. if (cameras.length === 0) {
  33676. console.warn('TilesRenderer: no cameras defined. Cannot update 3d tiles.');
  33677. return;
  33678. } // automatically scale the array of cameraInfo to match the cameras
  33679. while (cameraInfo.length > cameras.length) {
  33680. cameraInfo.pop();
  33681. }
  33682. while (cameraInfo.length < cameras.length) {
  33683. cameraInfo.push({
  33684. frustum: new _three.Frustum(),
  33685. sseDenominator: -1,
  33686. position: new _three.Vector3(),
  33687. invScale: -1,
  33688. pixelSize: 0
  33689. });
  33690. } // extract scale of group container
  33691. tempMat2.getInverse(group.matrixWorld);
  33692. let invScale;
  33693. tempVector.setFromMatrixScale(tempMat2);
  33694. invScale = tempVector.x;
  33695. if (Math.abs(Math.max(tempVector.x - tempVector.y, tempVector.x - tempVector.z)) > 1e-6) {
  33696. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.');
  33697. } // store the camera cameraInfo in the 3d tiles root frame
  33698. for (let i = 0, l = cameraInfo.length; i < l; i++) {
  33699. const camera = cameras[i];
  33700. const info = cameraInfo[i];
  33701. const frustum = info.frustum;
  33702. const position = info.position;
  33703. const resolution = cameraMap.get(camera);
  33704. if (resolution.width === 0 || resolution.height === 0) {
  33705. console.warn('TilesRenderer: resolution for camera error calculation is not set.');
  33706. }
  33707. if (camera.isPerspectiveCamera) {
  33708. info.sseDenominator = 2 * Math.tan(0.5 * camera.fov * DEG2RAD) / resolution.height;
  33709. }
  33710. if (camera.isOrthographicCamera) {
  33711. const w = camera.right - camera.left;
  33712. const h = camera.top - camera.bottom;
  33713. info.pixelSize = Math.max(h / resolution.height, w / resolution.width);
  33714. }
  33715. info.invScale = invScale; // get frustum in grop root frame
  33716. tempMat.copy(group.matrixWorld);
  33717. tempMat.premultiply(camera.matrixWorldInverse);
  33718. tempMat.premultiply(camera.projectionMatrix);
  33719. frustum.setFromProjectionMatrix(tempMat); // get transform position in group root frame
  33720. position.set(0, 0, 0);
  33721. position.applyMatrix4(camera.matrixWorld);
  33722. position.applyMatrix4(tempMat2);
  33723. }
  33724. super.update();
  33725. }
  33726. preprocessNode(tile, parentTile, tileSetDir) {
  33727. super.preprocessNode(tile, parentTile, tileSetDir);
  33728. const transform = new _three.Matrix4();
  33729. if (tile.transform) {
  33730. const transformArr = tile.transform;
  33731. for (let i = 0; i < 16; i++) {
  33732. transform.elements[i] = transformArr[i];
  33733. }
  33734. } else {
  33735. transform.identity();
  33736. }
  33737. if (parentTile) {
  33738. transform.multiply(parentTile.cached.transform);
  33739. }
  33740. let box = null;
  33741. let boxTransform = null;
  33742. let boxTransformInverse = null;
  33743. if ('box' in tile.boundingVolume) {
  33744. const data = tile.boundingVolume.box;
  33745. box = new _three.Box3();
  33746. boxTransform = new _three.Matrix4();
  33747. boxTransformInverse = new _three.Matrix4(); // get the extents of the bounds in each axis
  33748. vecX.set(data[3], data[4], data[5]);
  33749. vecY.set(data[6], data[7], data[8]);
  33750. vecZ.set(data[9], data[10], data[11]);
  33751. const scaleX = vecX.length();
  33752. const scaleY = vecY.length();
  33753. const scaleZ = vecZ.length();
  33754. vecX.normalize();
  33755. vecY.normalize();
  33756. vecZ.normalize(); // create the oriented frame that the box exists in
  33757. 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);
  33758. boxTransform.premultiply(transform);
  33759. boxTransformInverse.getInverse(boxTransform); // scale the box by the extents
  33760. box.min.set(-scaleX, -scaleY, -scaleZ);
  33761. box.max.set(scaleX, scaleY, scaleZ);
  33762. }
  33763. let sphere = null;
  33764. if ('sphere' in tile.boundingVolume) {
  33765. const data = tile.boundingVolume.sphere;
  33766. sphere = new _three.Sphere();
  33767. sphere.center.set(data[0], data[1], data[2]);
  33768. sphere.radius = data[3];
  33769. sphere.applyMatrix4(transform);
  33770. } else if ('box' in tile.boundingVolume) {
  33771. const data = tile.boundingVolume.box;
  33772. sphere = new _three.Sphere();
  33773. box.getBoundingSphere(sphere);
  33774. sphere.center.set(data[0], data[1], data[2]);
  33775. sphere.applyMatrix4(transform);
  33776. }
  33777. let region = null;
  33778. if ('region' in tile.boundingVolume) {
  33779. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  33780. }
  33781. tile.cached = {
  33782. loadIndex: 0,
  33783. transform,
  33784. active: false,
  33785. inFrustum: [],
  33786. box,
  33787. boxTransform,
  33788. boxTransformInverse,
  33789. sphere,
  33790. region,
  33791. scene: null,
  33792. geometry: null,
  33793. material: null,
  33794. distance: Infinity
  33795. };
  33796. }
  33797. parseTile(buffer, tile, extension) {
  33798. tile._loadIndex = tile._loadIndex || 0;
  33799. tile._loadIndex++;
  33800. const loadIndex = tile._loadIndex;
  33801. const manager = new _three.LoadingManager();
  33802. let promise = null;
  33803. if (useImageBitmap) {
  33804. // TODO: We should verify that `flipY` is false on the resulting texture after load because it can't be modified after
  33805. // the fact. Premultiply alpha default behavior is not well defined, either.
  33806. // TODO: Determine whether or not options are supported before using this so we can force flipY false and premultiply alpha
  33807. // behavior. Fall back to regular texture loading
  33808. manager.addHandler(/(^blob:)|(\.png$)|(\.jpg$)|(\.jpeg$)/g, {
  33809. load(url, onComplete) {
  33810. const loader = new _three.ImageBitmapLoader();
  33811. loader.load(url, res => {
  33812. onComplete(new _three.CanvasTexture(res));
  33813. });
  33814. }
  33815. });
  33816. }
  33817. switch (extension) {
  33818. case 'b3dm':
  33819. promise = new _B3DMLoader.B3DMLoader(manager).parse(buffer);
  33820. break;
  33821. case 'pnts':
  33822. case 'cmpt':
  33823. case 'i3dm':
  33824. default:
  33825. console.warn(`TilesRenderer: Content type "${extension}" not supported.`);
  33826. promise = Promise.resolve(null);
  33827. break;
  33828. }
  33829. return promise.then(res => {
  33830. if (tile._loadIndex !== loadIndex) {
  33831. return;
  33832. }
  33833. const upAxis = this.rootTileSet.asset && this.rootTileSet.asset.gltfUpAxis || 'y';
  33834. const cached = tile.cached;
  33835. const cachedTransform = cached.transform;
  33836. const scene = res ? res.scene : new _three.Group();
  33837. switch (upAxis.toLowerCase()) {
  33838. case 'x':
  33839. scene.matrix.makeRotationAxis(Y_AXIS, -Math.PI / 2);
  33840. break;
  33841. case 'y':
  33842. scene.matrix.makeRotationAxis(X_AXIS, Math.PI / 2);
  33843. break;
  33844. case 'z':
  33845. break;
  33846. }
  33847. scene.matrix.premultiply(cachedTransform);
  33848. scene.matrix.decompose(scene.position, scene.quaternion, scene.scale);
  33849. scene.traverse(c => c.frustumCulled = false);
  33850. cached.scene = scene; // We handle raycasting in a custom way so remove it from here
  33851. scene.traverse(c => {
  33852. c.raycast = emptyRaycast;
  33853. });
  33854. const materials = [];
  33855. const geometry = [];
  33856. const textures = [];
  33857. scene.traverse(c => {
  33858. if (c.geometry) {
  33859. geometry.push(c.geometry);
  33860. }
  33861. if (c.material) {
  33862. const material = c.material;
  33863. materials.push(c.material);
  33864. for (const key in material) {
  33865. const value = material[key];
  33866. if (value && value.isTexture) {
  33867. textures.push(value);
  33868. }
  33869. }
  33870. }
  33871. });
  33872. cached.materials = materials;
  33873. cached.geometry = geometry;
  33874. cached.textures = textures;
  33875. });
  33876. }
  33877. disposeTile(tile) {
  33878. // This could get called before the tile has finished downloading
  33879. const cached = tile.cached;
  33880. if (cached.scene) {
  33881. const materials = cached.materials;
  33882. const geometry = cached.geometry;
  33883. const textures = cached.textures;
  33884. for (let i = 0, l = geometry.length; i < l; i++) {
  33885. geometry[i].dispose();
  33886. }
  33887. for (let i = 0, l = materials.length; i < l; i++) {
  33888. materials[i].dispose();
  33889. }
  33890. for (let i = 0, l = textures.length; i < l; i++) {
  33891. const texture = textures[i];
  33892. texture.dispose();
  33893. if (useImageBitmap && 'close' in texture.image) {
  33894. texture.image.close();
  33895. }
  33896. }
  33897. cached.scene = null;
  33898. cached.materials = null;
  33899. cached.textures = null;
  33900. cached.geometry = null;
  33901. }
  33902. tile._loadIndex++;
  33903. }
  33904. setTileVisible(tile, visible) {
  33905. const scene = tile.cached.scene;
  33906. const visibleTiles = this.visibleTiles;
  33907. const group = this.group;
  33908. if (visible) {
  33909. group.add(scene);
  33910. visibleTiles.add(tile);
  33911. scene.updateMatrixWorld(true);
  33912. } else {
  33913. group.remove(scene);
  33914. visibleTiles.delete(tile);
  33915. }
  33916. }
  33917. setTileActive(tile, active) {
  33918. const activeTiles = this.activeTiles;
  33919. if (active) {
  33920. activeTiles.add(tile);
  33921. } else {
  33922. activeTiles.delete(tile);
  33923. }
  33924. }
  33925. calculateError(tile) {
  33926. if (tile.geometricError === 0.0) {
  33927. return 0.0;
  33928. }
  33929. const cached = tile.cached;
  33930. const inFrustum = cached.inFrustum;
  33931. const cameras = this.cameras;
  33932. const cameraInfo = this.cameraInfo; // TODO: Use the content bounding volume here?
  33933. const boundingVolume = tile.boundingVolume;
  33934. if ('box' in boundingVolume) {
  33935. const boundingBox = cached.box;
  33936. const boxTransformInverse = cached.boxTransformInverse;
  33937. let maxError = -Infinity;
  33938. let minDistance = Infinity;
  33939. for (let i = 0, l = cameras.length; i < l; i++) {
  33940. if (!inFrustum[i]) {
  33941. continue;
  33942. } // transform camera position into local frame of the tile bounding box
  33943. const camera = cameras[i];
  33944. const info = cameraInfo[i];
  33945. const invScale = info.invScale;
  33946. tempVector.copy(info.position);
  33947. tempVector.applyMatrix4(boxTransformInverse);
  33948. let error;
  33949. if (camera.isOrthographicCamera) {
  33950. const pixelSize = info.pixelSize;
  33951. error = tile.geometricError / (pixelSize * invScale);
  33952. } else {
  33953. const distance = boundingBox.distanceToPoint(tempVector);
  33954. const scaledDistance = distance * invScale;
  33955. const sseDenominator = info.sseDenominator;
  33956. error = tile.geometricError / (scaledDistance * sseDenominator);
  33957. minDistance = Math.min(minDistance, scaledDistance);
  33958. }
  33959. maxError = Math.max(maxError, error);
  33960. }
  33961. tile.cached.distance = minDistance;
  33962. return maxError;
  33963. } else if ('sphere' in boundingVolume) {
  33964. // const sphere = cached.sphere;
  33965. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  33966. } else if ('region' in boundingVolume) {
  33967. // unsupported
  33968. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  33969. }
  33970. return Infinity;
  33971. }
  33972. tileInView(tile) {
  33973. // TODO: we should use the more precise bounding volumes here if possible
  33974. // cache the root-space planes
  33975. // Use separating axis theorem for frustum and obb
  33976. const cached = tile.cached;
  33977. const sphere = cached.sphere;
  33978. const inFrustum = cached.inFrustum;
  33979. if (sphere) {
  33980. const cameraInfo = this.cameraInfo;
  33981. let inView = false;
  33982. for (let i = 0, l = cameraInfo.length; i < l; i++) {
  33983. // Track which camera frustums this tile is in so we can use it
  33984. // to ignore the error calculations for cameras that can't see it
  33985. const frustum = cameraInfo[i].frustum;
  33986. if (frustum.intersectsSphere(sphere)) {
  33987. inView = true;
  33988. inFrustum[i] = true;
  33989. } else {
  33990. inFrustum[i] = false;
  33991. }
  33992. }
  33993. return inView;
  33994. }
  33995. return true;
  33996. }
  33997. }
  33998. exports.TilesRenderer = TilesRenderer;
  33999. },{"../base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.js","./TilesGroup.js":"../src/three/TilesGroup.js","three":"../node_modules/three/build/three.module.js","./raycastTraverse.js":"../src/three/raycastTraverse.js"}],"../src/three/SphereHelper.js":[function(require,module,exports) {
  34000. "use strict";
  34001. Object.defineProperty(exports, "__esModule", {
  34002. value: true
  34003. });
  34004. exports.SphereHelper = void 0;
  34005. var _three = require("three");
  34006. const _vector = new _three.Vector3();
  34007. const axes = ['x', 'y', 'z'];
  34008. class SphereHelper extends _three.LineSegments {
  34009. constructor(sphere, color = 0xffff00, angleSteps = 40) {
  34010. const geometry = new _three.BufferGeometry();
  34011. const positions = [];
  34012. for (let i = 0; i < 3; i++) {
  34013. const axis1 = axes[i];
  34014. const axis2 = axes[(i + 1) % 3];
  34015. _vector.set(0, 0, 0);
  34016. for (let a = 0; a < angleSteps; a++) {
  34017. let angle;
  34018. angle = 2 * Math.PI * a / (angleSteps - 1);
  34019. _vector[axis1] = Math.sin(angle);
  34020. _vector[axis2] = Math.cos(angle);
  34021. positions.push(_vector.x, _vector.y, _vector.z);
  34022. angle = 2 * Math.PI * (a + 1) / (angleSteps - 1);
  34023. _vector[axis1] = Math.sin(angle);
  34024. _vector[axis2] = Math.cos(angle);
  34025. positions.push(_vector.x, _vector.y, _vector.z);
  34026. }
  34027. }
  34028. geometry.setAttribute('position', new _three.BufferAttribute(new Float32Array(positions), 3));
  34029. geometry.computeBoundingSphere();
  34030. super(geometry, new _three.LineBasicMaterial({
  34031. color: color,
  34032. toneMapped: false
  34033. }));
  34034. this.sphere = sphere;
  34035. this.type = 'SphereHelper';
  34036. }
  34037. updateMatrixWorld(force) {
  34038. // TODO: Why doesn't this radius have to be multiplied by 0.5?
  34039. const sphere = this.sphere;
  34040. this.position.copy(sphere.center);
  34041. this.scale.setScalar(sphere.radius);
  34042. super.updateMatrixWorld(force);
  34043. }
  34044. }
  34045. exports.SphereHelper = SphereHelper;
  34046. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/DebugTilesRenderer.js":[function(require,module,exports) {
  34047. "use strict";
  34048. Object.defineProperty(exports, "__esModule", {
  34049. value: true
  34050. });
  34051. exports.DebugTilesRenderer = void 0;
  34052. var _three = require("three");
  34053. var _TilesRenderer = require("./TilesRenderer.js");
  34054. var _SphereHelper = require("./SphereHelper.js");
  34055. const ORIGINAL_MATERIAL = Symbol('ORIGINAL_MATERIAL');
  34056. const NONE = 0;
  34057. const SCREEN_ERROR = 1;
  34058. const GEOMETRIC_ERROR = 2;
  34059. const DISTANCE = 3;
  34060. const DEPTH = 4;
  34061. const IS_LEAF = 5;
  34062. const RANDOM_COLOR = 6;
  34063. function emptyRaycast() {}
  34064. class DebugTilesRenderer extends _TilesRenderer.TilesRenderer {
  34065. constructor(...args) {
  34066. super(...args);
  34067. const tilesGroup = this.group;
  34068. const boxGroup = new _three.Group();
  34069. tilesGroup.add(boxGroup);
  34070. const sphereGroup = new _three.Group();
  34071. tilesGroup.add(sphereGroup);
  34072. this.displayBoxBounds = false;
  34073. this.displaySphereBounds = false;
  34074. this.colorMode = NONE;
  34075. this.boxGroup = boxGroup;
  34076. this.sphereGroup = sphereGroup;
  34077. this.maxDepth = -1;
  34078. this.maxDistance = -1;
  34079. this.maxError = -1;
  34080. this.extremeDepth = -1;
  34081. this.extremeError = -1;
  34082. }
  34083. initExtremes() {
  34084. let maxDepth = -1;
  34085. this.traverse(tile => {
  34086. maxDepth = Math.max(maxDepth, tile.__depth);
  34087. });
  34088. let maxError = -1;
  34089. this.traverse(tile => {
  34090. maxError = Math.max(maxError, tile.geometricError);
  34091. });
  34092. this.extremeDepth = maxDepth;
  34093. this.extremeError = maxError;
  34094. }
  34095. loadTileSet(...args) {
  34096. const pr = super.loadTileSet(...args);
  34097. pr.then(() => this.initExtremes());
  34098. return pr;
  34099. }
  34100. getTileInformationFromActiveObject(object) {
  34101. let targetTile = null;
  34102. const activeTiles = this.activeTiles;
  34103. activeTiles.forEach(tile => {
  34104. if (targetTile) {
  34105. return true;
  34106. }
  34107. const scene = tile.cached.scene;
  34108. if (scene) {
  34109. scene.traverse(c => {
  34110. if (c === object) {
  34111. targetTile = tile;
  34112. }
  34113. });
  34114. }
  34115. });
  34116. if (targetTile) {
  34117. return {
  34118. distanceToCamera: targetTile.cached.distance,
  34119. geometricError: targetTile.geometricError,
  34120. screenSpaceError: targetTile.__error,
  34121. depth: targetTile.__depth,
  34122. isLeaf: targetTile.__isLeaf
  34123. };
  34124. } else {
  34125. return null;
  34126. }
  34127. }
  34128. update() {
  34129. super.update();
  34130. if (!this.root) {
  34131. return;
  34132. }
  34133. this.boxGroup.visible = this.displayBoxBounds;
  34134. this.sphereGroup.visible = this.displaySphereBounds;
  34135. let maxDepth = -1;
  34136. if (this.maxDepth === -1) {
  34137. maxDepth = this.extremeDepth;
  34138. } else {
  34139. maxDepth = this.maxDepth;
  34140. }
  34141. let maxError = -1;
  34142. if (this.maxError === -1) {
  34143. maxError = this.extremeError;
  34144. } else {
  34145. maxError = this.maxError;
  34146. }
  34147. let maxDistance = -1;
  34148. if (this.maxDistance === -1) {
  34149. maxDistance = this.root.cached.sphere.radius;
  34150. } else {
  34151. maxDistance = this.maxDistance;
  34152. } // TODO: Support i3dm, pnts, cmpt here
  34153. const errorTarget = this.errorTarget;
  34154. const colorMode = this.colorMode;
  34155. const visibleTiles = this.visibleTiles;
  34156. visibleTiles.forEach(tile => {
  34157. const scene = tile.cached.scene;
  34158. scene.traverse(c => {
  34159. const currMaterial = c.material;
  34160. if (currMaterial) {
  34161. const originalMaterial = c[ORIGINAL_MATERIAL];
  34162. if (colorMode === NONE && currMaterial !== originalMaterial) {
  34163. c.material.dispose();
  34164. c.material = c[ORIGINAL_MATERIAL];
  34165. } else if (colorMode !== NONE && currMaterial === originalMaterial) {
  34166. c.material = new _three.MeshBasicMaterial();
  34167. }
  34168. if (colorMode !== RANDOM_COLOR) {
  34169. delete c.material.__randomColor;
  34170. }
  34171. switch (colorMode) {
  34172. case DEPTH:
  34173. {
  34174. const val = tile.__depth / maxDepth;
  34175. c.material.color.setRGB(val, val, val);
  34176. break;
  34177. }
  34178. case SCREEN_ERROR:
  34179. {
  34180. const val = tile.__error / errorTarget;
  34181. if (val > 1.0) {
  34182. c.material.color.setRGB(1.0, 0.0, 0.0);
  34183. } else {
  34184. c.material.color.setRGB(val, val, val);
  34185. }
  34186. break;
  34187. }
  34188. case GEOMETRIC_ERROR:
  34189. {
  34190. const val = Math.min(tile.geometricError / maxError, 1);
  34191. c.material.color.setRGB(val, val, val);
  34192. break;
  34193. }
  34194. case DISTANCE:
  34195. {
  34196. // We don't update the distance if the geometric error is 0.0 so
  34197. // it will always be black.
  34198. const val = Math.min(tile.cached.distance / maxDistance, 1);
  34199. c.material.color.setRGB(val, val, val);
  34200. break;
  34201. }
  34202. case IS_LEAF:
  34203. {
  34204. if (!tile.children || tile.children.length === 0) {
  34205. c.material.color.set(0xffffff);
  34206. } else {
  34207. c.material.color.set(0);
  34208. }
  34209. break;
  34210. }
  34211. case RANDOM_COLOR:
  34212. {
  34213. if (!c.material.__randomColor) {
  34214. const h = Math.random();
  34215. const s = 0.5 + Math.random() * 0.5;
  34216. const l = 0.375 + Math.random() * 0.25;
  34217. c.material.color.setHSL(h, s, l);
  34218. c.material.__randomColor = true;
  34219. }
  34220. break;
  34221. }
  34222. }
  34223. }
  34224. });
  34225. });
  34226. }
  34227. setTileVisible(tile, visible) {
  34228. super.setTileVisible(tile, visible);
  34229. const cached = tile.cached;
  34230. const sphereGroup = this.sphereGroup;
  34231. const boxGroup = this.boxGroup;
  34232. const boxHelperGroup = cached.boxHelperGroup;
  34233. const sphereHelper = cached.sphereHelper;
  34234. if (!visible) {
  34235. boxGroup.remove(boxHelperGroup);
  34236. sphereGroup.remove(sphereHelper);
  34237. } else {
  34238. boxGroup.add(boxHelperGroup);
  34239. boxHelperGroup.updateMatrixWorld(true);
  34240. sphereGroup.add(sphereHelper);
  34241. sphereHelper.updateMatrixWorld(true);
  34242. }
  34243. }
  34244. parseTile(buffer, tile, extension) {
  34245. return super.parseTile(buffer, tile, extension).then(() => {
  34246. const cached = tile.cached;
  34247. const scene = cached.scene;
  34248. if (scene) {
  34249. const cachedBox = cached.box;
  34250. const cachedBoxMat = cached.boxTransform;
  34251. const boxHelperGroup = new _three.Group();
  34252. boxHelperGroup.matrix.copy(cachedBoxMat);
  34253. boxHelperGroup.matrix.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  34254. const boxHelper = new _three.Box3Helper(cachedBox);
  34255. boxHelper.raycast = emptyRaycast;
  34256. boxHelperGroup.add(boxHelper);
  34257. cached.boxHelperGroup = boxHelperGroup;
  34258. if (this.visibleTiles.has(tile) && this.displayBoxBounds) {
  34259. this.boxGroup.add(boxHelperGroup);
  34260. boxHelperGroup.updateMatrixWorld(true);
  34261. }
  34262. const cachedSphere = cached.sphere;
  34263. const sphereHelper = new _SphereHelper.SphereHelper(cachedSphere);
  34264. sphereHelper.raycast = emptyRaycast;
  34265. cached.sphereHelper = sphereHelper;
  34266. if (this.visibleTiles.has(tile) && this.displaySphereBounds) {
  34267. this.sphereGroup.add(sphereHelper);
  34268. sphereHelper.updateMatrixWorld(true);
  34269. }
  34270. scene.traverse(c => {
  34271. const material = c.material;
  34272. if (material) {
  34273. c[ORIGINAL_MATERIAL] = material;
  34274. }
  34275. });
  34276. }
  34277. });
  34278. }
  34279. disposeTile(tile) {
  34280. super.disposeTile(tile);
  34281. const cached = tile.cached;
  34282. if (cached.boxHelperGroup) {
  34283. cached.boxHelperGroup.children[0].geometry.dispose();
  34284. cached.sphereHelper.geometry.dispose();
  34285. delete cached.boxHelperGroup;
  34286. delete cached.sphereHelper;
  34287. }
  34288. }
  34289. }
  34290. exports.DebugTilesRenderer = DebugTilesRenderer;
  34291. },{"three":"../node_modules/three/build/three.module.js","./TilesRenderer.js":"../src/three/TilesRenderer.js","./SphereHelper.js":"../src/three/SphereHelper.js"}],"../src/index.js":[function(require,module,exports) {
  34292. "use strict";
  34293. Object.defineProperty(exports, "__esModule", {
  34294. value: true
  34295. });
  34296. Object.defineProperty(exports, "DebugTilesRenderer", {
  34297. enumerable: true,
  34298. get: function () {
  34299. return _DebugTilesRenderer.DebugTilesRenderer;
  34300. }
  34301. });
  34302. Object.defineProperty(exports, "TilesRenderer", {
  34303. enumerable: true,
  34304. get: function () {
  34305. return _TilesRenderer.TilesRenderer;
  34306. }
  34307. });
  34308. Object.defineProperty(exports, "B3DMLoader", {
  34309. enumerable: true,
  34310. get: function () {
  34311. return _B3DMLoader.B3DMLoader;
  34312. }
  34313. });
  34314. Object.defineProperty(exports, "TilesRendererBase", {
  34315. enumerable: true,
  34316. get: function () {
  34317. return _TilesRendererBase.TilesRendererBase;
  34318. }
  34319. });
  34320. Object.defineProperty(exports, "B3DMLoaderBase", {
  34321. enumerable: true,
  34322. get: function () {
  34323. return _B3DMLoaderBase.B3DMLoaderBase;
  34324. }
  34325. });
  34326. Object.defineProperty(exports, "LRUCache", {
  34327. enumerable: true,
  34328. get: function () {
  34329. return _LRUCache.LRUCache;
  34330. }
  34331. });
  34332. Object.defineProperty(exports, "PriorityQueue", {
  34333. enumerable: true,
  34334. get: function () {
  34335. return _PriorityQueue.PriorityQueue;
  34336. }
  34337. });
  34338. var _DebugTilesRenderer = require("./three/DebugTilesRenderer.js");
  34339. var _TilesRenderer = require("./three/TilesRenderer.js");
  34340. var _B3DMLoader = require("./three/B3DMLoader.js");
  34341. var _TilesRendererBase = require("./base/TilesRendererBase.js");
  34342. var _B3DMLoaderBase = require("./base/B3DMLoaderBase.js");
  34343. var _LRUCache = require("./utilities/LRUCache.js");
  34344. var _PriorityQueue = require("./utilities/PriorityQueue.js");
  34345. },{"./three/DebugTilesRenderer.js":"../src/three/DebugTilesRenderer.js","./three/TilesRenderer.js":"../src/three/TilesRenderer.js","./three/B3DMLoader.js":"../src/three/B3DMLoader.js","./base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","./utilities/LRUCache.js":"../src/utilities/LRUCache.js","./utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  34346. "use strict";
  34347. Object.defineProperty(exports, "__esModule", {
  34348. value: true
  34349. });
  34350. exports.MapControls = exports.OrbitControls = void 0;
  34351. var _threeModule = require("../../../build/three.module.js");
  34352. /**
  34353. * @author qiao / https://github.com/qiao
  34354. * @author mrdoob / http://mrdoob.com
  34355. * @author alteredq / http://alteredqualia.com/
  34356. * @author WestLangley / http://github.com/WestLangley
  34357. * @author erich666 / http://erichaines.com
  34358. * @author ScieCode / http://github.com/sciecode
  34359. */
  34360. // This set of controls performs orbiting, dollying (zooming), and panning.
  34361. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  34362. //
  34363. // Orbit - left mouse / touch: one-finger move
  34364. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  34365. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  34366. var OrbitControls = function (object, domElement) {
  34367. if (domElement === undefined) console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.');
  34368. if (domElement === document) console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.');
  34369. this.object = object;
  34370. this.domElement = domElement; // Set to false to disable this control
  34371. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  34372. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  34373. this.minDistance = 0;
  34374. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  34375. this.minZoom = 0;
  34376. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  34377. // Range is 0 to Math.PI radians.
  34378. this.minPolarAngle = 0; // radians
  34379. this.maxPolarAngle = Math.PI; // radians
  34380. // How far you can orbit horizontally, upper and lower limits.
  34381. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  34382. this.minAzimuthAngle = -Infinity; // radians
  34383. this.maxAzimuthAngle = Infinity; // radians
  34384. // Set to true to enable damping (inertia)
  34385. // If damping is enabled, you must call controls.update() in your animation loop
  34386. this.enableDamping = false;
  34387. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  34388. // Set to false to disable zooming
  34389. this.enableZoom = true;
  34390. this.zoomSpeed = 1.0; // Set to false to disable rotating
  34391. this.enableRotate = true;
  34392. this.rotateSpeed = 1.0; // Set to false to disable panning
  34393. this.enablePan = true;
  34394. this.panSpeed = 1.0;
  34395. this.screenSpacePanning = false; // if true, pan in screen-space
  34396. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  34397. // Set to true to automatically rotate around the target
  34398. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  34399. this.autoRotate = false;
  34400. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  34401. // Set to false to disable use of the keys
  34402. this.enableKeys = true; // The four arrow keys
  34403. this.keys = {
  34404. LEFT: 37,
  34405. UP: 38,
  34406. RIGHT: 39,
  34407. BOTTOM: 40
  34408. }; // Mouse buttons
  34409. this.mouseButtons = {
  34410. LEFT: _threeModule.MOUSE.ROTATE,
  34411. MIDDLE: _threeModule.MOUSE.DOLLY,
  34412. RIGHT: _threeModule.MOUSE.PAN
  34413. }; // Touch fingers
  34414. this.touches = {
  34415. ONE: _threeModule.TOUCH.ROTATE,
  34416. TWO: _threeModule.TOUCH.DOLLY_PAN
  34417. }; // for reset
  34418. this.target0 = this.target.clone();
  34419. this.position0 = this.object.position.clone();
  34420. this.zoom0 = this.object.zoom; //
  34421. // public methods
  34422. //
  34423. this.getPolarAngle = function () {
  34424. return spherical.phi;
  34425. };
  34426. this.getAzimuthalAngle = function () {
  34427. return spherical.theta;
  34428. };
  34429. this.saveState = function () {
  34430. scope.target0.copy(scope.target);
  34431. scope.position0.copy(scope.object.position);
  34432. scope.zoom0 = scope.object.zoom;
  34433. };
  34434. this.reset = function () {
  34435. scope.target.copy(scope.target0);
  34436. scope.object.position.copy(scope.position0);
  34437. scope.object.zoom = scope.zoom0;
  34438. scope.object.updateProjectionMatrix();
  34439. scope.dispatchEvent(changeEvent);
  34440. scope.update();
  34441. state = STATE.NONE;
  34442. }; // this method is exposed, but perhaps it would be better if we can make it private...
  34443. this.update = function () {
  34444. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  34445. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  34446. var quatInverse = quat.clone().inverse();
  34447. var lastPosition = new _threeModule.Vector3();
  34448. var lastQuaternion = new _threeModule.Quaternion();
  34449. return function update() {
  34450. var position = scope.object.position;
  34451. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  34452. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  34453. spherical.setFromVector3(offset);
  34454. if (scope.autoRotate && state === STATE.NONE) {
  34455. rotateLeft(getAutoRotationAngle());
  34456. }
  34457. if (scope.enableDamping) {
  34458. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  34459. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  34460. } else {
  34461. spherical.theta += sphericalDelta.theta;
  34462. spherical.phi += sphericalDelta.phi;
  34463. } // restrict theta to be between desired limits
  34464. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  34465. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  34466. spherical.makeSafe();
  34467. spherical.radius *= scale; // restrict radius to be between desired limits
  34468. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  34469. if (scope.enableDamping === true) {
  34470. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  34471. } else {
  34472. scope.target.add(panOffset);
  34473. }
  34474. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  34475. offset.applyQuaternion(quatInverse);
  34476. position.copy(scope.target).add(offset);
  34477. scope.object.lookAt(scope.target);
  34478. if (scope.enableDamping === true) {
  34479. sphericalDelta.theta *= 1 - scope.dampingFactor;
  34480. sphericalDelta.phi *= 1 - scope.dampingFactor;
  34481. panOffset.multiplyScalar(1 - scope.dampingFactor);
  34482. } else {
  34483. sphericalDelta.set(0, 0, 0);
  34484. panOffset.set(0, 0, 0);
  34485. }
  34486. scale = 1; // update condition is:
  34487. // min(camera displacement, camera rotation in radians)^2 > EPS
  34488. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  34489. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  34490. scope.dispatchEvent(changeEvent);
  34491. lastPosition.copy(scope.object.position);
  34492. lastQuaternion.copy(scope.object.quaternion);
  34493. zoomChanged = false;
  34494. return true;
  34495. }
  34496. return false;
  34497. };
  34498. }();
  34499. this.dispose = function () {
  34500. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  34501. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  34502. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  34503. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  34504. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  34505. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  34506. document.removeEventListener('mousemove', onMouseMove, false);
  34507. document.removeEventListener('mouseup', onMouseUp, false);
  34508. scope.domElement.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  34509. }; //
  34510. // internals
  34511. //
  34512. var scope = this;
  34513. var changeEvent = {
  34514. type: 'change'
  34515. };
  34516. var startEvent = {
  34517. type: 'start'
  34518. };
  34519. var endEvent = {
  34520. type: 'end'
  34521. };
  34522. var STATE = {
  34523. NONE: -1,
  34524. ROTATE: 0,
  34525. DOLLY: 1,
  34526. PAN: 2,
  34527. TOUCH_ROTATE: 3,
  34528. TOUCH_PAN: 4,
  34529. TOUCH_DOLLY_PAN: 5,
  34530. TOUCH_DOLLY_ROTATE: 6
  34531. };
  34532. var state = STATE.NONE;
  34533. var EPS = 0.000001; // current position in spherical coordinates
  34534. var spherical = new _threeModule.Spherical();
  34535. var sphericalDelta = new _threeModule.Spherical();
  34536. var scale = 1;
  34537. var panOffset = new _threeModule.Vector3();
  34538. var zoomChanged = false;
  34539. var rotateStart = new _threeModule.Vector2();
  34540. var rotateEnd = new _threeModule.Vector2();
  34541. var rotateDelta = new _threeModule.Vector2();
  34542. var panStart = new _threeModule.Vector2();
  34543. var panEnd = new _threeModule.Vector2();
  34544. var panDelta = new _threeModule.Vector2();
  34545. var dollyStart = new _threeModule.Vector2();
  34546. var dollyEnd = new _threeModule.Vector2();
  34547. var dollyDelta = new _threeModule.Vector2();
  34548. function getAutoRotationAngle() {
  34549. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  34550. }
  34551. function getZoomScale() {
  34552. return Math.pow(0.95, scope.zoomSpeed);
  34553. }
  34554. function rotateLeft(angle) {
  34555. sphericalDelta.theta -= angle;
  34556. }
  34557. function rotateUp(angle) {
  34558. sphericalDelta.phi -= angle;
  34559. }
  34560. var panLeft = function () {
  34561. var v = new _threeModule.Vector3();
  34562. return function panLeft(distance, objectMatrix) {
  34563. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  34564. v.multiplyScalar(-distance);
  34565. panOffset.add(v);
  34566. };
  34567. }();
  34568. var panUp = function () {
  34569. var v = new _threeModule.Vector3();
  34570. return function panUp(distance, objectMatrix) {
  34571. if (scope.screenSpacePanning === true) {
  34572. v.setFromMatrixColumn(objectMatrix, 1);
  34573. } else {
  34574. v.setFromMatrixColumn(objectMatrix, 0);
  34575. v.crossVectors(scope.object.up, v);
  34576. }
  34577. v.multiplyScalar(distance);
  34578. panOffset.add(v);
  34579. };
  34580. }(); // deltaX and deltaY are in pixels; right and down are positive
  34581. var pan = function () {
  34582. var offset = new _threeModule.Vector3();
  34583. return function pan(deltaX, deltaY) {
  34584. var element = scope.domElement;
  34585. if (scope.object.isPerspectiveCamera) {
  34586. // perspective
  34587. var position = scope.object.position;
  34588. offset.copy(position).sub(scope.target);
  34589. var targetDistance = offset.length(); // half of the fov is center to top of screen
  34590. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  34591. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  34592. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  34593. } else if (scope.object.isOrthographicCamera) {
  34594. // orthographic
  34595. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  34596. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  34597. } else {
  34598. // camera neither orthographic nor perspective
  34599. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  34600. scope.enablePan = false;
  34601. }
  34602. };
  34603. }();
  34604. function dollyOut(dollyScale) {
  34605. if (scope.object.isPerspectiveCamera) {
  34606. scale /= dollyScale;
  34607. } else if (scope.object.isOrthographicCamera) {
  34608. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  34609. scope.object.updateProjectionMatrix();
  34610. zoomChanged = true;
  34611. } else {
  34612. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  34613. scope.enableZoom = false;
  34614. }
  34615. }
  34616. function dollyIn(dollyScale) {
  34617. if (scope.object.isPerspectiveCamera) {
  34618. scale *= dollyScale;
  34619. } else if (scope.object.isOrthographicCamera) {
  34620. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  34621. scope.object.updateProjectionMatrix();
  34622. zoomChanged = true;
  34623. } else {
  34624. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  34625. scope.enableZoom = false;
  34626. }
  34627. } //
  34628. // event callbacks - update the object state
  34629. //
  34630. function handleMouseDownRotate(event) {
  34631. rotateStart.set(event.clientX, event.clientY);
  34632. }
  34633. function handleMouseDownDolly(event) {
  34634. dollyStart.set(event.clientX, event.clientY);
  34635. }
  34636. function handleMouseDownPan(event) {
  34637. panStart.set(event.clientX, event.clientY);
  34638. }
  34639. function handleMouseMoveRotate(event) {
  34640. rotateEnd.set(event.clientX, event.clientY);
  34641. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  34642. var element = scope.domElement;
  34643. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  34644. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  34645. rotateStart.copy(rotateEnd);
  34646. scope.update();
  34647. }
  34648. function handleMouseMoveDolly(event) {
  34649. dollyEnd.set(event.clientX, event.clientY);
  34650. dollyDelta.subVectors(dollyEnd, dollyStart);
  34651. if (dollyDelta.y > 0) {
  34652. dollyOut(getZoomScale());
  34653. } else if (dollyDelta.y < 0) {
  34654. dollyIn(getZoomScale());
  34655. }
  34656. dollyStart.copy(dollyEnd);
  34657. scope.update();
  34658. }
  34659. function handleMouseMovePan(event) {
  34660. panEnd.set(event.clientX, event.clientY);
  34661. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  34662. pan(panDelta.x, panDelta.y);
  34663. panStart.copy(panEnd);
  34664. scope.update();
  34665. }
  34666. function handleMouseUp()
  34667. /*event*/
  34668. {// no-op
  34669. }
  34670. function handleMouseWheel(event) {
  34671. if (event.deltaY < 0) {
  34672. dollyIn(getZoomScale());
  34673. } else if (event.deltaY > 0) {
  34674. dollyOut(getZoomScale());
  34675. }
  34676. scope.update();
  34677. }
  34678. function handleKeyDown(event) {
  34679. var needsUpdate = false;
  34680. switch (event.keyCode) {
  34681. case scope.keys.UP:
  34682. pan(0, scope.keyPanSpeed);
  34683. needsUpdate = true;
  34684. break;
  34685. case scope.keys.BOTTOM:
  34686. pan(0, -scope.keyPanSpeed);
  34687. needsUpdate = true;
  34688. break;
  34689. case scope.keys.LEFT:
  34690. pan(scope.keyPanSpeed, 0);
  34691. needsUpdate = true;
  34692. break;
  34693. case scope.keys.RIGHT:
  34694. pan(-scope.keyPanSpeed, 0);
  34695. needsUpdate = true;
  34696. break;
  34697. }
  34698. if (needsUpdate) {
  34699. // prevent the browser from scrolling on cursor keys
  34700. event.preventDefault();
  34701. scope.update();
  34702. }
  34703. }
  34704. function handleTouchStartRotate(event) {
  34705. if (event.touches.length == 1) {
  34706. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  34707. } else {
  34708. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  34709. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  34710. rotateStart.set(x, y);
  34711. }
  34712. }
  34713. function handleTouchStartPan(event) {
  34714. if (event.touches.length == 1) {
  34715. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  34716. } else {
  34717. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  34718. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  34719. panStart.set(x, y);
  34720. }
  34721. }
  34722. function handleTouchStartDolly(event) {
  34723. var dx = event.touches[0].pageX - event.touches[1].pageX;
  34724. var dy = event.touches[0].pageY - event.touches[1].pageY;
  34725. var distance = Math.sqrt(dx * dx + dy * dy);
  34726. dollyStart.set(0, distance);
  34727. }
  34728. function handleTouchStartDollyPan(event) {
  34729. if (scope.enableZoom) handleTouchStartDolly(event);
  34730. if (scope.enablePan) handleTouchStartPan(event);
  34731. }
  34732. function handleTouchStartDollyRotate(event) {
  34733. if (scope.enableZoom) handleTouchStartDolly(event);
  34734. if (scope.enableRotate) handleTouchStartRotate(event);
  34735. }
  34736. function handleTouchMoveRotate(event) {
  34737. if (event.touches.length == 1) {
  34738. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  34739. } else {
  34740. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  34741. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  34742. rotateEnd.set(x, y);
  34743. }
  34744. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  34745. var element = scope.domElement;
  34746. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  34747. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  34748. rotateStart.copy(rotateEnd);
  34749. }
  34750. function handleTouchMovePan(event) {
  34751. if (event.touches.length == 1) {
  34752. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  34753. } else {
  34754. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  34755. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  34756. panEnd.set(x, y);
  34757. }
  34758. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  34759. pan(panDelta.x, panDelta.y);
  34760. panStart.copy(panEnd);
  34761. }
  34762. function handleTouchMoveDolly(event) {
  34763. var dx = event.touches[0].pageX - event.touches[1].pageX;
  34764. var dy = event.touches[0].pageY - event.touches[1].pageY;
  34765. var distance = Math.sqrt(dx * dx + dy * dy);
  34766. dollyEnd.set(0, distance);
  34767. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  34768. dollyOut(dollyDelta.y);
  34769. dollyStart.copy(dollyEnd);
  34770. }
  34771. function handleTouchMoveDollyPan(event) {
  34772. if (scope.enableZoom) handleTouchMoveDolly(event);
  34773. if (scope.enablePan) handleTouchMovePan(event);
  34774. }
  34775. function handleTouchMoveDollyRotate(event) {
  34776. if (scope.enableZoom) handleTouchMoveDolly(event);
  34777. if (scope.enableRotate) handleTouchMoveRotate(event);
  34778. }
  34779. function handleTouchEnd()
  34780. /*event*/
  34781. {} // no-op
  34782. //
  34783. // event handlers - FSM: listen for events and reset state
  34784. //
  34785. function onMouseDown(event) {
  34786. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  34787. event.preventDefault(); // Manually set the focus since calling preventDefault above
  34788. // prevents the browser from setting it automatically.
  34789. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  34790. var mouseAction;
  34791. switch (event.button) {
  34792. case 0:
  34793. mouseAction = scope.mouseButtons.LEFT;
  34794. break;
  34795. case 1:
  34796. mouseAction = scope.mouseButtons.MIDDLE;
  34797. break;
  34798. case 2:
  34799. mouseAction = scope.mouseButtons.RIGHT;
  34800. break;
  34801. default:
  34802. mouseAction = -1;
  34803. }
  34804. switch (mouseAction) {
  34805. case _threeModule.MOUSE.DOLLY:
  34806. if (scope.enableZoom === false) return;
  34807. handleMouseDownDolly(event);
  34808. state = STATE.DOLLY;
  34809. break;
  34810. case _threeModule.MOUSE.ROTATE:
  34811. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  34812. if (scope.enablePan === false) return;
  34813. handleMouseDownPan(event);
  34814. state = STATE.PAN;
  34815. } else {
  34816. if (scope.enableRotate === false) return;
  34817. handleMouseDownRotate(event);
  34818. state = STATE.ROTATE;
  34819. }
  34820. break;
  34821. case _threeModule.MOUSE.PAN:
  34822. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  34823. if (scope.enableRotate === false) return;
  34824. handleMouseDownRotate(event);
  34825. state = STATE.ROTATE;
  34826. } else {
  34827. if (scope.enablePan === false) return;
  34828. handleMouseDownPan(event);
  34829. state = STATE.PAN;
  34830. }
  34831. break;
  34832. default:
  34833. state = STATE.NONE;
  34834. }
  34835. if (state !== STATE.NONE) {
  34836. document.addEventListener('mousemove', onMouseMove, false);
  34837. document.addEventListener('mouseup', onMouseUp, false);
  34838. scope.dispatchEvent(startEvent);
  34839. }
  34840. }
  34841. function onMouseMove(event) {
  34842. if (scope.enabled === false) return;
  34843. event.preventDefault();
  34844. switch (state) {
  34845. case STATE.ROTATE:
  34846. if (scope.enableRotate === false) return;
  34847. handleMouseMoveRotate(event);
  34848. break;
  34849. case STATE.DOLLY:
  34850. if (scope.enableZoom === false) return;
  34851. handleMouseMoveDolly(event);
  34852. break;
  34853. case STATE.PAN:
  34854. if (scope.enablePan === false) return;
  34855. handleMouseMovePan(event);
  34856. break;
  34857. }
  34858. }
  34859. function onMouseUp(event) {
  34860. if (scope.enabled === false) return;
  34861. handleMouseUp(event);
  34862. document.removeEventListener('mousemove', onMouseMove, false);
  34863. document.removeEventListener('mouseup', onMouseUp, false);
  34864. scope.dispatchEvent(endEvent);
  34865. state = STATE.NONE;
  34866. }
  34867. function onMouseWheel(event) {
  34868. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  34869. event.preventDefault();
  34870. event.stopPropagation();
  34871. scope.dispatchEvent(startEvent);
  34872. handleMouseWheel(event);
  34873. scope.dispatchEvent(endEvent);
  34874. }
  34875. function onKeyDown(event) {
  34876. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  34877. handleKeyDown(event);
  34878. }
  34879. function onTouchStart(event) {
  34880. if (scope.enabled === false) return;
  34881. event.preventDefault(); // prevent scrolling
  34882. switch (event.touches.length) {
  34883. case 1:
  34884. switch (scope.touches.ONE) {
  34885. case _threeModule.TOUCH.ROTATE:
  34886. if (scope.enableRotate === false) return;
  34887. handleTouchStartRotate(event);
  34888. state = STATE.TOUCH_ROTATE;
  34889. break;
  34890. case _threeModule.TOUCH.PAN:
  34891. if (scope.enablePan === false) return;
  34892. handleTouchStartPan(event);
  34893. state = STATE.TOUCH_PAN;
  34894. break;
  34895. default:
  34896. state = STATE.NONE;
  34897. }
  34898. break;
  34899. case 2:
  34900. switch (scope.touches.TWO) {
  34901. case _threeModule.TOUCH.DOLLY_PAN:
  34902. if (scope.enableZoom === false && scope.enablePan === false) return;
  34903. handleTouchStartDollyPan(event);
  34904. state = STATE.TOUCH_DOLLY_PAN;
  34905. break;
  34906. case _threeModule.TOUCH.DOLLY_ROTATE:
  34907. if (scope.enableZoom === false && scope.enableRotate === false) return;
  34908. handleTouchStartDollyRotate(event);
  34909. state = STATE.TOUCH_DOLLY_ROTATE;
  34910. break;
  34911. default:
  34912. state = STATE.NONE;
  34913. }
  34914. break;
  34915. default:
  34916. state = STATE.NONE;
  34917. }
  34918. if (state !== STATE.NONE) {
  34919. scope.dispatchEvent(startEvent);
  34920. }
  34921. }
  34922. function onTouchMove(event) {
  34923. if (scope.enabled === false) return;
  34924. event.preventDefault(); // prevent scrolling
  34925. event.stopPropagation();
  34926. switch (state) {
  34927. case STATE.TOUCH_ROTATE:
  34928. if (scope.enableRotate === false) return;
  34929. handleTouchMoveRotate(event);
  34930. scope.update();
  34931. break;
  34932. case STATE.TOUCH_PAN:
  34933. if (scope.enablePan === false) return;
  34934. handleTouchMovePan(event);
  34935. scope.update();
  34936. break;
  34937. case STATE.TOUCH_DOLLY_PAN:
  34938. if (scope.enableZoom === false && scope.enablePan === false) return;
  34939. handleTouchMoveDollyPan(event);
  34940. scope.update();
  34941. break;
  34942. case STATE.TOUCH_DOLLY_ROTATE:
  34943. if (scope.enableZoom === false && scope.enableRotate === false) return;
  34944. handleTouchMoveDollyRotate(event);
  34945. scope.update();
  34946. break;
  34947. default:
  34948. state = STATE.NONE;
  34949. }
  34950. }
  34951. function onTouchEnd(event) {
  34952. if (scope.enabled === false) return;
  34953. handleTouchEnd(event);
  34954. scope.dispatchEvent(endEvent);
  34955. state = STATE.NONE;
  34956. }
  34957. function onContextMenu(event) {
  34958. if (scope.enabled === false) return;
  34959. event.preventDefault();
  34960. } //
  34961. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  34962. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  34963. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  34964. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  34965. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  34966. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  34967. scope.domElement.addEventListener('keydown', onKeyDown, false); // make sure element can receive keys.
  34968. if (scope.domElement.tabIndex === -1) {
  34969. scope.domElement.tabIndex = 0;
  34970. } // force an update at start
  34971. this.update();
  34972. };
  34973. exports.OrbitControls = OrbitControls;
  34974. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  34975. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  34976. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  34977. // This is very similar to OrbitControls, another set of touch behavior
  34978. //
  34979. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  34980. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  34981. // Pan - left mouse, or arrow keys / touch: one-finger move
  34982. var MapControls = function (object, domElement) {
  34983. OrbitControls.call(this, object, domElement);
  34984. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  34985. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  34986. this.touches.ONE = _threeModule.TOUCH.PAN;
  34987. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  34988. };
  34989. exports.MapControls = MapControls;
  34990. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  34991. MapControls.prototype.constructor = MapControls;
  34992. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.js":[function(require,module,exports) {
  34993. "use strict";
  34994. Object.defineProperty(exports, "__esModule", {
  34995. value: true
  34996. });
  34997. exports.BufferGeometryUtils = void 0;
  34998. var _threeModule = require("../../../build/three.module.js");
  34999. /**
  35000. * @author mrdoob / http://mrdoob.com/
  35001. */
  35002. var BufferGeometryUtils = {
  35003. computeTangents: function (geometry) {
  35004. var index = geometry.index;
  35005. var attributes = geometry.attributes; // based on http://www.terathon.com/code/tangent.html
  35006. // (per vertex tangents)
  35007. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  35008. console.warn('THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()');
  35009. return;
  35010. }
  35011. var indices = index.array;
  35012. var positions = attributes.position.array;
  35013. var normals = attributes.normal.array;
  35014. var uvs = attributes.uv.array;
  35015. var nVertices = positions.length / 3;
  35016. if (attributes.tangent === undefined) {
  35017. geometry.setAttribute('tangent', new _threeModule.BufferAttribute(new Float32Array(4 * nVertices), 4));
  35018. }
  35019. var tangents = attributes.tangent.array;
  35020. var tan1 = [],
  35021. tan2 = [];
  35022. for (var i = 0; i < nVertices; i++) {
  35023. tan1[i] = new _threeModule.Vector3();
  35024. tan2[i] = new _threeModule.Vector3();
  35025. }
  35026. var vA = new _threeModule.Vector3(),
  35027. vB = new _threeModule.Vector3(),
  35028. vC = new _threeModule.Vector3(),
  35029. uvA = new _threeModule.Vector2(),
  35030. uvB = new _threeModule.Vector2(),
  35031. uvC = new _threeModule.Vector2(),
  35032. sdir = new _threeModule.Vector3(),
  35033. tdir = new _threeModule.Vector3();
  35034. function handleTriangle(a, b, c) {
  35035. vA.fromArray(positions, a * 3);
  35036. vB.fromArray(positions, b * 3);
  35037. vC.fromArray(positions, c * 3);
  35038. uvA.fromArray(uvs, a * 2);
  35039. uvB.fromArray(uvs, b * 2);
  35040. uvC.fromArray(uvs, c * 2);
  35041. vB.sub(vA);
  35042. vC.sub(vA);
  35043. uvB.sub(uvA);
  35044. uvC.sub(uvA);
  35045. var r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  35046. if (!isFinite(r)) return;
  35047. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  35048. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  35049. tan1[a].add(sdir);
  35050. tan1[b].add(sdir);
  35051. tan1[c].add(sdir);
  35052. tan2[a].add(tdir);
  35053. tan2[b].add(tdir);
  35054. tan2[c].add(tdir);
  35055. }
  35056. var groups = geometry.groups;
  35057. if (groups.length === 0) {
  35058. groups = [{
  35059. start: 0,
  35060. count: indices.length
  35061. }];
  35062. }
  35063. for (var i = 0, il = groups.length; i < il; ++i) {
  35064. var group = groups[i];
  35065. var start = group.start;
  35066. var count = group.count;
  35067. for (var j = start, jl = start + count; j < jl; j += 3) {
  35068. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  35069. }
  35070. }
  35071. var tmp = new _threeModule.Vector3(),
  35072. tmp2 = new _threeModule.Vector3();
  35073. var n = new _threeModule.Vector3(),
  35074. n2 = new _threeModule.Vector3();
  35075. var w, t, test;
  35076. function handleVertex(v) {
  35077. n.fromArray(normals, v * 3);
  35078. n2.copy(n);
  35079. t = tan1[v]; // Gram-Schmidt orthogonalize
  35080. tmp.copy(t);
  35081. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  35082. tmp2.crossVectors(n2, t);
  35083. test = tmp2.dot(tan2[v]);
  35084. w = test < 0.0 ? -1.0 : 1.0;
  35085. tangents[v * 4] = tmp.x;
  35086. tangents[v * 4 + 1] = tmp.y;
  35087. tangents[v * 4 + 2] = tmp.z;
  35088. tangents[v * 4 + 3] = w;
  35089. }
  35090. for (var i = 0, il = groups.length; i < il; ++i) {
  35091. var group = groups[i];
  35092. var start = group.start;
  35093. var count = group.count;
  35094. for (var j = start, jl = start + count; j < jl; j += 3) {
  35095. handleVertex(indices[j + 0]);
  35096. handleVertex(indices[j + 1]);
  35097. handleVertex(indices[j + 2]);
  35098. }
  35099. }
  35100. },
  35101. /**
  35102. * @param {Array<BufferGeometry>} geometries
  35103. * @param {Boolean} useGroups
  35104. * @return {BufferGeometry}
  35105. */
  35106. mergeBufferGeometries: function (geometries, useGroups) {
  35107. var isIndexed = geometries[0].index !== null;
  35108. var attributesUsed = new Set(Object.keys(geometries[0].attributes));
  35109. var morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes));
  35110. var attributes = {};
  35111. var morphAttributes = {};
  35112. var morphTargetsRelative = geometries[0].morphTargetsRelative;
  35113. var mergedGeometry = new _threeModule.BufferGeometry();
  35114. var offset = 0;
  35115. for (var i = 0; i < geometries.length; ++i) {
  35116. var geometry = geometries[i]; // ensure that all geometries are indexed, or none
  35117. if (isIndexed !== (geometry.index !== null)) return null; // gather attributes, exit early if they're different
  35118. for (var name in geometry.attributes) {
  35119. if (!attributesUsed.has(name)) return null;
  35120. if (attributes[name] === undefined) attributes[name] = [];
  35121. attributes[name].push(geometry.attributes[name]);
  35122. } // gather morph attributes, exit early if they're different
  35123. if (morphTargetsRelative !== geometry.morphTargetsRelative) return null;
  35124. for (var name in geometry.morphAttributes) {
  35125. if (!morphAttributesUsed.has(name)) return null;
  35126. if (morphAttributes[name] === undefined) morphAttributes[name] = [];
  35127. morphAttributes[name].push(geometry.morphAttributes[name]);
  35128. } // gather .userData
  35129. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  35130. mergedGeometry.userData.mergedUserData.push(geometry.userData);
  35131. if (useGroups) {
  35132. var count;
  35133. if (isIndexed) {
  35134. count = geometry.index.count;
  35135. } else if (geometry.attributes.position !== undefined) {
  35136. count = geometry.attributes.position.count;
  35137. } else {
  35138. return null;
  35139. }
  35140. mergedGeometry.addGroup(offset, count, i);
  35141. offset += count;
  35142. }
  35143. } // merge indices
  35144. if (isIndexed) {
  35145. var indexOffset = 0;
  35146. var mergedIndex = [];
  35147. for (var i = 0; i < geometries.length; ++i) {
  35148. var index = geometries[i].index;
  35149. for (var j = 0; j < index.count; ++j) {
  35150. mergedIndex.push(index.getX(j) + indexOffset);
  35151. }
  35152. indexOffset += geometries[i].attributes.position.count;
  35153. }
  35154. mergedGeometry.setIndex(mergedIndex);
  35155. } // merge attributes
  35156. for (var name in attributes) {
  35157. var mergedAttribute = this.mergeBufferAttributes(attributes[name]);
  35158. if (!mergedAttribute) return null;
  35159. mergedGeometry.setAttribute(name, mergedAttribute);
  35160. } // merge morph attributes
  35161. for (var name in morphAttributes) {
  35162. var numMorphTargets = morphAttributes[name][0].length;
  35163. if (numMorphTargets === 0) break;
  35164. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  35165. mergedGeometry.morphAttributes[name] = [];
  35166. for (var i = 0; i < numMorphTargets; ++i) {
  35167. var morphAttributesToMerge = [];
  35168. for (var j = 0; j < morphAttributes[name].length; ++j) {
  35169. morphAttributesToMerge.push(morphAttributes[name][j][i]);
  35170. }
  35171. var mergedMorphAttribute = this.mergeBufferAttributes(morphAttributesToMerge);
  35172. if (!mergedMorphAttribute) return null;
  35173. mergedGeometry.morphAttributes[name].push(mergedMorphAttribute);
  35174. }
  35175. }
  35176. return mergedGeometry;
  35177. },
  35178. /**
  35179. * @param {Array<BufferAttribute>} attributes
  35180. * @return {BufferAttribute}
  35181. */
  35182. mergeBufferAttributes: function (attributes) {
  35183. var TypedArray;
  35184. var itemSize;
  35185. var normalized;
  35186. var arrayLength = 0;
  35187. for (var i = 0; i < attributes.length; ++i) {
  35188. var attribute = attributes[i];
  35189. if (attribute.isInterleavedBufferAttribute) return null;
  35190. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  35191. if (TypedArray !== attribute.array.constructor) return null;
  35192. if (itemSize === undefined) itemSize = attribute.itemSize;
  35193. if (itemSize !== attribute.itemSize) return null;
  35194. if (normalized === undefined) normalized = attribute.normalized;
  35195. if (normalized !== attribute.normalized) return null;
  35196. arrayLength += attribute.array.length;
  35197. }
  35198. var array = new TypedArray(arrayLength);
  35199. var offset = 0;
  35200. for (var i = 0; i < attributes.length; ++i) {
  35201. array.set(attributes[i].array, offset);
  35202. offset += attributes[i].array.length;
  35203. }
  35204. return new _threeModule.BufferAttribute(array, itemSize, normalized);
  35205. },
  35206. /**
  35207. * @param {Array<BufferAttribute>} attributes
  35208. * @return {Array<InterleavedBufferAttribute>}
  35209. */
  35210. interleaveAttributes: function (attributes) {
  35211. // Interleaves the provided attributes into an InterleavedBuffer and returns
  35212. // a set of InterleavedBufferAttributes for each attribute
  35213. var TypedArray;
  35214. var arrayLength = 0;
  35215. var stride = 0; // calculate the the length and type of the interleavedBuffer
  35216. for (var i = 0, l = attributes.length; i < l; ++i) {
  35217. var attribute = attributes[i];
  35218. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  35219. if (TypedArray !== attribute.array.constructor) {
  35220. console.warn('AttributeBuffers of different types cannot be interleaved');
  35221. return null;
  35222. }
  35223. arrayLength += attribute.array.length;
  35224. stride += attribute.itemSize;
  35225. } // Create the set of buffer attributes
  35226. var interleavedBuffer = new _threeModule.InterleavedBuffer(new TypedArray(arrayLength), stride);
  35227. var offset = 0;
  35228. var res = [];
  35229. var getters = ['getX', 'getY', 'getZ', 'getW'];
  35230. var setters = ['setX', 'setY', 'setZ', 'setW'];
  35231. for (var j = 0, l = attributes.length; j < l; j++) {
  35232. var attribute = attributes[j];
  35233. var itemSize = attribute.itemSize;
  35234. var count = attribute.count;
  35235. var iba = new _threeModule.InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, attribute.normalized);
  35236. res.push(iba);
  35237. offset += itemSize; // Move the data for each attribute into the new interleavedBuffer
  35238. // at the appropriate offset
  35239. for (var c = 0; c < count; c++) {
  35240. for (var k = 0; k < itemSize; k++) {
  35241. iba[setters[k]](c, attribute[getters[k]](c));
  35242. }
  35243. }
  35244. }
  35245. return res;
  35246. },
  35247. /**
  35248. * @param {Array<BufferGeometry>} geometry
  35249. * @return {number}
  35250. */
  35251. estimateBytesUsed: function (geometry) {
  35252. // Return the estimated memory used by this geometry in bytes
  35253. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  35254. // for InterleavedBufferAttributes.
  35255. var mem = 0;
  35256. for (var name in geometry.attributes) {
  35257. var attr = geometry.getAttribute(name);
  35258. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  35259. }
  35260. var indices = geometry.getIndex();
  35261. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  35262. return mem;
  35263. },
  35264. /**
  35265. * @param {BufferGeometry} geometry
  35266. * @param {number} tolerance
  35267. * @return {BufferGeometry>}
  35268. */
  35269. mergeVertices: function (geometry, tolerance = 1e-4) {
  35270. tolerance = Math.max(tolerance, Number.EPSILON); // Generate an index buffer if the geometry doesn't have one, or optimize it
  35271. // if it's already available.
  35272. var hashToIndex = {};
  35273. var indices = geometry.getIndex();
  35274. var positions = geometry.getAttribute('position');
  35275. var vertexCount = indices ? indices.count : positions.count; // next value for triangle indices
  35276. var nextIndex = 0; // attributes and new attribute arrays
  35277. var attributeNames = Object.keys(geometry.attributes);
  35278. var attrArrays = {};
  35279. var morphAttrsArrays = {};
  35280. var newIndices = [];
  35281. var getters = ['getX', 'getY', 'getZ', 'getW']; // initialize the arrays
  35282. for (var i = 0, l = attributeNames.length; i < l; i++) {
  35283. var name = attributeNames[i];
  35284. attrArrays[name] = [];
  35285. var morphAttr = geometry.morphAttributes[name];
  35286. if (morphAttr) {
  35287. morphAttrsArrays[name] = new Array(morphAttr.length).fill().map(() => []);
  35288. }
  35289. } // convert the error tolerance to an amount of decimal places to truncate to
  35290. var decimalShift = Math.log10(1 / tolerance);
  35291. var shiftMultiplier = Math.pow(10, decimalShift);
  35292. for (var i = 0; i < vertexCount; i++) {
  35293. var index = indices ? indices.getX(i) : i; // Generate a hash for the vertex attributes at the current index 'i'
  35294. var hash = '';
  35295. for (var j = 0, l = attributeNames.length; j < l; j++) {
  35296. var name = attributeNames[j];
  35297. var attribute = geometry.getAttribute(name);
  35298. var itemSize = attribute.itemSize;
  35299. for (var k = 0; k < itemSize; k++) {
  35300. // double tilde truncates the decimal value
  35301. hash += `${~~(attribute[getters[k]](index) * shiftMultiplier)},`;
  35302. }
  35303. } // Add another reference to the vertex if it's already
  35304. // used by another index
  35305. if (hash in hashToIndex) {
  35306. newIndices.push(hashToIndex[hash]);
  35307. } else {
  35308. // copy data to the new index in the attribute arrays
  35309. for (var j = 0, l = attributeNames.length; j < l; j++) {
  35310. var name = attributeNames[j];
  35311. var attribute = geometry.getAttribute(name);
  35312. var morphAttr = geometry.morphAttributes[name];
  35313. var itemSize = attribute.itemSize;
  35314. var newarray = attrArrays[name];
  35315. var newMorphArrays = morphAttrsArrays[name];
  35316. for (var k = 0; k < itemSize; k++) {
  35317. var getterFunc = getters[k];
  35318. newarray.push(attribute[getterFunc](index));
  35319. if (morphAttr) {
  35320. for (var m = 0, ml = morphAttr.length; m < ml; m++) {
  35321. newMorphArrays[m].push(morphAttr[m][getterFunc](index));
  35322. }
  35323. }
  35324. }
  35325. }
  35326. hashToIndex[hash] = nextIndex;
  35327. newIndices.push(nextIndex);
  35328. nextIndex++;
  35329. }
  35330. } // Generate typed arrays from new attribute arrays and update
  35331. // the attributeBuffers
  35332. const result = geometry.clone();
  35333. for (var i = 0, l = attributeNames.length; i < l; i++) {
  35334. var name = attributeNames[i];
  35335. var oldAttribute = geometry.getAttribute(name);
  35336. var buffer = new oldAttribute.array.constructor(attrArrays[name]);
  35337. var attribute = new _threeModule.BufferAttribute(buffer, oldAttribute.itemSize, oldAttribute.normalized);
  35338. result.setAttribute(name, attribute); // Update the attribute arrays
  35339. if (name in morphAttrsArrays) {
  35340. for (var j = 0; j < morphAttrsArrays[name].length; j++) {
  35341. var oldMorphAttribute = geometry.morphAttributes[name][j];
  35342. var buffer = new oldMorphAttribute.array.constructor(morphAttrsArrays[name][j]);
  35343. var morphAttribute = new _threeModule.BufferAttribute(buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized);
  35344. result.morphAttributes[name][j] = morphAttribute;
  35345. }
  35346. }
  35347. } // indices
  35348. result.setIndex(newIndices);
  35349. return result;
  35350. },
  35351. /**
  35352. * @param {BufferGeometry} geometry
  35353. * @param {number} drawMode
  35354. * @return {BufferGeometry>}
  35355. */
  35356. toTrianglesDrawMode: function (geometry, drawMode) {
  35357. if (drawMode === _threeModule.TrianglesDrawMode) {
  35358. console.warn('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.');
  35359. return geometry;
  35360. }
  35361. if (drawMode === _threeModule.TriangleFanDrawMode || drawMode === _threeModule.TriangleStripDrawMode) {
  35362. var index = geometry.getIndex(); // generate index if not present
  35363. if (index === null) {
  35364. var indices = [];
  35365. var position = geometry.getAttribute('position');
  35366. if (position !== undefined) {
  35367. for (var i = 0; i < position.count; i++) {
  35368. indices.push(i);
  35369. }
  35370. geometry.setIndex(indices);
  35371. index = geometry.getIndex();
  35372. } else {
  35373. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  35374. return geometry;
  35375. }
  35376. } //
  35377. var numberOfTriangles = index.count - 2;
  35378. var newIndices = [];
  35379. if (drawMode === _threeModule.TriangleFanDrawMode) {
  35380. // gl.TRIANGLE_FAN
  35381. for (var i = 1; i <= numberOfTriangles; i++) {
  35382. newIndices.push(index.getX(0));
  35383. newIndices.push(index.getX(i));
  35384. newIndices.push(index.getX(i + 1));
  35385. }
  35386. } else {
  35387. // gl.TRIANGLE_STRIP
  35388. for (var i = 0; i < numberOfTriangles; i++) {
  35389. if (i % 2 === 0) {
  35390. newIndices.push(index.getX(i));
  35391. newIndices.push(index.getX(i + 1));
  35392. newIndices.push(index.getX(i + 2));
  35393. } else {
  35394. newIndices.push(index.getX(i + 2));
  35395. newIndices.push(index.getX(i + 1));
  35396. newIndices.push(index.getX(i));
  35397. }
  35398. }
  35399. }
  35400. if (newIndices.length / 3 !== numberOfTriangles) {
  35401. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  35402. } // build final geometry
  35403. var newGeometry = geometry.clone();
  35404. newGeometry.setIndex(newIndices);
  35405. newGeometry.clearGroups();
  35406. return newGeometry;
  35407. } else {
  35408. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode);
  35409. return geometry;
  35410. }
  35411. }
  35412. };
  35413. exports.BufferGeometryUtils = BufferGeometryUtils;
  35414. },{"../../../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) {
  35415. "use strict";
  35416. Object.defineProperty(exports, "__esModule", {
  35417. value: true
  35418. });
  35419. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  35420. /**
  35421. * dat-gui JavaScript Controller Library
  35422. * http://code.google.com/p/dat-gui
  35423. *
  35424. * Copyright 2011 Data Arts Team, Google Creative Lab
  35425. *
  35426. * Licensed under the Apache License, Version 2.0 (the "License");
  35427. * you may not use this file except in compliance with the License.
  35428. * You may obtain a copy of the License at
  35429. *
  35430. * http://www.apache.org/licenses/LICENSE-2.0
  35431. */
  35432. function ___$insertStyle(css) {
  35433. if (!css) {
  35434. return;
  35435. }
  35436. if (typeof window === 'undefined') {
  35437. return;
  35438. }
  35439. var style = document.createElement('style');
  35440. style.setAttribute('type', 'text/css');
  35441. style.innerHTML = css;
  35442. document.head.appendChild(style);
  35443. return css;
  35444. }
  35445. function colorToString(color, forceCSSHex) {
  35446. var colorFormat = color.__state.conversionName.toString();
  35447. var r = Math.round(color.r);
  35448. var g = Math.round(color.g);
  35449. var b = Math.round(color.b);
  35450. var a = color.a;
  35451. var h = Math.round(color.h);
  35452. var s = color.s.toFixed(1);
  35453. var v = color.v.toFixed(1);
  35454. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  35455. var str = color.hex.toString(16);
  35456. while (str.length < 6) {
  35457. str = '0' + str;
  35458. }
  35459. return '#' + str;
  35460. } else if (colorFormat === 'CSS_RGB') {
  35461. return 'rgb(' + r + ',' + g + ',' + b + ')';
  35462. } else if (colorFormat === 'CSS_RGBA') {
  35463. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  35464. } else if (colorFormat === 'HEX') {
  35465. return '0x' + color.hex.toString(16);
  35466. } else if (colorFormat === 'RGB_ARRAY') {
  35467. return '[' + r + ',' + g + ',' + b + ']';
  35468. } else if (colorFormat === 'RGBA_ARRAY') {
  35469. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  35470. } else if (colorFormat === 'RGB_OBJ') {
  35471. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  35472. } else if (colorFormat === 'RGBA_OBJ') {
  35473. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  35474. } else if (colorFormat === 'HSV_OBJ') {
  35475. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  35476. } else if (colorFormat === 'HSVA_OBJ') {
  35477. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  35478. }
  35479. return 'unknown format';
  35480. }
  35481. var ARR_EACH = Array.prototype.forEach;
  35482. var ARR_SLICE = Array.prototype.slice;
  35483. var Common = {
  35484. BREAK: {},
  35485. extend: function extend(target) {
  35486. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  35487. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  35488. keys.forEach(function (key) {
  35489. if (!this.isUndefined(obj[key])) {
  35490. target[key] = obj[key];
  35491. }
  35492. }.bind(this));
  35493. }, this);
  35494. return target;
  35495. },
  35496. defaults: function defaults(target) {
  35497. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  35498. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  35499. keys.forEach(function (key) {
  35500. if (this.isUndefined(target[key])) {
  35501. target[key] = obj[key];
  35502. }
  35503. }.bind(this));
  35504. }, this);
  35505. return target;
  35506. },
  35507. compose: function compose() {
  35508. var toCall = ARR_SLICE.call(arguments);
  35509. return function () {
  35510. var args = ARR_SLICE.call(arguments);
  35511. for (var i = toCall.length - 1; i >= 0; i--) {
  35512. args = [toCall[i].apply(this, args)];
  35513. }
  35514. return args[0];
  35515. };
  35516. },
  35517. each: function each(obj, itr, scope) {
  35518. if (!obj) {
  35519. return;
  35520. }
  35521. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  35522. obj.forEach(itr, scope);
  35523. } else if (obj.length === obj.length + 0) {
  35524. var key = void 0;
  35525. var l = void 0;
  35526. for (key = 0, l = obj.length; key < l; key++) {
  35527. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  35528. return;
  35529. }
  35530. }
  35531. } else {
  35532. for (var _key in obj) {
  35533. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  35534. return;
  35535. }
  35536. }
  35537. }
  35538. },
  35539. defer: function defer(fnc) {
  35540. setTimeout(fnc, 0);
  35541. },
  35542. debounce: function debounce(func, threshold, callImmediately) {
  35543. var timeout = void 0;
  35544. return function () {
  35545. var obj = this;
  35546. var args = arguments;
  35547. function delayed() {
  35548. timeout = null;
  35549. if (!callImmediately) func.apply(obj, args);
  35550. }
  35551. var callNow = callImmediately || !timeout;
  35552. clearTimeout(timeout);
  35553. timeout = setTimeout(delayed, threshold);
  35554. if (callNow) {
  35555. func.apply(obj, args);
  35556. }
  35557. };
  35558. },
  35559. toArray: function toArray(obj) {
  35560. if (obj.toArray) return obj.toArray();
  35561. return ARR_SLICE.call(obj);
  35562. },
  35563. isUndefined: function isUndefined(obj) {
  35564. return obj === undefined;
  35565. },
  35566. isNull: function isNull(obj) {
  35567. return obj === null;
  35568. },
  35569. isNaN: function (_isNaN) {
  35570. function isNaN() {
  35571. return _isNaN.apply(this, arguments);
  35572. }
  35573. isNaN.toString = function () {
  35574. return _isNaN.toString();
  35575. };
  35576. return isNaN;
  35577. }(function (obj) {
  35578. return isNaN(obj);
  35579. }),
  35580. isArray: Array.isArray || function (obj) {
  35581. return obj.constructor === Array;
  35582. },
  35583. isObject: function isObject(obj) {
  35584. return obj === Object(obj);
  35585. },
  35586. isNumber: function isNumber(obj) {
  35587. return obj === obj + 0;
  35588. },
  35589. isString: function isString(obj) {
  35590. return obj === obj + '';
  35591. },
  35592. isBoolean: function isBoolean(obj) {
  35593. return obj === false || obj === true;
  35594. },
  35595. isFunction: function isFunction(obj) {
  35596. return Object.prototype.toString.call(obj) === '[object Function]';
  35597. }
  35598. };
  35599. var INTERPRETATIONS = [{
  35600. litmus: Common.isString,
  35601. conversions: {
  35602. THREE_CHAR_HEX: {
  35603. read: function read(original) {
  35604. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  35605. if (test === null) {
  35606. return false;
  35607. }
  35608. return {
  35609. space: 'HEX',
  35610. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  35611. };
  35612. },
  35613. write: colorToString
  35614. },
  35615. SIX_CHAR_HEX: {
  35616. read: function read(original) {
  35617. var test = original.match(/^#([A-F0-9]{6})$/i);
  35618. if (test === null) {
  35619. return false;
  35620. }
  35621. return {
  35622. space: 'HEX',
  35623. hex: parseInt('0x' + test[1].toString(), 0)
  35624. };
  35625. },
  35626. write: colorToString
  35627. },
  35628. CSS_RGB: {
  35629. read: function read(original) {
  35630. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  35631. if (test === null) {
  35632. return false;
  35633. }
  35634. return {
  35635. space: 'RGB',
  35636. r: parseFloat(test[1]),
  35637. g: parseFloat(test[2]),
  35638. b: parseFloat(test[3])
  35639. };
  35640. },
  35641. write: colorToString
  35642. },
  35643. CSS_RGBA: {
  35644. read: function read(original) {
  35645. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  35646. if (test === null) {
  35647. return false;
  35648. }
  35649. return {
  35650. space: 'RGB',
  35651. r: parseFloat(test[1]),
  35652. g: parseFloat(test[2]),
  35653. b: parseFloat(test[3]),
  35654. a: parseFloat(test[4])
  35655. };
  35656. },
  35657. write: colorToString
  35658. }
  35659. }
  35660. }, {
  35661. litmus: Common.isNumber,
  35662. conversions: {
  35663. HEX: {
  35664. read: function read(original) {
  35665. return {
  35666. space: 'HEX',
  35667. hex: original,
  35668. conversionName: 'HEX'
  35669. };
  35670. },
  35671. write: function write(color) {
  35672. return color.hex;
  35673. }
  35674. }
  35675. }
  35676. }, {
  35677. litmus: Common.isArray,
  35678. conversions: {
  35679. RGB_ARRAY: {
  35680. read: function read(original) {
  35681. if (original.length !== 3) {
  35682. return false;
  35683. }
  35684. return {
  35685. space: 'RGB',
  35686. r: original[0],
  35687. g: original[1],
  35688. b: original[2]
  35689. };
  35690. },
  35691. write: function write(color) {
  35692. return [color.r, color.g, color.b];
  35693. }
  35694. },
  35695. RGBA_ARRAY: {
  35696. read: function read(original) {
  35697. if (original.length !== 4) return false;
  35698. return {
  35699. space: 'RGB',
  35700. r: original[0],
  35701. g: original[1],
  35702. b: original[2],
  35703. a: original[3]
  35704. };
  35705. },
  35706. write: function write(color) {
  35707. return [color.r, color.g, color.b, color.a];
  35708. }
  35709. }
  35710. }
  35711. }, {
  35712. litmus: Common.isObject,
  35713. conversions: {
  35714. RGBA_OBJ: {
  35715. read: function read(original) {
  35716. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  35717. return {
  35718. space: 'RGB',
  35719. r: original.r,
  35720. g: original.g,
  35721. b: original.b,
  35722. a: original.a
  35723. };
  35724. }
  35725. return false;
  35726. },
  35727. write: function write(color) {
  35728. return {
  35729. r: color.r,
  35730. g: color.g,
  35731. b: color.b,
  35732. a: color.a
  35733. };
  35734. }
  35735. },
  35736. RGB_OBJ: {
  35737. read: function read(original) {
  35738. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  35739. return {
  35740. space: 'RGB',
  35741. r: original.r,
  35742. g: original.g,
  35743. b: original.b
  35744. };
  35745. }
  35746. return false;
  35747. },
  35748. write: function write(color) {
  35749. return {
  35750. r: color.r,
  35751. g: color.g,
  35752. b: color.b
  35753. };
  35754. }
  35755. },
  35756. HSVA_OBJ: {
  35757. read: function read(original) {
  35758. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  35759. return {
  35760. space: 'HSV',
  35761. h: original.h,
  35762. s: original.s,
  35763. v: original.v,
  35764. a: original.a
  35765. };
  35766. }
  35767. return false;
  35768. },
  35769. write: function write(color) {
  35770. return {
  35771. h: color.h,
  35772. s: color.s,
  35773. v: color.v,
  35774. a: color.a
  35775. };
  35776. }
  35777. },
  35778. HSV_OBJ: {
  35779. read: function read(original) {
  35780. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  35781. return {
  35782. space: 'HSV',
  35783. h: original.h,
  35784. s: original.s,
  35785. v: original.v
  35786. };
  35787. }
  35788. return false;
  35789. },
  35790. write: function write(color) {
  35791. return {
  35792. h: color.h,
  35793. s: color.s,
  35794. v: color.v
  35795. };
  35796. }
  35797. }
  35798. }
  35799. }];
  35800. var result = void 0;
  35801. var toReturn = void 0;
  35802. var interpret = function interpret() {
  35803. toReturn = false;
  35804. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  35805. Common.each(INTERPRETATIONS, function (family) {
  35806. if (family.litmus(original)) {
  35807. Common.each(family.conversions, function (conversion, conversionName) {
  35808. result = conversion.read(original);
  35809. if (toReturn === false && result !== false) {
  35810. toReturn = result;
  35811. result.conversionName = conversionName;
  35812. result.conversion = conversion;
  35813. return Common.BREAK;
  35814. }
  35815. });
  35816. return Common.BREAK;
  35817. }
  35818. });
  35819. return toReturn;
  35820. };
  35821. var tmpComponent = void 0;
  35822. var ColorMath = {
  35823. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  35824. var hi = Math.floor(h / 60) % 6;
  35825. var f = h / 60 - Math.floor(h / 60);
  35826. var p = v * (1.0 - s);
  35827. var q = v * (1.0 - f * s);
  35828. var t = v * (1.0 - (1.0 - f) * s);
  35829. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  35830. return {
  35831. r: c[0] * 255,
  35832. g: c[1] * 255,
  35833. b: c[2] * 255
  35834. };
  35835. },
  35836. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  35837. var min = Math.min(r, g, b);
  35838. var max = Math.max(r, g, b);
  35839. var delta = max - min;
  35840. var h = void 0;
  35841. var s = void 0;
  35842. if (max !== 0) {
  35843. s = delta / max;
  35844. } else {
  35845. return {
  35846. h: NaN,
  35847. s: 0,
  35848. v: 0
  35849. };
  35850. }
  35851. if (r === max) {
  35852. h = (g - b) / delta;
  35853. } else if (g === max) {
  35854. h = 2 + (b - r) / delta;
  35855. } else {
  35856. h = 4 + (r - g) / delta;
  35857. }
  35858. h /= 6;
  35859. if (h < 0) {
  35860. h += 1;
  35861. }
  35862. return {
  35863. h: h * 360,
  35864. s: s,
  35865. v: max / 255
  35866. };
  35867. },
  35868. rgb_to_hex: function rgb_to_hex(r, g, b) {
  35869. var hex = this.hex_with_component(0, 2, r);
  35870. hex = this.hex_with_component(hex, 1, g);
  35871. hex = this.hex_with_component(hex, 0, b);
  35872. return hex;
  35873. },
  35874. component_from_hex: function component_from_hex(hex, componentIndex) {
  35875. return hex >> componentIndex * 8 & 0xFF;
  35876. },
  35877. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  35878. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  35879. }
  35880. };
  35881. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  35882. return typeof obj;
  35883. } : function (obj) {
  35884. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  35885. };
  35886. var classCallCheck = function (instance, Constructor) {
  35887. if (!(instance instanceof Constructor)) {
  35888. throw new TypeError("Cannot call a class as a function");
  35889. }
  35890. };
  35891. var createClass = function () {
  35892. function defineProperties(target, props) {
  35893. for (var i = 0; i < props.length; i++) {
  35894. var descriptor = props[i];
  35895. descriptor.enumerable = descriptor.enumerable || false;
  35896. descriptor.configurable = true;
  35897. if ("value" in descriptor) descriptor.writable = true;
  35898. Object.defineProperty(target, descriptor.key, descriptor);
  35899. }
  35900. }
  35901. return function (Constructor, protoProps, staticProps) {
  35902. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  35903. if (staticProps) defineProperties(Constructor, staticProps);
  35904. return Constructor;
  35905. };
  35906. }();
  35907. var get = function get(object, property, receiver) {
  35908. if (object === null) object = Function.prototype;
  35909. var desc = Object.getOwnPropertyDescriptor(object, property);
  35910. if (desc === undefined) {
  35911. var parent = Object.getPrototypeOf(object);
  35912. if (parent === null) {
  35913. return undefined;
  35914. } else {
  35915. return get(parent, property, receiver);
  35916. }
  35917. } else if ("value" in desc) {
  35918. return desc.value;
  35919. } else {
  35920. var getter = desc.get;
  35921. if (getter === undefined) {
  35922. return undefined;
  35923. }
  35924. return getter.call(receiver);
  35925. }
  35926. };
  35927. var inherits = function (subClass, superClass) {
  35928. if (typeof superClass !== "function" && superClass !== null) {
  35929. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  35930. }
  35931. subClass.prototype = Object.create(superClass && superClass.prototype, {
  35932. constructor: {
  35933. value: subClass,
  35934. enumerable: false,
  35935. writable: true,
  35936. configurable: true
  35937. }
  35938. });
  35939. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  35940. };
  35941. var possibleConstructorReturn = function (self, call) {
  35942. if (!self) {
  35943. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  35944. }
  35945. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  35946. };
  35947. var Color = function () {
  35948. function Color() {
  35949. classCallCheck(this, Color);
  35950. this.__state = interpret.apply(this, arguments);
  35951. if (this.__state === false) {
  35952. throw new Error('Failed to interpret color arguments');
  35953. }
  35954. this.__state.a = this.__state.a || 1;
  35955. }
  35956. createClass(Color, [{
  35957. key: 'toString',
  35958. value: function toString() {
  35959. return colorToString(this);
  35960. }
  35961. }, {
  35962. key: 'toHexString',
  35963. value: function toHexString() {
  35964. return colorToString(this, true);
  35965. }
  35966. }, {
  35967. key: 'toOriginal',
  35968. value: function toOriginal() {
  35969. return this.__state.conversion.write(this);
  35970. }
  35971. }]);
  35972. return Color;
  35973. }();
  35974. function defineRGBComponent(target, component, componentHexIndex) {
  35975. Object.defineProperty(target, component, {
  35976. get: function get$$1() {
  35977. if (this.__state.space === 'RGB') {
  35978. return this.__state[component];
  35979. }
  35980. Color.recalculateRGB(this, component, componentHexIndex);
  35981. return this.__state[component];
  35982. },
  35983. set: function set$$1(v) {
  35984. if (this.__state.space !== 'RGB') {
  35985. Color.recalculateRGB(this, component, componentHexIndex);
  35986. this.__state.space = 'RGB';
  35987. }
  35988. this.__state[component] = v;
  35989. }
  35990. });
  35991. }
  35992. function defineHSVComponent(target, component) {
  35993. Object.defineProperty(target, component, {
  35994. get: function get$$1() {
  35995. if (this.__state.space === 'HSV') {
  35996. return this.__state[component];
  35997. }
  35998. Color.recalculateHSV(this);
  35999. return this.__state[component];
  36000. },
  36001. set: function set$$1(v) {
  36002. if (this.__state.space !== 'HSV') {
  36003. Color.recalculateHSV(this);
  36004. this.__state.space = 'HSV';
  36005. }
  36006. this.__state[component] = v;
  36007. }
  36008. });
  36009. }
  36010. Color.recalculateRGB = function (color, component, componentHexIndex) {
  36011. if (color.__state.space === 'HEX') {
  36012. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  36013. } else if (color.__state.space === 'HSV') {
  36014. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  36015. } else {
  36016. throw new Error('Corrupted color state');
  36017. }
  36018. };
  36019. Color.recalculateHSV = function (color) {
  36020. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  36021. Common.extend(color.__state, {
  36022. s: result.s,
  36023. v: result.v
  36024. });
  36025. if (!Common.isNaN(result.h)) {
  36026. color.__state.h = result.h;
  36027. } else if (Common.isUndefined(color.__state.h)) {
  36028. color.__state.h = 0;
  36029. }
  36030. };
  36031. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  36032. defineRGBComponent(Color.prototype, 'r', 2);
  36033. defineRGBComponent(Color.prototype, 'g', 1);
  36034. defineRGBComponent(Color.prototype, 'b', 0);
  36035. defineHSVComponent(Color.prototype, 'h');
  36036. defineHSVComponent(Color.prototype, 's');
  36037. defineHSVComponent(Color.prototype, 'v');
  36038. Object.defineProperty(Color.prototype, 'a', {
  36039. get: function get$$1() {
  36040. return this.__state.a;
  36041. },
  36042. set: function set$$1(v) {
  36043. this.__state.a = v;
  36044. }
  36045. });
  36046. Object.defineProperty(Color.prototype, 'hex', {
  36047. get: function get$$1() {
  36048. if (!this.__state.space !== 'HEX') {
  36049. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  36050. }
  36051. return this.__state.hex;
  36052. },
  36053. set: function set$$1(v) {
  36054. this.__state.space = 'HEX';
  36055. this.__state.hex = v;
  36056. }
  36057. });
  36058. var Controller = function () {
  36059. function Controller(object, property) {
  36060. classCallCheck(this, Controller);
  36061. this.initialValue = object[property];
  36062. this.domElement = document.createElement('div');
  36063. this.object = object;
  36064. this.property = property;
  36065. this.__onChange = undefined;
  36066. this.__onFinishChange = undefined;
  36067. }
  36068. createClass(Controller, [{
  36069. key: 'onChange',
  36070. value: function onChange(fnc) {
  36071. this.__onChange = fnc;
  36072. return this;
  36073. }
  36074. }, {
  36075. key: 'onFinishChange',
  36076. value: function onFinishChange(fnc) {
  36077. this.__onFinishChange = fnc;
  36078. return this;
  36079. }
  36080. }, {
  36081. key: 'setValue',
  36082. value: function setValue(newValue) {
  36083. this.object[this.property] = newValue;
  36084. if (this.__onChange) {
  36085. this.__onChange.call(this, newValue);
  36086. }
  36087. this.updateDisplay();
  36088. return this;
  36089. }
  36090. }, {
  36091. key: 'getValue',
  36092. value: function getValue() {
  36093. return this.object[this.property];
  36094. }
  36095. }, {
  36096. key: 'updateDisplay',
  36097. value: function updateDisplay() {
  36098. return this;
  36099. }
  36100. }, {
  36101. key: 'isModified',
  36102. value: function isModified() {
  36103. return this.initialValue !== this.getValue();
  36104. }
  36105. }]);
  36106. return Controller;
  36107. }();
  36108. var EVENT_MAP = {
  36109. HTMLEvents: ['change'],
  36110. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  36111. KeyboardEvents: ['keydown']
  36112. };
  36113. var EVENT_MAP_INV = {};
  36114. Common.each(EVENT_MAP, function (v, k) {
  36115. Common.each(v, function (e) {
  36116. EVENT_MAP_INV[e] = k;
  36117. });
  36118. });
  36119. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  36120. function cssValueToPixels(val) {
  36121. if (val === '0' || Common.isUndefined(val)) {
  36122. return 0;
  36123. }
  36124. var match = val.match(CSS_VALUE_PIXELS);
  36125. if (!Common.isNull(match)) {
  36126. return parseFloat(match[1]);
  36127. }
  36128. return 0;
  36129. }
  36130. var dom = {
  36131. makeSelectable: function makeSelectable(elem, selectable) {
  36132. if (elem === undefined || elem.style === undefined) return;
  36133. elem.onselectstart = selectable ? function () {
  36134. return false;
  36135. } : function () {};
  36136. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  36137. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  36138. elem.unselectable = selectable ? 'on' : 'off';
  36139. },
  36140. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  36141. var vertical = vert;
  36142. var horizontal = hor;
  36143. if (Common.isUndefined(horizontal)) {
  36144. horizontal = true;
  36145. }
  36146. if (Common.isUndefined(vertical)) {
  36147. vertical = true;
  36148. }
  36149. elem.style.position = 'absolute';
  36150. if (horizontal) {
  36151. elem.style.left = 0;
  36152. elem.style.right = 0;
  36153. }
  36154. if (vertical) {
  36155. elem.style.top = 0;
  36156. elem.style.bottom = 0;
  36157. }
  36158. },
  36159. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  36160. var params = pars || {};
  36161. var className = EVENT_MAP_INV[eventType];
  36162. if (!className) {
  36163. throw new Error('Event type ' + eventType + ' not supported.');
  36164. }
  36165. var evt = document.createEvent(className);
  36166. switch (className) {
  36167. case 'MouseEvents':
  36168. {
  36169. var clientX = params.x || params.clientX || 0;
  36170. var clientY = params.y || params.clientY || 0;
  36171. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  36172. break;
  36173. }
  36174. case 'KeyboardEvents':
  36175. {
  36176. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  36177. Common.defaults(params, {
  36178. cancelable: true,
  36179. ctrlKey: false,
  36180. altKey: false,
  36181. shiftKey: false,
  36182. metaKey: false,
  36183. keyCode: undefined,
  36184. charCode: undefined
  36185. });
  36186. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  36187. break;
  36188. }
  36189. default:
  36190. {
  36191. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  36192. break;
  36193. }
  36194. }
  36195. Common.defaults(evt, aux);
  36196. elem.dispatchEvent(evt);
  36197. },
  36198. bind: function bind(elem, event, func, newBool) {
  36199. var bool = newBool || false;
  36200. if (elem.addEventListener) {
  36201. elem.addEventListener(event, func, bool);
  36202. } else if (elem.attachEvent) {
  36203. elem.attachEvent('on' + event, func);
  36204. }
  36205. return dom;
  36206. },
  36207. unbind: function unbind(elem, event, func, newBool) {
  36208. var bool = newBool || false;
  36209. if (elem.removeEventListener) {
  36210. elem.removeEventListener(event, func, bool);
  36211. } else if (elem.detachEvent) {
  36212. elem.detachEvent('on' + event, func);
  36213. }
  36214. return dom;
  36215. },
  36216. addClass: function addClass(elem, className) {
  36217. if (elem.className === undefined) {
  36218. elem.className = className;
  36219. } else if (elem.className !== className) {
  36220. var classes = elem.className.split(/ +/);
  36221. if (classes.indexOf(className) === -1) {
  36222. classes.push(className);
  36223. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  36224. }
  36225. }
  36226. return dom;
  36227. },
  36228. removeClass: function removeClass(elem, className) {
  36229. if (className) {
  36230. if (elem.className === className) {
  36231. elem.removeAttribute('class');
  36232. } else {
  36233. var classes = elem.className.split(/ +/);
  36234. var index = classes.indexOf(className);
  36235. if (index !== -1) {
  36236. classes.splice(index, 1);
  36237. elem.className = classes.join(' ');
  36238. }
  36239. }
  36240. } else {
  36241. elem.className = undefined;
  36242. }
  36243. return dom;
  36244. },
  36245. hasClass: function hasClass(elem, className) {
  36246. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  36247. },
  36248. getWidth: function getWidth(elem) {
  36249. var style = getComputedStyle(elem);
  36250. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  36251. },
  36252. getHeight: function getHeight(elem) {
  36253. var style = getComputedStyle(elem);
  36254. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  36255. },
  36256. getOffset: function getOffset(el) {
  36257. var elem = el;
  36258. var offset = {
  36259. left: 0,
  36260. top: 0
  36261. };
  36262. if (elem.offsetParent) {
  36263. do {
  36264. offset.left += elem.offsetLeft;
  36265. offset.top += elem.offsetTop;
  36266. elem = elem.offsetParent;
  36267. } while (elem);
  36268. }
  36269. return offset;
  36270. },
  36271. isActive: function isActive(elem) {
  36272. return elem === document.activeElement && (elem.type || elem.href);
  36273. }
  36274. };
  36275. var BooleanController = function (_Controller) {
  36276. inherits(BooleanController, _Controller);
  36277. function BooleanController(object, property) {
  36278. classCallCheck(this, BooleanController);
  36279. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  36280. var _this = _this2;
  36281. _this2.__prev = _this2.getValue();
  36282. _this2.__checkbox = document.createElement('input');
  36283. _this2.__checkbox.setAttribute('type', 'checkbox');
  36284. function onChange() {
  36285. _this.setValue(!_this.__prev);
  36286. }
  36287. dom.bind(_this2.__checkbox, 'change', onChange, false);
  36288. _this2.domElement.appendChild(_this2.__checkbox);
  36289. _this2.updateDisplay();
  36290. return _this2;
  36291. }
  36292. createClass(BooleanController, [{
  36293. key: 'setValue',
  36294. value: function setValue(v) {
  36295. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  36296. if (this.__onFinishChange) {
  36297. this.__onFinishChange.call(this, this.getValue());
  36298. }
  36299. this.__prev = this.getValue();
  36300. return toReturn;
  36301. }
  36302. }, {
  36303. key: 'updateDisplay',
  36304. value: function updateDisplay() {
  36305. if (this.getValue() === true) {
  36306. this.__checkbox.setAttribute('checked', 'checked');
  36307. this.__checkbox.checked = true;
  36308. this.__prev = true;
  36309. } else {
  36310. this.__checkbox.checked = false;
  36311. this.__prev = false;
  36312. }
  36313. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  36314. }
  36315. }]);
  36316. return BooleanController;
  36317. }(Controller);
  36318. var OptionController = function (_Controller) {
  36319. inherits(OptionController, _Controller);
  36320. function OptionController(object, property, opts) {
  36321. classCallCheck(this, OptionController);
  36322. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  36323. var options = opts;
  36324. var _this = _this2;
  36325. _this2.__select = document.createElement('select');
  36326. if (Common.isArray(options)) {
  36327. var map = {};
  36328. Common.each(options, function (element) {
  36329. map[element] = element;
  36330. });
  36331. options = map;
  36332. }
  36333. Common.each(options, function (value, key) {
  36334. var opt = document.createElement('option');
  36335. opt.innerHTML = key;
  36336. opt.setAttribute('value', value);
  36337. _this.__select.appendChild(opt);
  36338. });
  36339. _this2.updateDisplay();
  36340. dom.bind(_this2.__select, 'change', function () {
  36341. var desiredValue = this.options[this.selectedIndex].value;
  36342. _this.setValue(desiredValue);
  36343. });
  36344. _this2.domElement.appendChild(_this2.__select);
  36345. return _this2;
  36346. }
  36347. createClass(OptionController, [{
  36348. key: 'setValue',
  36349. value: function setValue(v) {
  36350. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  36351. if (this.__onFinishChange) {
  36352. this.__onFinishChange.call(this, this.getValue());
  36353. }
  36354. return toReturn;
  36355. }
  36356. }, {
  36357. key: 'updateDisplay',
  36358. value: function updateDisplay() {
  36359. if (dom.isActive(this.__select)) return this;
  36360. this.__select.value = this.getValue();
  36361. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  36362. }
  36363. }]);
  36364. return OptionController;
  36365. }(Controller);
  36366. var StringController = function (_Controller) {
  36367. inherits(StringController, _Controller);
  36368. function StringController(object, property) {
  36369. classCallCheck(this, StringController);
  36370. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  36371. var _this = _this2;
  36372. function onChange() {
  36373. _this.setValue(_this.__input.value);
  36374. }
  36375. function onBlur() {
  36376. if (_this.__onFinishChange) {
  36377. _this.__onFinishChange.call(_this, _this.getValue());
  36378. }
  36379. }
  36380. _this2.__input = document.createElement('input');
  36381. _this2.__input.setAttribute('type', 'text');
  36382. dom.bind(_this2.__input, 'keyup', onChange);
  36383. dom.bind(_this2.__input, 'change', onChange);
  36384. dom.bind(_this2.__input, 'blur', onBlur);
  36385. dom.bind(_this2.__input, 'keydown', function (e) {
  36386. if (e.keyCode === 13) {
  36387. this.blur();
  36388. }
  36389. });
  36390. _this2.updateDisplay();
  36391. _this2.domElement.appendChild(_this2.__input);
  36392. return _this2;
  36393. }
  36394. createClass(StringController, [{
  36395. key: 'updateDisplay',
  36396. value: function updateDisplay() {
  36397. if (!dom.isActive(this.__input)) {
  36398. this.__input.value = this.getValue();
  36399. }
  36400. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  36401. }
  36402. }]);
  36403. return StringController;
  36404. }(Controller);
  36405. function numDecimals(x) {
  36406. var _x = x.toString();
  36407. if (_x.indexOf('.') > -1) {
  36408. return _x.length - _x.indexOf('.') - 1;
  36409. }
  36410. return 0;
  36411. }
  36412. var NumberController = function (_Controller) {
  36413. inherits(NumberController, _Controller);
  36414. function NumberController(object, property, params) {
  36415. classCallCheck(this, NumberController);
  36416. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  36417. var _params = params || {};
  36418. _this.__min = _params.min;
  36419. _this.__max = _params.max;
  36420. _this.__step = _params.step;
  36421. if (Common.isUndefined(_this.__step)) {
  36422. if (_this.initialValue === 0) {
  36423. _this.__impliedStep = 1;
  36424. } else {
  36425. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  36426. }
  36427. } else {
  36428. _this.__impliedStep = _this.__step;
  36429. }
  36430. _this.__precision = numDecimals(_this.__impliedStep);
  36431. return _this;
  36432. }
  36433. createClass(NumberController, [{
  36434. key: 'setValue',
  36435. value: function setValue(v) {
  36436. var _v = v;
  36437. if (this.__min !== undefined && _v < this.__min) {
  36438. _v = this.__min;
  36439. } else if (this.__max !== undefined && _v > this.__max) {
  36440. _v = this.__max;
  36441. }
  36442. if (this.__step !== undefined && _v % this.__step !== 0) {
  36443. _v = Math.round(_v / this.__step) * this.__step;
  36444. }
  36445. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  36446. }
  36447. }, {
  36448. key: 'min',
  36449. value: function min(minValue) {
  36450. this.__min = minValue;
  36451. return this;
  36452. }
  36453. }, {
  36454. key: 'max',
  36455. value: function max(maxValue) {
  36456. this.__max = maxValue;
  36457. return this;
  36458. }
  36459. }, {
  36460. key: 'step',
  36461. value: function step(stepValue) {
  36462. this.__step = stepValue;
  36463. this.__impliedStep = stepValue;
  36464. this.__precision = numDecimals(stepValue);
  36465. return this;
  36466. }
  36467. }]);
  36468. return NumberController;
  36469. }(Controller);
  36470. function roundToDecimal(value, decimals) {
  36471. var tenTo = Math.pow(10, decimals);
  36472. return Math.round(value * tenTo) / tenTo;
  36473. }
  36474. var NumberControllerBox = function (_NumberController) {
  36475. inherits(NumberControllerBox, _NumberController);
  36476. function NumberControllerBox(object, property, params) {
  36477. classCallCheck(this, NumberControllerBox);
  36478. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  36479. _this2.__truncationSuspended = false;
  36480. var _this = _this2;
  36481. var prevY = void 0;
  36482. function onChange() {
  36483. var attempted = parseFloat(_this.__input.value);
  36484. if (!Common.isNaN(attempted)) {
  36485. _this.setValue(attempted);
  36486. }
  36487. }
  36488. function onFinish() {
  36489. if (_this.__onFinishChange) {
  36490. _this.__onFinishChange.call(_this, _this.getValue());
  36491. }
  36492. }
  36493. function onBlur() {
  36494. onFinish();
  36495. }
  36496. function onMouseDrag(e) {
  36497. var diff = prevY - e.clientY;
  36498. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  36499. prevY = e.clientY;
  36500. }
  36501. function onMouseUp() {
  36502. dom.unbind(window, 'mousemove', onMouseDrag);
  36503. dom.unbind(window, 'mouseup', onMouseUp);
  36504. onFinish();
  36505. }
  36506. function onMouseDown(e) {
  36507. dom.bind(window, 'mousemove', onMouseDrag);
  36508. dom.bind(window, 'mouseup', onMouseUp);
  36509. prevY = e.clientY;
  36510. }
  36511. _this2.__input = document.createElement('input');
  36512. _this2.__input.setAttribute('type', 'text');
  36513. dom.bind(_this2.__input, 'change', onChange);
  36514. dom.bind(_this2.__input, 'blur', onBlur);
  36515. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  36516. dom.bind(_this2.__input, 'keydown', function (e) {
  36517. if (e.keyCode === 13) {
  36518. _this.__truncationSuspended = true;
  36519. this.blur();
  36520. _this.__truncationSuspended = false;
  36521. onFinish();
  36522. }
  36523. });
  36524. _this2.updateDisplay();
  36525. _this2.domElement.appendChild(_this2.__input);
  36526. return _this2;
  36527. }
  36528. createClass(NumberControllerBox, [{
  36529. key: 'updateDisplay',
  36530. value: function updateDisplay() {
  36531. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  36532. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  36533. }
  36534. }]);
  36535. return NumberControllerBox;
  36536. }(NumberController);
  36537. function map(v, i1, i2, o1, o2) {
  36538. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  36539. }
  36540. var NumberControllerSlider = function (_NumberController) {
  36541. inherits(NumberControllerSlider, _NumberController);
  36542. function NumberControllerSlider(object, property, min, max, step) {
  36543. classCallCheck(this, NumberControllerSlider);
  36544. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  36545. min: min,
  36546. max: max,
  36547. step: step
  36548. }));
  36549. var _this = _this2;
  36550. _this2.__background = document.createElement('div');
  36551. _this2.__foreground = document.createElement('div');
  36552. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  36553. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  36554. dom.addClass(_this2.__background, 'slider');
  36555. dom.addClass(_this2.__foreground, 'slider-fg');
  36556. function onMouseDown(e) {
  36557. document.activeElement.blur();
  36558. dom.bind(window, 'mousemove', onMouseDrag);
  36559. dom.bind(window, 'mouseup', onMouseUp);
  36560. onMouseDrag(e);
  36561. }
  36562. function onMouseDrag(e) {
  36563. e.preventDefault();
  36564. var bgRect = _this.__background.getBoundingClientRect();
  36565. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  36566. return false;
  36567. }
  36568. function onMouseUp() {
  36569. dom.unbind(window, 'mousemove', onMouseDrag);
  36570. dom.unbind(window, 'mouseup', onMouseUp);
  36571. if (_this.__onFinishChange) {
  36572. _this.__onFinishChange.call(_this, _this.getValue());
  36573. }
  36574. }
  36575. function onTouchStart(e) {
  36576. if (e.touches.length !== 1) {
  36577. return;
  36578. }
  36579. dom.bind(window, 'touchmove', onTouchMove);
  36580. dom.bind(window, 'touchend', onTouchEnd);
  36581. onTouchMove(e);
  36582. }
  36583. function onTouchMove(e) {
  36584. var clientX = e.touches[0].clientX;
  36585. var bgRect = _this.__background.getBoundingClientRect();
  36586. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  36587. }
  36588. function onTouchEnd() {
  36589. dom.unbind(window, 'touchmove', onTouchMove);
  36590. dom.unbind(window, 'touchend', onTouchEnd);
  36591. if (_this.__onFinishChange) {
  36592. _this.__onFinishChange.call(_this, _this.getValue());
  36593. }
  36594. }
  36595. _this2.updateDisplay();
  36596. _this2.__background.appendChild(_this2.__foreground);
  36597. _this2.domElement.appendChild(_this2.__background);
  36598. return _this2;
  36599. }
  36600. createClass(NumberControllerSlider, [{
  36601. key: 'updateDisplay',
  36602. value: function updateDisplay() {
  36603. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  36604. this.__foreground.style.width = pct * 100 + '%';
  36605. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  36606. }
  36607. }]);
  36608. return NumberControllerSlider;
  36609. }(NumberController);
  36610. var FunctionController = function (_Controller) {
  36611. inherits(FunctionController, _Controller);
  36612. function FunctionController(object, property, text) {
  36613. classCallCheck(this, FunctionController);
  36614. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  36615. var _this = _this2;
  36616. _this2.__button = document.createElement('div');
  36617. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  36618. dom.bind(_this2.__button, 'click', function (e) {
  36619. e.preventDefault();
  36620. _this.fire();
  36621. return false;
  36622. });
  36623. dom.addClass(_this2.__button, 'button');
  36624. _this2.domElement.appendChild(_this2.__button);
  36625. return _this2;
  36626. }
  36627. createClass(FunctionController, [{
  36628. key: 'fire',
  36629. value: function fire() {
  36630. if (this.__onChange) {
  36631. this.__onChange.call(this);
  36632. }
  36633. this.getValue().call(this.object);
  36634. if (this.__onFinishChange) {
  36635. this.__onFinishChange.call(this, this.getValue());
  36636. }
  36637. }
  36638. }]);
  36639. return FunctionController;
  36640. }(Controller);
  36641. var ColorController = function (_Controller) {
  36642. inherits(ColorController, _Controller);
  36643. function ColorController(object, property) {
  36644. classCallCheck(this, ColorController);
  36645. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  36646. _this2.__color = new Color(_this2.getValue());
  36647. _this2.__temp = new Color(0);
  36648. var _this = _this2;
  36649. _this2.domElement = document.createElement('div');
  36650. dom.makeSelectable(_this2.domElement, false);
  36651. _this2.__selector = document.createElement('div');
  36652. _this2.__selector.className = 'selector';
  36653. _this2.__saturation_field = document.createElement('div');
  36654. _this2.__saturation_field.className = 'saturation-field';
  36655. _this2.__field_knob = document.createElement('div');
  36656. _this2.__field_knob.className = 'field-knob';
  36657. _this2.__field_knob_border = '2px solid ';
  36658. _this2.__hue_knob = document.createElement('div');
  36659. _this2.__hue_knob.className = 'hue-knob';
  36660. _this2.__hue_field = document.createElement('div');
  36661. _this2.__hue_field.className = 'hue-field';
  36662. _this2.__input = document.createElement('input');
  36663. _this2.__input.type = 'text';
  36664. _this2.__input_textShadow = '0 1px 1px ';
  36665. dom.bind(_this2.__input, 'keydown', function (e) {
  36666. if (e.keyCode === 13) {
  36667. onBlur.call(this);
  36668. }
  36669. });
  36670. dom.bind(_this2.__input, 'blur', onBlur);
  36671. dom.bind(_this2.__selector, 'mousedown', function () {
  36672. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  36673. dom.removeClass(_this.__selector, 'drag');
  36674. });
  36675. });
  36676. dom.bind(_this2.__selector, 'touchstart', function () {
  36677. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  36678. dom.removeClass(_this.__selector, 'drag');
  36679. });
  36680. });
  36681. var valueField = document.createElement('div');
  36682. Common.extend(_this2.__selector.style, {
  36683. width: '122px',
  36684. height: '102px',
  36685. padding: '3px',
  36686. backgroundColor: '#222',
  36687. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  36688. });
  36689. Common.extend(_this2.__field_knob.style, {
  36690. position: 'absolute',
  36691. width: '12px',
  36692. height: '12px',
  36693. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  36694. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  36695. borderRadius: '12px',
  36696. zIndex: 1
  36697. });
  36698. Common.extend(_this2.__hue_knob.style, {
  36699. position: 'absolute',
  36700. width: '15px',
  36701. height: '2px',
  36702. borderRight: '4px solid #fff',
  36703. zIndex: 1
  36704. });
  36705. Common.extend(_this2.__saturation_field.style, {
  36706. width: '100px',
  36707. height: '100px',
  36708. border: '1px solid #555',
  36709. marginRight: '3px',
  36710. display: 'inline-block',
  36711. cursor: 'pointer'
  36712. });
  36713. Common.extend(valueField.style, {
  36714. width: '100%',
  36715. height: '100%',
  36716. background: 'none'
  36717. });
  36718. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  36719. Common.extend(_this2.__hue_field.style, {
  36720. width: '15px',
  36721. height: '100px',
  36722. border: '1px solid #555',
  36723. cursor: 'ns-resize',
  36724. position: 'absolute',
  36725. top: '3px',
  36726. right: '3px'
  36727. });
  36728. hueGradient(_this2.__hue_field);
  36729. Common.extend(_this2.__input.style, {
  36730. outline: 'none',
  36731. textAlign: 'center',
  36732. color: '#fff',
  36733. border: 0,
  36734. fontWeight: 'bold',
  36735. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  36736. });
  36737. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  36738. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  36739. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  36740. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  36741. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  36742. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  36743. function fieldDown(e) {
  36744. setSV(e);
  36745. dom.bind(window, 'mousemove', setSV);
  36746. dom.bind(window, 'touchmove', setSV);
  36747. dom.bind(window, 'mouseup', fieldUpSV);
  36748. dom.bind(window, 'touchend', fieldUpSV);
  36749. }
  36750. function fieldDownH(e) {
  36751. setH(e);
  36752. dom.bind(window, 'mousemove', setH);
  36753. dom.bind(window, 'touchmove', setH);
  36754. dom.bind(window, 'mouseup', fieldUpH);
  36755. dom.bind(window, 'touchend', fieldUpH);
  36756. }
  36757. function fieldUpSV() {
  36758. dom.unbind(window, 'mousemove', setSV);
  36759. dom.unbind(window, 'touchmove', setSV);
  36760. dom.unbind(window, 'mouseup', fieldUpSV);
  36761. dom.unbind(window, 'touchend', fieldUpSV);
  36762. onFinish();
  36763. }
  36764. function fieldUpH() {
  36765. dom.unbind(window, 'mousemove', setH);
  36766. dom.unbind(window, 'touchmove', setH);
  36767. dom.unbind(window, 'mouseup', fieldUpH);
  36768. dom.unbind(window, 'touchend', fieldUpH);
  36769. onFinish();
  36770. }
  36771. function onBlur() {
  36772. var i = interpret(this.value);
  36773. if (i !== false) {
  36774. _this.__color.__state = i;
  36775. _this.setValue(_this.__color.toOriginal());
  36776. } else {
  36777. this.value = _this.__color.toString();
  36778. }
  36779. }
  36780. function onFinish() {
  36781. if (_this.__onFinishChange) {
  36782. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  36783. }
  36784. }
  36785. _this2.__saturation_field.appendChild(valueField);
  36786. _this2.__selector.appendChild(_this2.__field_knob);
  36787. _this2.__selector.appendChild(_this2.__saturation_field);
  36788. _this2.__selector.appendChild(_this2.__hue_field);
  36789. _this2.__hue_field.appendChild(_this2.__hue_knob);
  36790. _this2.domElement.appendChild(_this2.__input);
  36791. _this2.domElement.appendChild(_this2.__selector);
  36792. _this2.updateDisplay();
  36793. function setSV(e) {
  36794. if (e.type.indexOf('touch') === -1) {
  36795. e.preventDefault();
  36796. }
  36797. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  36798. var _ref = e.touches && e.touches[0] || e,
  36799. clientX = _ref.clientX,
  36800. clientY = _ref.clientY;
  36801. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  36802. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  36803. if (v > 1) {
  36804. v = 1;
  36805. } else if (v < 0) {
  36806. v = 0;
  36807. }
  36808. if (s > 1) {
  36809. s = 1;
  36810. } else if (s < 0) {
  36811. s = 0;
  36812. }
  36813. _this.__color.v = v;
  36814. _this.__color.s = s;
  36815. _this.setValue(_this.__color.toOriginal());
  36816. return false;
  36817. }
  36818. function setH(e) {
  36819. if (e.type.indexOf('touch') === -1) {
  36820. e.preventDefault();
  36821. }
  36822. var fieldRect = _this.__hue_field.getBoundingClientRect();
  36823. var _ref2 = e.touches && e.touches[0] || e,
  36824. clientY = _ref2.clientY;
  36825. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  36826. if (h > 1) {
  36827. h = 1;
  36828. } else if (h < 0) {
  36829. h = 0;
  36830. }
  36831. _this.__color.h = h * 360;
  36832. _this.setValue(_this.__color.toOriginal());
  36833. return false;
  36834. }
  36835. return _this2;
  36836. }
  36837. createClass(ColorController, [{
  36838. key: 'updateDisplay',
  36839. value: function updateDisplay() {
  36840. var i = interpret(this.getValue());
  36841. if (i !== false) {
  36842. var mismatch = false;
  36843. Common.each(Color.COMPONENTS, function (component) {
  36844. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  36845. mismatch = true;
  36846. return {};
  36847. }
  36848. }, this);
  36849. if (mismatch) {
  36850. Common.extend(this.__color.__state, i);
  36851. }
  36852. }
  36853. Common.extend(this.__temp.__state, this.__color.__state);
  36854. this.__temp.a = 1;
  36855. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  36856. var _flip = 255 - flip;
  36857. Common.extend(this.__field_knob.style, {
  36858. marginLeft: 100 * this.__color.s - 7 + 'px',
  36859. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  36860. backgroundColor: this.__temp.toHexString(),
  36861. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  36862. });
  36863. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  36864. this.__temp.s = 1;
  36865. this.__temp.v = 1;
  36866. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  36867. this.__input.value = this.__color.toString();
  36868. Common.extend(this.__input.style, {
  36869. backgroundColor: this.__color.toHexString(),
  36870. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  36871. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  36872. });
  36873. }
  36874. }]);
  36875. return ColorController;
  36876. }(Controller);
  36877. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  36878. function linearGradient(elem, x, a, b) {
  36879. elem.style.background = '';
  36880. Common.each(vendors, function (vendor) {
  36881. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  36882. });
  36883. }
  36884. function hueGradient(elem) {
  36885. elem.style.background = '';
  36886. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  36887. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36888. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36889. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36890. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36891. }
  36892. var css = {
  36893. load: function load(url, indoc) {
  36894. var doc = indoc || document;
  36895. var link = doc.createElement('link');
  36896. link.type = 'text/css';
  36897. link.rel = 'stylesheet';
  36898. link.href = url;
  36899. doc.getElementsByTagName('head')[0].appendChild(link);
  36900. },
  36901. inject: function inject(cssContent, indoc) {
  36902. var doc = indoc || document;
  36903. var injected = document.createElement('style');
  36904. injected.type = 'text/css';
  36905. injected.innerHTML = cssContent;
  36906. var head = doc.getElementsByTagName('head')[0];
  36907. try {
  36908. head.appendChild(injected);
  36909. } catch (e) {}
  36910. }
  36911. };
  36912. 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>";
  36913. var ControllerFactory = function ControllerFactory(object, property) {
  36914. var initialValue = object[property];
  36915. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  36916. return new OptionController(object, property, arguments[2]);
  36917. }
  36918. if (Common.isNumber(initialValue)) {
  36919. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  36920. if (Common.isNumber(arguments[4])) {
  36921. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  36922. }
  36923. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  36924. }
  36925. if (Common.isNumber(arguments[4])) {
  36926. return new NumberControllerBox(object, property, {
  36927. min: arguments[2],
  36928. max: arguments[3],
  36929. step: arguments[4]
  36930. });
  36931. }
  36932. return new NumberControllerBox(object, property, {
  36933. min: arguments[2],
  36934. max: arguments[3]
  36935. });
  36936. }
  36937. if (Common.isString(initialValue)) {
  36938. return new StringController(object, property);
  36939. }
  36940. if (Common.isFunction(initialValue)) {
  36941. return new FunctionController(object, property, '');
  36942. }
  36943. if (Common.isBoolean(initialValue)) {
  36944. return new BooleanController(object, property);
  36945. }
  36946. return null;
  36947. };
  36948. function requestAnimationFrame(callback) {
  36949. setTimeout(callback, 1000 / 60);
  36950. }
  36951. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  36952. var CenteredDiv = function () {
  36953. function CenteredDiv() {
  36954. classCallCheck(this, CenteredDiv);
  36955. this.backgroundElement = document.createElement('div');
  36956. Common.extend(this.backgroundElement.style, {
  36957. backgroundColor: 'rgba(0,0,0,0.8)',
  36958. top: 0,
  36959. left: 0,
  36960. display: 'none',
  36961. zIndex: '1000',
  36962. opacity: 0,
  36963. WebkitTransition: 'opacity 0.2s linear',
  36964. transition: 'opacity 0.2s linear'
  36965. });
  36966. dom.makeFullscreen(this.backgroundElement);
  36967. this.backgroundElement.style.position = 'fixed';
  36968. this.domElement = document.createElement('div');
  36969. Common.extend(this.domElement.style, {
  36970. position: 'fixed',
  36971. display: 'none',
  36972. zIndex: '1001',
  36973. opacity: 0,
  36974. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  36975. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  36976. });
  36977. document.body.appendChild(this.backgroundElement);
  36978. document.body.appendChild(this.domElement);
  36979. var _this = this;
  36980. dom.bind(this.backgroundElement, 'click', function () {
  36981. _this.hide();
  36982. });
  36983. }
  36984. createClass(CenteredDiv, [{
  36985. key: 'show',
  36986. value: function show() {
  36987. var _this = this;
  36988. this.backgroundElement.style.display = 'block';
  36989. this.domElement.style.display = 'block';
  36990. this.domElement.style.opacity = 0;
  36991. this.domElement.style.webkitTransform = 'scale(1.1)';
  36992. this.layout();
  36993. Common.defer(function () {
  36994. _this.backgroundElement.style.opacity = 1;
  36995. _this.domElement.style.opacity = 1;
  36996. _this.domElement.style.webkitTransform = 'scale(1)';
  36997. });
  36998. }
  36999. }, {
  37000. key: 'hide',
  37001. value: function hide() {
  37002. var _this = this;
  37003. var hide = function hide() {
  37004. _this.domElement.style.display = 'none';
  37005. _this.backgroundElement.style.display = 'none';
  37006. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  37007. dom.unbind(_this.domElement, 'transitionend', hide);
  37008. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  37009. };
  37010. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  37011. dom.bind(this.domElement, 'transitionend', hide);
  37012. dom.bind(this.domElement, 'oTransitionEnd', hide);
  37013. this.backgroundElement.style.opacity = 0;
  37014. this.domElement.style.opacity = 0;
  37015. this.domElement.style.webkitTransform = 'scale(1.1)';
  37016. }
  37017. }, {
  37018. key: 'layout',
  37019. value: function layout() {
  37020. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  37021. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  37022. }
  37023. }]);
  37024. return CenteredDiv;
  37025. }();
  37026. 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");
  37027. css.inject(styleSheet);
  37028. var CSS_NAMESPACE = 'dg';
  37029. var HIDE_KEY_CODE = 72;
  37030. var CLOSE_BUTTON_HEIGHT = 20;
  37031. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  37032. var SUPPORTS_LOCAL_STORAGE = function () {
  37033. try {
  37034. return !!window.localStorage;
  37035. } catch (e) {
  37036. return false;
  37037. }
  37038. }();
  37039. var SAVE_DIALOGUE = void 0;
  37040. var autoPlaceVirgin = true;
  37041. var autoPlaceContainer = void 0;
  37042. var hide = false;
  37043. var hideableGuis = [];
  37044. var GUI = function GUI(pars) {
  37045. var _this = this;
  37046. var params = pars || {};
  37047. this.domElement = document.createElement('div');
  37048. this.__ul = document.createElement('ul');
  37049. this.domElement.appendChild(this.__ul);
  37050. dom.addClass(this.domElement, CSS_NAMESPACE);
  37051. this.__folders = {};
  37052. this.__controllers = [];
  37053. this.__rememberedObjects = [];
  37054. this.__rememberedObjectIndecesToControllers = [];
  37055. this.__listening = [];
  37056. params = Common.defaults(params, {
  37057. closeOnTop: false,
  37058. autoPlace: true,
  37059. width: GUI.DEFAULT_WIDTH
  37060. });
  37061. params = Common.defaults(params, {
  37062. resizable: params.autoPlace,
  37063. hideable: params.autoPlace
  37064. });
  37065. if (!Common.isUndefined(params.load)) {
  37066. if (params.preset) {
  37067. params.load.preset = params.preset;
  37068. }
  37069. } else {
  37070. params.load = {
  37071. preset: DEFAULT_DEFAULT_PRESET_NAME
  37072. };
  37073. }
  37074. if (Common.isUndefined(params.parent) && params.hideable) {
  37075. hideableGuis.push(this);
  37076. }
  37077. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  37078. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  37079. params.scrollable = true;
  37080. }
  37081. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  37082. var saveToLocalStorage = void 0;
  37083. var titleRow = void 0;
  37084. Object.defineProperties(this, {
  37085. parent: {
  37086. get: function get$$1() {
  37087. return params.parent;
  37088. }
  37089. },
  37090. scrollable: {
  37091. get: function get$$1() {
  37092. return params.scrollable;
  37093. }
  37094. },
  37095. autoPlace: {
  37096. get: function get$$1() {
  37097. return params.autoPlace;
  37098. }
  37099. },
  37100. closeOnTop: {
  37101. get: function get$$1() {
  37102. return params.closeOnTop;
  37103. }
  37104. },
  37105. preset: {
  37106. get: function get$$1() {
  37107. if (_this.parent) {
  37108. return _this.getRoot().preset;
  37109. }
  37110. return params.load.preset;
  37111. },
  37112. set: function set$$1(v) {
  37113. if (_this.parent) {
  37114. _this.getRoot().preset = v;
  37115. } else {
  37116. params.load.preset = v;
  37117. }
  37118. setPresetSelectIndex(this);
  37119. _this.revert();
  37120. }
  37121. },
  37122. width: {
  37123. get: function get$$1() {
  37124. return params.width;
  37125. },
  37126. set: function set$$1(v) {
  37127. params.width = v;
  37128. setWidth(_this, v);
  37129. }
  37130. },
  37131. name: {
  37132. get: function get$$1() {
  37133. return params.name;
  37134. },
  37135. set: function set$$1(v) {
  37136. params.name = v;
  37137. if (titleRow) {
  37138. titleRow.innerHTML = params.name;
  37139. }
  37140. }
  37141. },
  37142. closed: {
  37143. get: function get$$1() {
  37144. return params.closed;
  37145. },
  37146. set: function set$$1(v) {
  37147. params.closed = v;
  37148. if (params.closed) {
  37149. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  37150. } else {
  37151. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  37152. }
  37153. this.onResize();
  37154. if (_this.__closeButton) {
  37155. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  37156. }
  37157. }
  37158. },
  37159. load: {
  37160. get: function get$$1() {
  37161. return params.load;
  37162. }
  37163. },
  37164. useLocalStorage: {
  37165. get: function get$$1() {
  37166. return useLocalStorage;
  37167. },
  37168. set: function set$$1(bool) {
  37169. if (SUPPORTS_LOCAL_STORAGE) {
  37170. useLocalStorage = bool;
  37171. if (bool) {
  37172. dom.bind(window, 'unload', saveToLocalStorage);
  37173. } else {
  37174. dom.unbind(window, 'unload', saveToLocalStorage);
  37175. }
  37176. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  37177. }
  37178. }
  37179. }
  37180. });
  37181. if (Common.isUndefined(params.parent)) {
  37182. this.closed = params.closed || false;
  37183. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  37184. dom.makeSelectable(this.domElement, false);
  37185. if (SUPPORTS_LOCAL_STORAGE) {
  37186. if (useLocalStorage) {
  37187. _this.useLocalStorage = true;
  37188. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  37189. if (savedGui) {
  37190. params.load = JSON.parse(savedGui);
  37191. }
  37192. }
  37193. }
  37194. this.__closeButton = document.createElement('div');
  37195. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  37196. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  37197. if (params.closeOnTop) {
  37198. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  37199. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  37200. } else {
  37201. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  37202. this.domElement.appendChild(this.__closeButton);
  37203. }
  37204. dom.bind(this.__closeButton, 'click', function () {
  37205. _this.closed = !_this.closed;
  37206. });
  37207. } else {
  37208. if (params.closed === undefined) {
  37209. params.closed = true;
  37210. }
  37211. var titleRowName = document.createTextNode(params.name);
  37212. dom.addClass(titleRowName, 'controller-name');
  37213. titleRow = addRow(_this, titleRowName);
  37214. var onClickTitle = function onClickTitle(e) {
  37215. e.preventDefault();
  37216. _this.closed = !_this.closed;
  37217. return false;
  37218. };
  37219. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  37220. dom.addClass(titleRow, 'title');
  37221. dom.bind(titleRow, 'click', onClickTitle);
  37222. if (!params.closed) {
  37223. this.closed = false;
  37224. }
  37225. }
  37226. if (params.autoPlace) {
  37227. if (Common.isUndefined(params.parent)) {
  37228. if (autoPlaceVirgin) {
  37229. autoPlaceContainer = document.createElement('div');
  37230. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  37231. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  37232. document.body.appendChild(autoPlaceContainer);
  37233. autoPlaceVirgin = false;
  37234. }
  37235. autoPlaceContainer.appendChild(this.domElement);
  37236. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  37237. }
  37238. if (!this.parent) {
  37239. setWidth(_this, params.width);
  37240. }
  37241. }
  37242. this.__resizeHandler = function () {
  37243. _this.onResizeDebounced();
  37244. };
  37245. dom.bind(window, 'resize', this.__resizeHandler);
  37246. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  37247. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  37248. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  37249. this.onResize();
  37250. if (params.resizable) {
  37251. addResizeHandle(this);
  37252. }
  37253. saveToLocalStorage = function saveToLocalStorage() {
  37254. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  37255. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  37256. }
  37257. };
  37258. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  37259. function resetWidth() {
  37260. var root = _this.getRoot();
  37261. root.width += 1;
  37262. Common.defer(function () {
  37263. root.width -= 1;
  37264. });
  37265. }
  37266. if (!params.parent) {
  37267. resetWidth();
  37268. }
  37269. };
  37270. GUI.toggleHide = function () {
  37271. hide = !hide;
  37272. Common.each(hideableGuis, function (gui) {
  37273. gui.domElement.style.display = hide ? 'none' : '';
  37274. });
  37275. };
  37276. GUI.CLASS_AUTO_PLACE = 'a';
  37277. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  37278. GUI.CLASS_MAIN = 'main';
  37279. GUI.CLASS_CONTROLLER_ROW = 'cr';
  37280. GUI.CLASS_TOO_TALL = 'taller-than-window';
  37281. GUI.CLASS_CLOSED = 'closed';
  37282. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  37283. GUI.CLASS_CLOSE_TOP = 'close-top';
  37284. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  37285. GUI.CLASS_DRAG = 'drag';
  37286. GUI.DEFAULT_WIDTH = 245;
  37287. GUI.TEXT_CLOSED = 'Close Controls';
  37288. GUI.TEXT_OPEN = 'Open Controls';
  37289. GUI._keydownHandler = function (e) {
  37290. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  37291. GUI.toggleHide();
  37292. }
  37293. };
  37294. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  37295. Common.extend(GUI.prototype, {
  37296. add: function add(object, property) {
  37297. return _add(this, object, property, {
  37298. factoryArgs: Array.prototype.slice.call(arguments, 2)
  37299. });
  37300. },
  37301. addColor: function addColor(object, property) {
  37302. return _add(this, object, property, {
  37303. color: true
  37304. });
  37305. },
  37306. remove: function remove(controller) {
  37307. this.__ul.removeChild(controller.__li);
  37308. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  37309. var _this = this;
  37310. Common.defer(function () {
  37311. _this.onResize();
  37312. });
  37313. },
  37314. destroy: function destroy() {
  37315. if (this.parent) {
  37316. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  37317. }
  37318. if (this.autoPlace) {
  37319. autoPlaceContainer.removeChild(this.domElement);
  37320. }
  37321. var _this = this;
  37322. Common.each(this.__folders, function (subfolder) {
  37323. _this.removeFolder(subfolder);
  37324. });
  37325. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  37326. removeListeners(this);
  37327. },
  37328. addFolder: function addFolder(name) {
  37329. if (this.__folders[name] !== undefined) {
  37330. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  37331. }
  37332. var newGuiParams = {
  37333. name: name,
  37334. parent: this
  37335. };
  37336. newGuiParams.autoPlace = this.autoPlace;
  37337. if (this.load && this.load.folders && this.load.folders[name]) {
  37338. newGuiParams.closed = this.load.folders[name].closed;
  37339. newGuiParams.load = this.load.folders[name];
  37340. }
  37341. var gui = new GUI(newGuiParams);
  37342. this.__folders[name] = gui;
  37343. var li = addRow(this, gui.domElement);
  37344. dom.addClass(li, 'folder');
  37345. return gui;
  37346. },
  37347. removeFolder: function removeFolder(folder) {
  37348. this.__ul.removeChild(folder.domElement.parentElement);
  37349. delete this.__folders[folder.name];
  37350. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  37351. delete this.load.folders[folder.name];
  37352. }
  37353. removeListeners(folder);
  37354. var _this = this;
  37355. Common.each(folder.__folders, function (subfolder) {
  37356. folder.removeFolder(subfolder);
  37357. });
  37358. Common.defer(function () {
  37359. _this.onResize();
  37360. });
  37361. },
  37362. open: function open() {
  37363. this.closed = false;
  37364. },
  37365. close: function close() {
  37366. this.closed = true;
  37367. },
  37368. hide: function hide() {
  37369. this.domElement.style.display = 'none';
  37370. },
  37371. show: function show() {
  37372. this.domElement.style.display = '';
  37373. },
  37374. onResize: function onResize() {
  37375. var root = this.getRoot();
  37376. if (root.scrollable) {
  37377. var top = dom.getOffset(root.__ul).top;
  37378. var h = 0;
  37379. Common.each(root.__ul.childNodes, function (node) {
  37380. if (!(root.autoPlace && node === root.__save_row)) {
  37381. h += dom.getHeight(node);
  37382. }
  37383. });
  37384. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  37385. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  37386. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  37387. } else {
  37388. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  37389. root.__ul.style.height = 'auto';
  37390. }
  37391. }
  37392. if (root.__resize_handle) {
  37393. Common.defer(function () {
  37394. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  37395. });
  37396. }
  37397. if (root.__closeButton) {
  37398. root.__closeButton.style.width = root.width + 'px';
  37399. }
  37400. },
  37401. onResizeDebounced: Common.debounce(function () {
  37402. this.onResize();
  37403. }, 50),
  37404. remember: function remember() {
  37405. if (Common.isUndefined(SAVE_DIALOGUE)) {
  37406. SAVE_DIALOGUE = new CenteredDiv();
  37407. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  37408. }
  37409. if (this.parent) {
  37410. throw new Error('You can only call remember on a top level GUI.');
  37411. }
  37412. var _this = this;
  37413. Common.each(Array.prototype.slice.call(arguments), function (object) {
  37414. if (_this.__rememberedObjects.length === 0) {
  37415. addSaveMenu(_this);
  37416. }
  37417. if (_this.__rememberedObjects.indexOf(object) === -1) {
  37418. _this.__rememberedObjects.push(object);
  37419. }
  37420. });
  37421. if (this.autoPlace) {
  37422. setWidth(this, this.width);
  37423. }
  37424. },
  37425. getRoot: function getRoot() {
  37426. var gui = this;
  37427. while (gui.parent) {
  37428. gui = gui.parent;
  37429. }
  37430. return gui;
  37431. },
  37432. getSaveObject: function getSaveObject() {
  37433. var toReturn = this.load;
  37434. toReturn.closed = this.closed;
  37435. if (this.__rememberedObjects.length > 0) {
  37436. toReturn.preset = this.preset;
  37437. if (!toReturn.remembered) {
  37438. toReturn.remembered = {};
  37439. }
  37440. toReturn.remembered[this.preset] = getCurrentPreset(this);
  37441. }
  37442. toReturn.folders = {};
  37443. Common.each(this.__folders, function (element, key) {
  37444. toReturn.folders[key] = element.getSaveObject();
  37445. });
  37446. return toReturn;
  37447. },
  37448. save: function save() {
  37449. if (!this.load.remembered) {
  37450. this.load.remembered = {};
  37451. }
  37452. this.load.remembered[this.preset] = getCurrentPreset(this);
  37453. markPresetModified(this, false);
  37454. this.saveToLocalStorageIfPossible();
  37455. },
  37456. saveAs: function saveAs(presetName) {
  37457. if (!this.load.remembered) {
  37458. this.load.remembered = {};
  37459. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  37460. }
  37461. this.load.remembered[presetName] = getCurrentPreset(this);
  37462. this.preset = presetName;
  37463. addPresetOption(this, presetName, true);
  37464. this.saveToLocalStorageIfPossible();
  37465. },
  37466. revert: function revert(gui) {
  37467. Common.each(this.__controllers, function (controller) {
  37468. if (!this.getRoot().load.remembered) {
  37469. controller.setValue(controller.initialValue);
  37470. } else {
  37471. recallSavedValue(gui || this.getRoot(), controller);
  37472. }
  37473. if (controller.__onFinishChange) {
  37474. controller.__onFinishChange.call(controller, controller.getValue());
  37475. }
  37476. }, this);
  37477. Common.each(this.__folders, function (folder) {
  37478. folder.revert(folder);
  37479. });
  37480. if (!gui) {
  37481. markPresetModified(this.getRoot(), false);
  37482. }
  37483. },
  37484. listen: function listen(controller) {
  37485. var init = this.__listening.length === 0;
  37486. this.__listening.push(controller);
  37487. if (init) {
  37488. updateDisplays(this.__listening);
  37489. }
  37490. },
  37491. updateDisplay: function updateDisplay() {
  37492. Common.each(this.__controllers, function (controller) {
  37493. controller.updateDisplay();
  37494. });
  37495. Common.each(this.__folders, function (folder) {
  37496. folder.updateDisplay();
  37497. });
  37498. }
  37499. });
  37500. function addRow(gui, newDom, liBefore) {
  37501. var li = document.createElement('li');
  37502. if (newDom) {
  37503. li.appendChild(newDom);
  37504. }
  37505. if (liBefore) {
  37506. gui.__ul.insertBefore(li, liBefore);
  37507. } else {
  37508. gui.__ul.appendChild(li);
  37509. }
  37510. gui.onResize();
  37511. return li;
  37512. }
  37513. function removeListeners(gui) {
  37514. dom.unbind(window, 'resize', gui.__resizeHandler);
  37515. if (gui.saveToLocalStorageIfPossible) {
  37516. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  37517. }
  37518. }
  37519. function markPresetModified(gui, modified) {
  37520. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  37521. if (modified) {
  37522. opt.innerHTML = opt.value + '*';
  37523. } else {
  37524. opt.innerHTML = opt.value;
  37525. }
  37526. }
  37527. function augmentController(gui, li, controller) {
  37528. controller.__li = li;
  37529. controller.__gui = gui;
  37530. Common.extend(controller, {
  37531. options: function options(_options) {
  37532. if (arguments.length > 1) {
  37533. var nextSibling = controller.__li.nextElementSibling;
  37534. controller.remove();
  37535. return _add(gui, controller.object, controller.property, {
  37536. before: nextSibling,
  37537. factoryArgs: [Common.toArray(arguments)]
  37538. });
  37539. }
  37540. if (Common.isArray(_options) || Common.isObject(_options)) {
  37541. var _nextSibling = controller.__li.nextElementSibling;
  37542. controller.remove();
  37543. return _add(gui, controller.object, controller.property, {
  37544. before: _nextSibling,
  37545. factoryArgs: [_options]
  37546. });
  37547. }
  37548. },
  37549. name: function name(_name) {
  37550. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  37551. return controller;
  37552. },
  37553. listen: function listen() {
  37554. controller.__gui.listen(controller);
  37555. return controller;
  37556. },
  37557. remove: function remove() {
  37558. controller.__gui.remove(controller);
  37559. return controller;
  37560. }
  37561. });
  37562. if (controller instanceof NumberControllerSlider) {
  37563. var box = new NumberControllerBox(controller.object, controller.property, {
  37564. min: controller.__min,
  37565. max: controller.__max,
  37566. step: controller.__step
  37567. });
  37568. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  37569. var pc = controller[method];
  37570. var pb = box[method];
  37571. controller[method] = box[method] = function () {
  37572. var args = Array.prototype.slice.call(arguments);
  37573. pb.apply(box, args);
  37574. return pc.apply(controller, args);
  37575. };
  37576. });
  37577. dom.addClass(li, 'has-slider');
  37578. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  37579. } else if (controller instanceof NumberControllerBox) {
  37580. var r = function r(returned) {
  37581. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  37582. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  37583. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  37584. controller.remove();
  37585. var newController = _add(gui, controller.object, controller.property, {
  37586. before: controller.__li.nextElementSibling,
  37587. factoryArgs: [controller.__min, controller.__max, controller.__step]
  37588. });
  37589. newController.name(oldName);
  37590. if (wasListening) newController.listen();
  37591. return newController;
  37592. }
  37593. return returned;
  37594. };
  37595. controller.min = Common.compose(r, controller.min);
  37596. controller.max = Common.compose(r, controller.max);
  37597. } else if (controller instanceof BooleanController) {
  37598. dom.bind(li, 'click', function () {
  37599. dom.fakeEvent(controller.__checkbox, 'click');
  37600. });
  37601. dom.bind(controller.__checkbox, 'click', function (e) {
  37602. e.stopPropagation();
  37603. });
  37604. } else if (controller instanceof FunctionController) {
  37605. dom.bind(li, 'click', function () {
  37606. dom.fakeEvent(controller.__button, 'click');
  37607. });
  37608. dom.bind(li, 'mouseover', function () {
  37609. dom.addClass(controller.__button, 'hover');
  37610. });
  37611. dom.bind(li, 'mouseout', function () {
  37612. dom.removeClass(controller.__button, 'hover');
  37613. });
  37614. } else if (controller instanceof ColorController) {
  37615. dom.addClass(li, 'color');
  37616. controller.updateDisplay = Common.compose(function (val) {
  37617. li.style.borderLeftColor = controller.__color.toString();
  37618. return val;
  37619. }, controller.updateDisplay);
  37620. controller.updateDisplay();
  37621. }
  37622. controller.setValue = Common.compose(function (val) {
  37623. if (gui.getRoot().__preset_select && controller.isModified()) {
  37624. markPresetModified(gui.getRoot(), true);
  37625. }
  37626. return val;
  37627. }, controller.setValue);
  37628. }
  37629. function recallSavedValue(gui, controller) {
  37630. var root = gui.getRoot();
  37631. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  37632. if (matchedIndex !== -1) {
  37633. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  37634. if (controllerMap === undefined) {
  37635. controllerMap = {};
  37636. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  37637. }
  37638. controllerMap[controller.property] = controller;
  37639. if (root.load && root.load.remembered) {
  37640. var presetMap = root.load.remembered;
  37641. var preset = void 0;
  37642. if (presetMap[gui.preset]) {
  37643. preset = presetMap[gui.preset];
  37644. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  37645. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  37646. } else {
  37647. return;
  37648. }
  37649. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  37650. var value = preset[matchedIndex][controller.property];
  37651. controller.initialValue = value;
  37652. controller.setValue(value);
  37653. }
  37654. }
  37655. }
  37656. }
  37657. function _add(gui, object, property, params) {
  37658. if (object[property] === undefined) {
  37659. throw new Error('Object "' + object + '" has no property "' + property + '"');
  37660. }
  37661. var controller = void 0;
  37662. if (params.color) {
  37663. controller = new ColorController(object, property);
  37664. } else {
  37665. var factoryArgs = [object, property].concat(params.factoryArgs);
  37666. controller = ControllerFactory.apply(gui, factoryArgs);
  37667. }
  37668. if (params.before instanceof Controller) {
  37669. params.before = params.before.__li;
  37670. }
  37671. recallSavedValue(gui, controller);
  37672. dom.addClass(controller.domElement, 'c');
  37673. var name = document.createElement('span');
  37674. dom.addClass(name, 'property-name');
  37675. name.innerHTML = controller.property;
  37676. var container = document.createElement('div');
  37677. container.appendChild(name);
  37678. container.appendChild(controller.domElement);
  37679. var li = addRow(gui, container, params.before);
  37680. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  37681. if (controller instanceof ColorController) {
  37682. dom.addClass(li, 'color');
  37683. } else {
  37684. dom.addClass(li, _typeof(controller.getValue()));
  37685. }
  37686. augmentController(gui, li, controller);
  37687. gui.__controllers.push(controller);
  37688. return controller;
  37689. }
  37690. function getLocalStorageHash(gui, key) {
  37691. return document.location.href + '.' + key;
  37692. }
  37693. function addPresetOption(gui, name, setSelected) {
  37694. var opt = document.createElement('option');
  37695. opt.innerHTML = name;
  37696. opt.value = name;
  37697. gui.__preset_select.appendChild(opt);
  37698. if (setSelected) {
  37699. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  37700. }
  37701. }
  37702. function showHideExplain(gui, explain) {
  37703. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  37704. }
  37705. function addSaveMenu(gui) {
  37706. var div = gui.__save_row = document.createElement('li');
  37707. dom.addClass(gui.domElement, 'has-save');
  37708. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  37709. dom.addClass(div, 'save-row');
  37710. var gears = document.createElement('span');
  37711. gears.innerHTML = '&nbsp;';
  37712. dom.addClass(gears, 'button gears');
  37713. var button = document.createElement('span');
  37714. button.innerHTML = 'Save';
  37715. dom.addClass(button, 'button');
  37716. dom.addClass(button, 'save');
  37717. var button2 = document.createElement('span');
  37718. button2.innerHTML = 'New';
  37719. dom.addClass(button2, 'button');
  37720. dom.addClass(button2, 'save-as');
  37721. var button3 = document.createElement('span');
  37722. button3.innerHTML = 'Revert';
  37723. dom.addClass(button3, 'button');
  37724. dom.addClass(button3, 'revert');
  37725. var select = gui.__preset_select = document.createElement('select');
  37726. if (gui.load && gui.load.remembered) {
  37727. Common.each(gui.load.remembered, function (value, key) {
  37728. addPresetOption(gui, key, key === gui.preset);
  37729. });
  37730. } else {
  37731. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  37732. }
  37733. dom.bind(select, 'change', function () {
  37734. for (var index = 0; index < gui.__preset_select.length; index++) {
  37735. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  37736. }
  37737. gui.preset = this.value;
  37738. });
  37739. div.appendChild(select);
  37740. div.appendChild(gears);
  37741. div.appendChild(button);
  37742. div.appendChild(button2);
  37743. div.appendChild(button3);
  37744. if (SUPPORTS_LOCAL_STORAGE) {
  37745. var explain = document.getElementById('dg-local-explain');
  37746. var localStorageCheckBox = document.getElementById('dg-local-storage');
  37747. var saveLocally = document.getElementById('dg-save-locally');
  37748. saveLocally.style.display = 'block';
  37749. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  37750. localStorageCheckBox.setAttribute('checked', 'checked');
  37751. }
  37752. showHideExplain(gui, explain);
  37753. dom.bind(localStorageCheckBox, 'change', function () {
  37754. gui.useLocalStorage = !gui.useLocalStorage;
  37755. showHideExplain(gui, explain);
  37756. });
  37757. }
  37758. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  37759. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  37760. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  37761. SAVE_DIALOGUE.hide();
  37762. }
  37763. });
  37764. dom.bind(gears, 'click', function () {
  37765. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  37766. SAVE_DIALOGUE.show();
  37767. newConstructorTextArea.focus();
  37768. newConstructorTextArea.select();
  37769. });
  37770. dom.bind(button, 'click', function () {
  37771. gui.save();
  37772. });
  37773. dom.bind(button2, 'click', function () {
  37774. var presetName = prompt('Enter a new preset name.');
  37775. if (presetName) {
  37776. gui.saveAs(presetName);
  37777. }
  37778. });
  37779. dom.bind(button3, 'click', function () {
  37780. gui.revert();
  37781. });
  37782. }
  37783. function addResizeHandle(gui) {
  37784. var pmouseX = void 0;
  37785. gui.__resize_handle = document.createElement('div');
  37786. Common.extend(gui.__resize_handle.style, {
  37787. width: '6px',
  37788. marginLeft: '-3px',
  37789. height: '200px',
  37790. cursor: 'ew-resize',
  37791. position: 'absolute'
  37792. });
  37793. function drag(e) {
  37794. e.preventDefault();
  37795. gui.width += pmouseX - e.clientX;
  37796. gui.onResize();
  37797. pmouseX = e.clientX;
  37798. return false;
  37799. }
  37800. function dragStop() {
  37801. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  37802. dom.unbind(window, 'mousemove', drag);
  37803. dom.unbind(window, 'mouseup', dragStop);
  37804. }
  37805. function dragStart(e) {
  37806. e.preventDefault();
  37807. pmouseX = e.clientX;
  37808. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  37809. dom.bind(window, 'mousemove', drag);
  37810. dom.bind(window, 'mouseup', dragStop);
  37811. return false;
  37812. }
  37813. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  37814. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  37815. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  37816. }
  37817. function setWidth(gui, w) {
  37818. gui.domElement.style.width = w + 'px';
  37819. if (gui.__save_row && gui.autoPlace) {
  37820. gui.__save_row.style.width = w + 'px';
  37821. }
  37822. if (gui.__closeButton) {
  37823. gui.__closeButton.style.width = w + 'px';
  37824. }
  37825. }
  37826. function getCurrentPreset(gui, useInitialValues) {
  37827. var toReturn = {};
  37828. Common.each(gui.__rememberedObjects, function (val, index) {
  37829. var savedValues = {};
  37830. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  37831. Common.each(controllerMap, function (controller, property) {
  37832. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  37833. });
  37834. toReturn[index] = savedValues;
  37835. });
  37836. return toReturn;
  37837. }
  37838. function setPresetSelectIndex(gui) {
  37839. for (var index = 0; index < gui.__preset_select.length; index++) {
  37840. if (gui.__preset_select[index].value === gui.preset) {
  37841. gui.__preset_select.selectedIndex = index;
  37842. }
  37843. }
  37844. }
  37845. function updateDisplays(controllerArray) {
  37846. if (controllerArray.length !== 0) {
  37847. requestAnimationFrame$1.call(window, function () {
  37848. updateDisplays(controllerArray);
  37849. });
  37850. }
  37851. Common.each(controllerArray, function (c) {
  37852. c.updateDisplay();
  37853. });
  37854. }
  37855. var color = {
  37856. Color: Color,
  37857. math: ColorMath,
  37858. interpret: interpret
  37859. };
  37860. exports.color = color;
  37861. var controllers = {
  37862. Controller: Controller,
  37863. BooleanController: BooleanController,
  37864. OptionController: OptionController,
  37865. StringController: StringController,
  37866. NumberController: NumberController,
  37867. NumberControllerBox: NumberControllerBox,
  37868. NumberControllerSlider: NumberControllerSlider,
  37869. FunctionController: FunctionController,
  37870. ColorController: ColorController
  37871. };
  37872. exports.controllers = controllers;
  37873. var dom$1 = {
  37874. dom: dom
  37875. };
  37876. exports.dom = dom$1;
  37877. var gui = {
  37878. GUI: GUI
  37879. };
  37880. exports.gui = gui;
  37881. var GUI$1 = GUI;
  37882. exports.GUI = GUI$1;
  37883. var index = {
  37884. color: color,
  37885. controllers: controllers,
  37886. dom: dom$1,
  37887. gui: gui,
  37888. GUI: GUI$1
  37889. };
  37890. var _default = index;
  37891. exports.default = _default;
  37892. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  37893. "use strict";
  37894. Object.defineProperty(exports, "__esModule", {
  37895. value: true
  37896. });
  37897. exports.default = void 0;
  37898. /**
  37899. * @author mrdoob / http://mrdoob.com/
  37900. */
  37901. var Stats = function () {
  37902. var mode = 0;
  37903. var container = document.createElement('div');
  37904. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  37905. container.addEventListener('click', function (event) {
  37906. event.preventDefault();
  37907. showPanel(++mode % container.children.length);
  37908. }, false); //
  37909. function addPanel(panel) {
  37910. container.appendChild(panel.dom);
  37911. return panel;
  37912. }
  37913. function showPanel(id) {
  37914. for (var i = 0; i < container.children.length; i++) {
  37915. container.children[i].style.display = i === id ? 'block' : 'none';
  37916. }
  37917. mode = id;
  37918. } //
  37919. var beginTime = (performance || Date).now(),
  37920. prevTime = beginTime,
  37921. frames = 0;
  37922. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  37923. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  37924. if (self.performance && self.performance.memory) {
  37925. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  37926. }
  37927. showPanel(0);
  37928. return {
  37929. REVISION: 16,
  37930. dom: container,
  37931. addPanel: addPanel,
  37932. showPanel: showPanel,
  37933. begin: function () {
  37934. beginTime = (performance || Date).now();
  37935. },
  37936. end: function () {
  37937. frames++;
  37938. var time = (performance || Date).now();
  37939. msPanel.update(time - beginTime, 200);
  37940. if (time >= prevTime + 1000) {
  37941. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  37942. prevTime = time;
  37943. frames = 0;
  37944. if (memPanel) {
  37945. var memory = performance.memory;
  37946. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  37947. }
  37948. }
  37949. return time;
  37950. },
  37951. update: function () {
  37952. beginTime = this.end();
  37953. },
  37954. // Backwards Compatibility
  37955. domElement: container,
  37956. setMode: showPanel
  37957. };
  37958. };
  37959. Stats.Panel = function (name, fg, bg) {
  37960. var min = Infinity,
  37961. max = 0,
  37962. round = Math.round;
  37963. var PR = round(window.devicePixelRatio || 1);
  37964. var WIDTH = 80 * PR,
  37965. HEIGHT = 48 * PR,
  37966. TEXT_X = 3 * PR,
  37967. TEXT_Y = 2 * PR,
  37968. GRAPH_X = 3 * PR,
  37969. GRAPH_Y = 15 * PR,
  37970. GRAPH_WIDTH = 74 * PR,
  37971. GRAPH_HEIGHT = 30 * PR;
  37972. var canvas = document.createElement('canvas');
  37973. canvas.width = WIDTH;
  37974. canvas.height = HEIGHT;
  37975. canvas.style.cssText = 'width:80px;height:48px';
  37976. var context = canvas.getContext('2d');
  37977. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  37978. context.textBaseline = 'top';
  37979. context.fillStyle = bg;
  37980. context.fillRect(0, 0, WIDTH, HEIGHT);
  37981. context.fillStyle = fg;
  37982. context.fillText(name, TEXT_X, TEXT_Y);
  37983. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  37984. context.fillStyle = bg;
  37985. context.globalAlpha = 0.9;
  37986. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  37987. return {
  37988. dom: canvas,
  37989. update: function (value, maxValue) {
  37990. min = Math.min(min, value);
  37991. max = Math.max(max, value);
  37992. context.fillStyle = bg;
  37993. context.globalAlpha = 1;
  37994. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  37995. context.fillStyle = fg;
  37996. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  37997. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  37998. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  37999. context.fillStyle = bg;
  38000. context.globalAlpha = 0.9;
  38001. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  38002. }
  38003. };
  38004. };
  38005. var _default = Stats;
  38006. exports.default = _default;
  38007. },{}],"index.js":[function(require,module,exports) {
  38008. "use strict";
  38009. var _index = require("../src/index.js");
  38010. var _three = require("three");
  38011. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  38012. var _BufferGeometryUtils = require("three/examples/jsm/utils/BufferGeometryUtils.js");
  38013. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  38014. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  38015. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  38016. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  38017. 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; }
  38018. let camera, controls, scene, renderer, tiles, cameraHelper;
  38019. let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  38020. let secondRenderer, secondCameraHelper, secondControls, secondCamera;
  38021. let orthoCamera, orthoCameraHelper;
  38022. let box;
  38023. let raycaster, mouse, rayIntersect, lastHoveredElement;
  38024. let offsetParent;
  38025. let statsContainer, stats;
  38026. let params = {
  38027. 'enableUpdate': true,
  38028. 'enableRaycast': false,
  38029. 'enableCacheDisplay': false,
  38030. 'orthographic': false,
  38031. 'errorTarget': 6,
  38032. 'errorThreshold': 60,
  38033. 'maxDepth': 15,
  38034. 'loadSiblings': true,
  38035. 'displayActiveTiles': false,
  38036. 'resolutionScale': 1.0,
  38037. 'up': '+Y',
  38038. 'displayBoxBounds': false,
  38039. 'colorMode': 0,
  38040. 'showThirdPerson': false,
  38041. 'showSecondView': false,
  38042. 'reload': reinstantiateTiles
  38043. };
  38044. init();
  38045. animate();
  38046. function reinstantiateTiles() {
  38047. const url = window.location.hash.replace(/^#/, '') || '../data/tileset.json';
  38048. if (tiles) {
  38049. offsetParent.remove(tiles.group);
  38050. }
  38051. tiles = new _index.DebugTilesRenderer(url);
  38052. offsetParent.add(tiles.group);
  38053. }
  38054. function init() {
  38055. scene = new _three.Scene(); // primary camera view
  38056. renderer = new _three.WebGLRenderer({
  38057. antialias: true
  38058. });
  38059. renderer.setPixelRatio(window.devicePixelRatio);
  38060. renderer.setSize(window.innerWidth, window.innerHeight);
  38061. renderer.setClearColor(0x151c1f);
  38062. renderer.outputEncoding = _three.sRGBEncoding;
  38063. document.body.appendChild(renderer.domElement);
  38064. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  38065. camera.position.set(400, 400, 400);
  38066. cameraHelper = new _three.CameraHelper(camera);
  38067. scene.add(cameraHelper);
  38068. orthoCamera = new _three.OrthographicCamera();
  38069. orthoCameraHelper = new _three.CameraHelper(orthoCamera);
  38070. scene.add(orthoCameraHelper); // secondary camera view
  38071. secondCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  38072. secondCamera.position.set(400, 400, -400);
  38073. secondCamera.lookAt(0, 0, 0);
  38074. secondRenderer = new _three.WebGLRenderer({
  38075. antialias: true
  38076. });
  38077. secondRenderer.setPixelRatio(window.devicePixelRatio);
  38078. secondRenderer.setSize(window.innerWidth, window.innerHeight);
  38079. secondRenderer.setClearColor(0x151c1f);
  38080. secondRenderer.outputEncoding = _three.sRGBEncoding;
  38081. document.body.appendChild(secondRenderer.domElement);
  38082. secondRenderer.domElement.style.position = 'absolute';
  38083. secondRenderer.domElement.style.right = '0';
  38084. secondRenderer.domElement.style.top = '0';
  38085. secondRenderer.domElement.style.outline = '#0f1416 solid 2px';
  38086. secondControls = new _OrbitControls.OrbitControls(secondCamera, secondRenderer.domElement);
  38087. secondControls.screenSpacePanning = false;
  38088. secondControls.minDistance = 1;
  38089. secondControls.maxDistance = 2000;
  38090. secondCameraHelper = new _three.CameraHelper(secondCamera);
  38091. scene.add(secondCameraHelper); // Third person camera view
  38092. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  38093. thirdPersonCamera.position.set(50, 40, 40);
  38094. thirdPersonCamera.lookAt(0, 0, 0);
  38095. thirdPersonRenderer = new _three.WebGLRenderer({
  38096. antialias: true
  38097. });
  38098. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  38099. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  38100. thirdPersonRenderer.setClearColor(0x0f1416);
  38101. thirdPersonRenderer.outputEncoding = _three.sRGBEncoding;
  38102. document.body.appendChild(thirdPersonRenderer.domElement);
  38103. thirdPersonRenderer.domElement.style.position = 'fixed';
  38104. thirdPersonRenderer.domElement.style.left = '5px';
  38105. thirdPersonRenderer.domElement.style.bottom = '5px';
  38106. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  38107. thirdPersonControls.screenSpacePanning = false;
  38108. thirdPersonControls.minDistance = 1;
  38109. thirdPersonControls.maxDistance = 2000; // controls
  38110. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  38111. controls.screenSpacePanning = false;
  38112. controls.minDistance = 1;
  38113. controls.maxDistance = 2000; // lights
  38114. var dirLight = new _three.DirectionalLight(0xffffff);
  38115. dirLight.position.set(1, 2, 3);
  38116. scene.add(dirLight);
  38117. var ambLight = new _three.AmbientLight(0xffffff, 0.2);
  38118. scene.add(ambLight);
  38119. box = new _three.Box3();
  38120. offsetParent = new _three.Group();
  38121. scene.add(offsetParent); // Raycasting init
  38122. raycaster = new _three.Raycaster();
  38123. mouse = new _three.Vector2();
  38124. rayIntersect = new _three.Group();
  38125. const rayIntersectMat = new _three.MeshBasicMaterial({
  38126. color: 0xe91e63
  38127. });
  38128. const rayMesh = new _three.Mesh(new _three.CylinderBufferGeometry(0.25, 0.25, 6), rayIntersectMat);
  38129. rayMesh.rotation.x = Math.PI / 2;
  38130. rayMesh.position.z += 3;
  38131. rayIntersect.add(rayMesh);
  38132. const rayRing = new _three.Mesh(new _three.TorusBufferGeometry(1.5, 0.2, 16, 100), rayIntersectMat);
  38133. rayIntersect.add(rayRing);
  38134. scene.add(rayIntersect);
  38135. rayIntersect.visible = false;
  38136. reinstantiateTiles();
  38137. onWindowResize();
  38138. window.addEventListener('resize', onWindowResize, false);
  38139. renderer.domElement.addEventListener('mousemove', onMouseMove, false);
  38140. renderer.domElement.addEventListener('mousedown', onMouseDown, false);
  38141. renderer.domElement.addEventListener('mouseup', onMouseUp, false);
  38142. renderer.domElement.addEventListener('mouseleave', onMouseLeave, false);
  38143. secondRenderer.domElement.addEventListener('mousemove', onMouseMove, false);
  38144. secondRenderer.domElement.addEventListener('mousedown', onMouseDown, false);
  38145. secondRenderer.domElement.addEventListener('mouseup', onMouseUp, false);
  38146. secondRenderer.domElement.addEventListener('mouseleave', onMouseLeave, false); // GUI
  38147. const gui = new dat.GUI();
  38148. gui.width = 300;
  38149. const tileOptions = gui.addFolder('Tiles Options');
  38150. tileOptions.add(params, 'loadSiblings');
  38151. tileOptions.add(params, 'displayActiveTiles');
  38152. tileOptions.add(params, 'errorTarget').min(0).max(50);
  38153. tileOptions.add(params, 'errorThreshold').min(0).max(1000);
  38154. tileOptions.add(params, 'maxDepth').min(1).max(100);
  38155. tileOptions.add(params, 'up', ['+Y', '-Z']);
  38156. tileOptions.open();
  38157. const debug = gui.addFolder('Debug Options');
  38158. debug.add(params, 'displayBoxBounds');
  38159. debug.add(params, 'colorMode', {
  38160. DEFAULT: 0,
  38161. SCREEN_ERROR: 1,
  38162. GEOMETRIC_ERROR: 2,
  38163. DISTANCE: 3,
  38164. DEPTH: 4,
  38165. IS_LEAF: 5,
  38166. RANDOM_COLOR: 6
  38167. });
  38168. debug.open();
  38169. const exampleOptions = gui.addFolder('Example Options');
  38170. exampleOptions.add(params, 'resolutionScale').min(0.01).max(2.0).step(0.01).onChange(onWindowResize);
  38171. exampleOptions.add(params, 'orthographic');
  38172. exampleOptions.add(params, 'showThirdPerson');
  38173. exampleOptions.add(params, 'showSecondView').onChange(onWindowResize);
  38174. exampleOptions.add(params, 'enableUpdate');
  38175. exampleOptions.add(params, 'enableRaycast');
  38176. exampleOptions.add(params, 'enableCacheDisplay');
  38177. exampleOptions.open();
  38178. gui.add(params, 'reload');
  38179. gui.open();
  38180. statsContainer = document.createElement('div');
  38181. statsContainer.style.position = 'absolute';
  38182. statsContainer.style.top = 0;
  38183. statsContainer.style.left = 0;
  38184. statsContainer.style.color = 'white';
  38185. statsContainer.style.width = '100%';
  38186. statsContainer.style.textAlign = 'center';
  38187. statsContainer.style.padding = '5px';
  38188. statsContainer.style.pointerEvents = 'none';
  38189. statsContainer.style.lineHeight = '1.5em';
  38190. document.body.appendChild(statsContainer); // Stats
  38191. stats = new _statsModule.default();
  38192. stats.showPanel(0);
  38193. document.body.appendChild(stats.dom);
  38194. }
  38195. function onWindowResize() {
  38196. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  38197. thirdPersonCamera.updateProjectionMatrix();
  38198. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  38199. if (params.showSecondView) {
  38200. camera.aspect = 0.5 * window.innerWidth / window.innerHeight;
  38201. renderer.setSize(0.5 * window.innerWidth, window.innerHeight);
  38202. secondCamera.aspect = 0.5 * window.innerWidth / window.innerHeight;
  38203. secondRenderer.setSize(0.5 * window.innerWidth, window.innerHeight);
  38204. secondRenderer.domElement.style.display = 'block';
  38205. } else {
  38206. camera.aspect = window.innerWidth / window.innerHeight;
  38207. renderer.setSize(window.innerWidth, window.innerHeight);
  38208. secondRenderer.domElement.style.display = 'none';
  38209. }
  38210. camera.updateProjectionMatrix();
  38211. renderer.setPixelRatio(window.devicePixelRatio * params.resolutionScale);
  38212. secondCamera.updateProjectionMatrix();
  38213. secondRenderer.setPixelRatio(window.devicePixelRatio);
  38214. updateOrthoCamera();
  38215. }
  38216. function onMouseLeave(e) {
  38217. lastHoveredElement = null;
  38218. }
  38219. function onMouseMove(e) {
  38220. const bounds = this.getBoundingClientRect();
  38221. mouse.x = e.clientX - bounds.x;
  38222. mouse.y = e.clientY - bounds.y;
  38223. mouse.x = mouse.x / bounds.width * 2 - 1;
  38224. mouse.y = -(mouse.y / bounds.height) * 2 + 1;
  38225. lastHoveredElement = this;
  38226. }
  38227. const startPos = new _three.Vector2();
  38228. const endPos = new _three.Vector2();
  38229. function onMouseDown(e) {
  38230. const bounds = this.getBoundingClientRect();
  38231. startPos.set(e.clientX - bounds.x, e.clientY - bounds.y);
  38232. }
  38233. function onMouseUp(e) {
  38234. const bounds = this.getBoundingClientRect();
  38235. endPos.set(e.clientX - bounds.x, e.clientY - bounds.y);
  38236. if (startPos.distanceTo(endPos) > 2) {
  38237. return;
  38238. }
  38239. if (lastHoveredElement === secondRenderer.domElement) {
  38240. raycaster.setFromCamera(mouse, secondCamera);
  38241. } else {
  38242. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  38243. }
  38244. raycaster.firstHitOnly = true;
  38245. const results = raycaster.intersectObject(tiles.group, true);
  38246. if (results.length) {
  38247. const object = results[0].object;
  38248. const info = tiles.getTileInformationFromActiveObject(object);
  38249. let str = '';
  38250. for (const key in info) {
  38251. let val = info[key];
  38252. if (typeof val === 'number') {
  38253. val = Math.floor(val * 1e5) / 1e5;
  38254. }
  38255. let name = key;
  38256. while (name.length < 20) {
  38257. name += ' ';
  38258. }
  38259. str += `${name} : ${val}\n`;
  38260. }
  38261. console.log(str);
  38262. }
  38263. }
  38264. function updateOrthoCamera() {
  38265. orthoCamera.position.copy(camera.position);
  38266. orthoCamera.rotation.copy(camera.rotation);
  38267. const scale = camera.position.distanceTo(controls.target) / 2.0;
  38268. let aspect = window.innerWidth / window.innerHeight;
  38269. if (params.showSecondView) {
  38270. aspect *= 0.5;
  38271. }
  38272. orthoCamera.left = -aspect * scale;
  38273. orthoCamera.right = aspect * scale;
  38274. orthoCamera.bottom = -scale;
  38275. orthoCamera.top = scale;
  38276. orthoCamera.near = camera.near;
  38277. orthoCamera.far = camera.far;
  38278. orthoCamera.updateProjectionMatrix();
  38279. }
  38280. function animate() {
  38281. requestAnimationFrame(animate); // update options
  38282. tiles.errorTarget = params.errorTarget;
  38283. tiles.errorThreshold = params.errorThreshold;
  38284. tiles.loadSiblings = params.loadSiblings;
  38285. tiles.displayActiveTiles = params.displayActiveTiles;
  38286. tiles.maxDepth = params.maxDepth;
  38287. tiles.displayBoxBounds = params.displayBoxBounds;
  38288. tiles.colorMode = parseFloat(params.colorMode);
  38289. if (params.orthographic) {
  38290. tiles.deleteCamera(camera);
  38291. tiles.setCamera(orthoCamera);
  38292. tiles.setResolutionFromRenderer(orthoCamera, renderer);
  38293. } else {
  38294. tiles.deleteCamera(orthoCamera);
  38295. tiles.setCamera(camera);
  38296. tiles.setResolutionFromRenderer(camera, renderer);
  38297. }
  38298. if (params.showSecondView) {
  38299. tiles.setCamera(secondCamera);
  38300. tiles.setResolutionFromRenderer(secondCamera, secondRenderer);
  38301. } else {
  38302. tiles.deleteCamera(secondCamera);
  38303. }
  38304. offsetParent.rotation.set(0, 0, 0);
  38305. if (params.up === '-Z') {
  38306. offsetParent.rotation.x = Math.PI / 2;
  38307. }
  38308. offsetParent.updateMatrixWorld(true); // update tiles center
  38309. if (tiles.getBounds(box)) {
  38310. box.getCenter(tiles.group.position);
  38311. tiles.group.position.multiplyScalar(-1);
  38312. }
  38313. if (params.enableRaycast && lastHoveredElement !== null) {
  38314. if (lastHoveredElement === renderer.domElement) {
  38315. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  38316. } else {
  38317. raycaster.setFromCamera(mouse, secondCamera);
  38318. }
  38319. raycaster.firstHitOnly = true;
  38320. const results = raycaster.intersectObject(tiles.group, true);
  38321. if (results.length) {
  38322. const closestHit = results[0];
  38323. const point = closestHit.point;
  38324. rayIntersect.position.copy(point); // If the display bounds are visible they get intersected
  38325. if (closestHit.face) {
  38326. const normal = closestHit.face.normal;
  38327. normal.transformDirection(closestHit.object.matrixWorld);
  38328. rayIntersect.lookAt(point.x + normal.x, point.y + normal.y, point.z + normal.z);
  38329. }
  38330. rayIntersect.visible = true;
  38331. } else {
  38332. rayIntersect.visible = false;
  38333. }
  38334. } else {
  38335. rayIntersect.visible = false;
  38336. } // update tiles
  38337. window.tiles = tiles;
  38338. if (params.enableUpdate) {
  38339. secondCamera.updateMatrixWorld();
  38340. camera.updateMatrixWorld();
  38341. orthoCamera.updateMatrixWorld();
  38342. tiles.update();
  38343. }
  38344. render();
  38345. stats.update();
  38346. }
  38347. function render() {
  38348. updateOrthoCamera();
  38349. cameraHelper.visible = false;
  38350. orthoCameraHelper.visible = false;
  38351. secondCameraHelper.visible = false; // render primary view
  38352. if (params.orthographic) {
  38353. const dist = orthoCamera.position.distanceTo(rayIntersect.position);
  38354. rayIntersect.scale.setScalar(dist / 150);
  38355. } else {
  38356. const dist = camera.position.distanceTo(rayIntersect.position);
  38357. rayIntersect.scale.setScalar(dist * camera.fov / 6000);
  38358. }
  38359. renderer.render(scene, params.orthographic ? orthoCamera : camera); // render secondary view
  38360. if (params.showSecondView) {
  38361. const dist = secondCamera.position.distanceTo(rayIntersect.position);
  38362. rayIntersect.scale.setScalar(dist * secondCamera.fov / 6000);
  38363. secondRenderer.render(scene, secondCamera);
  38364. } // render third person view
  38365. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  38366. if (params.showThirdPerson) {
  38367. cameraHelper.update();
  38368. cameraHelper.visible = !params.orthographic;
  38369. orthoCameraHelper.update();
  38370. orthoCameraHelper.visible = params.orthographic;
  38371. if (params.showSecondView) {
  38372. secondCameraHelper.update();
  38373. secondCameraHelper.visible = true;
  38374. }
  38375. const dist = thirdPersonCamera.position.distanceTo(rayIntersect.position);
  38376. rayIntersect.scale.setScalar(dist * thirdPersonCamera.fov / 6000);
  38377. thirdPersonRenderer.render(scene, thirdPersonCamera);
  38378. }
  38379. const cacheFullness = tiles.lruCache.itemList.length / tiles.lruCache.minSize;
  38380. let str = `Downloading: ${tiles.stats.downloading} Parsing: ${tiles.stats.parsing} Visible: ${tiles.group.children.length - 2}`;
  38381. if (params.enableCacheDisplay) {
  38382. const geomSet = new Set();
  38383. tiles.traverse(tile => {
  38384. const scene = tile.cached.scene;
  38385. if (scene) {
  38386. scene.traverse(c => {
  38387. if (c.geometry) {
  38388. geomSet.add(c.geometry);
  38389. }
  38390. });
  38391. }
  38392. });
  38393. let count = 0;
  38394. geomSet.forEach(g => {
  38395. count += _BufferGeometryUtils.BufferGeometryUtils.estimateBytesUsed(g);
  38396. });
  38397. str += `<br/>Cache: ${(100 * cacheFullness).toFixed(2)}% ~${(count / 1000 / 1000).toFixed(2)}mb`;
  38398. }
  38399. if (statsContainer.innerHTML !== str) {
  38400. statsContainer.innerHTML = str;
  38401. }
  38402. }
  38403. },{"../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/utils/BufferGeometryUtils.js":"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.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) {
  38404. var global = arguments[3];
  38405. var OVERLAY_ID = '__parcel__error__overlay__';
  38406. var OldModule = module.bundle.Module;
  38407. function Module(moduleName) {
  38408. OldModule.call(this, moduleName);
  38409. this.hot = {
  38410. data: module.bundle.hotData,
  38411. _acceptCallbacks: [],
  38412. _disposeCallbacks: [],
  38413. accept: function (fn) {
  38414. this._acceptCallbacks.push(fn || function () {});
  38415. },
  38416. dispose: function (fn) {
  38417. this._disposeCallbacks.push(fn);
  38418. }
  38419. };
  38420. module.bundle.hotData = null;
  38421. }
  38422. module.bundle.Module = Module;
  38423. var checkedAssets, assetsToAccept;
  38424. var parent = module.bundle.parent;
  38425. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  38426. var hostname = "" || location.hostname;
  38427. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  38428. var ws = new WebSocket(protocol + '://' + hostname + ':' + "50023" + '/');
  38429. ws.onmessage = function (event) {
  38430. checkedAssets = {};
  38431. assetsToAccept = [];
  38432. var data = JSON.parse(event.data);
  38433. if (data.type === 'update') {
  38434. var handled = false;
  38435. data.assets.forEach(function (asset) {
  38436. if (!asset.isNew) {
  38437. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  38438. if (didAccept) {
  38439. handled = true;
  38440. }
  38441. }
  38442. }); // Enable HMR for CSS by default.
  38443. handled = handled || data.assets.every(function (asset) {
  38444. return asset.type === 'css' && asset.generated.js;
  38445. });
  38446. if (handled) {
  38447. console.clear();
  38448. data.assets.forEach(function (asset) {
  38449. hmrApply(global.parcelRequire, asset);
  38450. });
  38451. assetsToAccept.forEach(function (v) {
  38452. hmrAcceptRun(v[0], v[1]);
  38453. });
  38454. } else if (location.reload) {
  38455. // `location` global exists in a web worker context but lacks `.reload()` function.
  38456. location.reload();
  38457. }
  38458. }
  38459. if (data.type === 'reload') {
  38460. ws.close();
  38461. ws.onclose = function () {
  38462. location.reload();
  38463. };
  38464. }
  38465. if (data.type === 'error-resolved') {
  38466. console.log('[parcel] ✨ Error resolved');
  38467. removeErrorOverlay();
  38468. }
  38469. if (data.type === 'error') {
  38470. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  38471. removeErrorOverlay();
  38472. var overlay = createErrorOverlay(data);
  38473. document.body.appendChild(overlay);
  38474. }
  38475. };
  38476. }
  38477. function removeErrorOverlay() {
  38478. var overlay = document.getElementById(OVERLAY_ID);
  38479. if (overlay) {
  38480. overlay.remove();
  38481. }
  38482. }
  38483. function createErrorOverlay(data) {
  38484. var overlay = document.createElement('div');
  38485. overlay.id = OVERLAY_ID; // html encode message and stack trace
  38486. var message = document.createElement('div');
  38487. var stackTrace = document.createElement('pre');
  38488. message.innerText = data.error.message;
  38489. stackTrace.innerText = data.error.stack;
  38490. 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>';
  38491. return overlay;
  38492. }
  38493. function getParents(bundle, id) {
  38494. var modules = bundle.modules;
  38495. if (!modules) {
  38496. return [];
  38497. }
  38498. var parents = [];
  38499. var k, d, dep;
  38500. for (k in modules) {
  38501. for (d in modules[k][1]) {
  38502. dep = modules[k][1][d];
  38503. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  38504. parents.push(k);
  38505. }
  38506. }
  38507. }
  38508. if (bundle.parent) {
  38509. parents = parents.concat(getParents(bundle.parent, id));
  38510. }
  38511. return parents;
  38512. }
  38513. function hmrApply(bundle, asset) {
  38514. var modules = bundle.modules;
  38515. if (!modules) {
  38516. return;
  38517. }
  38518. if (modules[asset.id] || !bundle.parent) {
  38519. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  38520. asset.isNew = !modules[asset.id];
  38521. modules[asset.id] = [fn, asset.deps];
  38522. } else if (bundle.parent) {
  38523. hmrApply(bundle.parent, asset);
  38524. }
  38525. }
  38526. function hmrAcceptCheck(bundle, id) {
  38527. var modules = bundle.modules;
  38528. if (!modules) {
  38529. return;
  38530. }
  38531. if (!modules[id] && bundle.parent) {
  38532. return hmrAcceptCheck(bundle.parent, id);
  38533. }
  38534. if (checkedAssets[id]) {
  38535. return;
  38536. }
  38537. checkedAssets[id] = true;
  38538. var cached = bundle.cache[id];
  38539. assetsToAccept.push([bundle, id]);
  38540. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  38541. return true;
  38542. }
  38543. return getParents(global.parcelRequire, id).some(function (id) {
  38544. return hmrAcceptCheck(global.parcelRequire, id);
  38545. });
  38546. }
  38547. function hmrAcceptRun(bundle, id) {
  38548. var cached = bundle.cache[id];
  38549. bundle.hotData = {};
  38550. if (cached) {
  38551. cached.hot.data = bundle.hotData;
  38552. }
  38553. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  38554. cached.hot._disposeCallbacks.forEach(function (cb) {
  38555. cb(bundle.hotData);
  38556. });
  38557. }
  38558. delete bundle.cache[id];
  38559. bundle(id);
  38560. cached = bundle.cache[id];
  38561. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  38562. cached.hot._acceptCallbacks.forEach(function (cb) {
  38563. cb();
  38564. });
  38565. return true;
  38566. }
  38567. }
  38568. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  38569. //# sourceMappingURL=example.e31bb0bc.js.map