example.e31bb0bc.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146
  1. // modules are defined as an array
  2. // [ module function, map of requires ]
  3. //
  4. // map of requires is short require name -> numeric require
  5. //
  6. // anything defined in a previous bundle is accessed via the
  7. // orig method which is the require for previous bundles
  8. parcelRequire = (function (modules, cache, entry, globalName) {
  9. // Save the require from previous bundle to this closure if any
  10. var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
  11. var nodeRequire = typeof require === 'function' && require;
  12. function newRequire(name, jumped) {
  13. if (!cache[name]) {
  14. if (!modules[name]) {
  15. // if we cannot find the module within our internal map or
  16. // cache jump to the current global require ie. the last bundle
  17. // that was added to the page.
  18. var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
  19. if (!jumped && currentRequire) {
  20. return currentRequire(name, true);
  21. }
  22. // If there are other bundles on this page the require from the
  23. // previous one is saved to 'previousRequire'. Repeat this as
  24. // many times as there are bundles until the module is found or
  25. // we exhaust the require chain.
  26. if (previousRequire) {
  27. return previousRequire(name, true);
  28. }
  29. // Try the node require function if it exists.
  30. if (nodeRequire && typeof name === 'string') {
  31. return nodeRequire(name);
  32. }
  33. var err = new Error('Cannot find module \'' + name + '\'');
  34. err.code = 'MODULE_NOT_FOUND';
  35. throw err;
  36. }
  37. localRequire.resolve = resolve;
  38. localRequire.cache = {};
  39. var module = cache[name] = new newRequire.Module(name);
  40. modules[name][0].call(module.exports, localRequire, module, module.exports, this);
  41. }
  42. return cache[name].exports;
  43. function localRequire(x){
  44. return newRequire(localRequire.resolve(x));
  45. }
  46. function resolve(x){
  47. return modules[name][1][x] || x;
  48. }
  49. }
  50. function Module(moduleName) {
  51. this.id = moduleName;
  52. this.bundle = newRequire;
  53. this.exports = {};
  54. }
  55. newRequire.isParcelRequire = true;
  56. newRequire.Module = Module;
  57. newRequire.modules = modules;
  58. newRequire.cache = cache;
  59. newRequire.parent = previousRequire;
  60. newRequire.register = function (id, exports) {
  61. modules[id] = [function (require, module) {
  62. module.exports = exports;
  63. }, {}];
  64. };
  65. var error;
  66. for (var i = 0; i < entry.length; i++) {
  67. try {
  68. newRequire(entry[i]);
  69. } catch (e) {
  70. // Save first error but execute all entries
  71. if (!error) {
  72. error = e;
  73. }
  74. }
  75. }
  76. if (entry.length) {
  77. // Expose entry point to Node, AMD or browser globals
  78. // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
  79. var mainExports = newRequire(entry[entry.length - 1]);
  80. // CommonJS
  81. if (typeof exports === "object" && typeof module !== "undefined") {
  82. module.exports = mainExports;
  83. // RequireJS
  84. } else if (typeof define === "function" && define.amd) {
  85. define(function () {
  86. return mainExports;
  87. });
  88. // <script>
  89. } else if (globalName) {
  90. this[globalName] = mainExports;
  91. }
  92. }
  93. // Override the current require with this new one
  94. parcelRequire = newRequire;
  95. if (error) {
  96. // throw error from earlier, _after updating parcelRequire_
  97. throw error;
  98. }
  99. return newRequire;
  100. })({"../node_modules/process/browser.js":[function(require,module,exports) {
  101. // shim for using process in browser
  102. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  103. // don't break things. But we need to wrap it in a try catch in case it is
  104. // wrapped in strict mode code which doesn't define any globals. It's inside a
  105. // function because try/catches deoptimize in certain engines.
  106. var cachedSetTimeout;
  107. var cachedClearTimeout;
  108. function defaultSetTimout() {
  109. throw new Error('setTimeout has not been defined');
  110. }
  111. function defaultClearTimeout() {
  112. throw new Error('clearTimeout has not been defined');
  113. }
  114. (function () {
  115. try {
  116. if (typeof setTimeout === 'function') {
  117. cachedSetTimeout = setTimeout;
  118. } else {
  119. cachedSetTimeout = defaultSetTimout;
  120. }
  121. } catch (e) {
  122. cachedSetTimeout = defaultSetTimout;
  123. }
  124. try {
  125. if (typeof clearTimeout === 'function') {
  126. cachedClearTimeout = clearTimeout;
  127. } else {
  128. cachedClearTimeout = defaultClearTimeout;
  129. }
  130. } catch (e) {
  131. cachedClearTimeout = defaultClearTimeout;
  132. }
  133. })();
  134. function runTimeout(fun) {
  135. if (cachedSetTimeout === setTimeout) {
  136. //normal enviroments in sane situations
  137. return setTimeout(fun, 0);
  138. } // if setTimeout wasn't available but was latter defined
  139. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  140. cachedSetTimeout = setTimeout;
  141. return setTimeout(fun, 0);
  142. }
  143. try {
  144. // when when somebody has screwed with setTimeout but no I.E. maddness
  145. return cachedSetTimeout(fun, 0);
  146. } catch (e) {
  147. try {
  148. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  149. return cachedSetTimeout.call(null, fun, 0);
  150. } catch (e) {
  151. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  152. return cachedSetTimeout.call(this, fun, 0);
  153. }
  154. }
  155. }
  156. function runClearTimeout(marker) {
  157. if (cachedClearTimeout === clearTimeout) {
  158. //normal enviroments in sane situations
  159. return clearTimeout(marker);
  160. } // if clearTimeout wasn't available but was latter defined
  161. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  162. cachedClearTimeout = clearTimeout;
  163. return clearTimeout(marker);
  164. }
  165. try {
  166. // when when somebody has screwed with setTimeout but no I.E. maddness
  167. return cachedClearTimeout(marker);
  168. } catch (e) {
  169. try {
  170. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  171. return cachedClearTimeout.call(null, marker);
  172. } catch (e) {
  173. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  174. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  175. return cachedClearTimeout.call(this, marker);
  176. }
  177. }
  178. }
  179. var queue = [];
  180. var draining = false;
  181. var currentQueue;
  182. var queueIndex = -1;
  183. function cleanUpNextTick() {
  184. if (!draining || !currentQueue) {
  185. return;
  186. }
  187. draining = false;
  188. if (currentQueue.length) {
  189. queue = currentQueue.concat(queue);
  190. } else {
  191. queueIndex = -1;
  192. }
  193. if (queue.length) {
  194. drainQueue();
  195. }
  196. }
  197. function drainQueue() {
  198. if (draining) {
  199. return;
  200. }
  201. var timeout = runTimeout(cleanUpNextTick);
  202. draining = true;
  203. var len = queue.length;
  204. while (len) {
  205. currentQueue = queue;
  206. queue = [];
  207. while (++queueIndex < len) {
  208. if (currentQueue) {
  209. currentQueue[queueIndex].run();
  210. }
  211. }
  212. queueIndex = -1;
  213. len = queue.length;
  214. }
  215. currentQueue = null;
  216. draining = false;
  217. runClearTimeout(timeout);
  218. }
  219. process.nextTick = function (fun) {
  220. var args = new Array(arguments.length - 1);
  221. if (arguments.length > 1) {
  222. for (var i = 1; i < arguments.length; i++) {
  223. args[i - 1] = arguments[i];
  224. }
  225. }
  226. queue.push(new Item(fun, args));
  227. if (queue.length === 1 && !draining) {
  228. runTimeout(drainQueue);
  229. }
  230. }; // v8 likes predictible objects
  231. function Item(fun, array) {
  232. this.fun = fun;
  233. this.array = array;
  234. }
  235. Item.prototype.run = function () {
  236. this.fun.apply(null, this.array);
  237. };
  238. process.title = 'browser';
  239. process.env = {};
  240. process.argv = [];
  241. process.version = ''; // empty string to avoid regexp issues
  242. process.versions = {};
  243. function noop() {}
  244. process.on = noop;
  245. process.addListener = noop;
  246. process.once = noop;
  247. process.off = noop;
  248. process.removeListener = noop;
  249. process.removeAllListeners = noop;
  250. process.emit = noop;
  251. process.prependListener = noop;
  252. process.prependOnceListener = noop;
  253. process.listeners = function (name) {
  254. return [];
  255. };
  256. process.binding = function (name) {
  257. throw new Error('process.binding is not supported');
  258. };
  259. process.cwd = function () {
  260. return '/';
  261. };
  262. process.chdir = function (dir) {
  263. throw new Error('process.chdir is not supported');
  264. };
  265. process.umask = function () {
  266. return 0;
  267. };
  268. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  269. var process = require("process");
  270. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  271. // backported and transplited with Babel, with backwards-compat fixes
  272. // Copyright Joyent, Inc. and other Node contributors.
  273. //
  274. // Permission is hereby granted, free of charge, to any person obtaining a
  275. // copy of this software and associated documentation files (the
  276. // "Software"), to deal in the Software without restriction, including
  277. // without limitation the rights to use, copy, modify, merge, publish,
  278. // distribute, sublicense, and/or sell copies of the Software, and to permit
  279. // persons to whom the Software is furnished to do so, subject to the
  280. // following conditions:
  281. //
  282. // The above copyright notice and this permission notice shall be included
  283. // in all copies or substantial portions of the Software.
  284. //
  285. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  286. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  287. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  288. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  289. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  290. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  291. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  292. // resolves . and .. elements in a path array with directory names there
  293. // must be no slashes, empty elements, or device names (c:\) in the array
  294. // (so also no leading and trailing slashes - it does not distinguish
  295. // relative and absolute paths)
  296. function normalizeArray(parts, allowAboveRoot) {
  297. // if the path tries to go above the root, `up` ends up > 0
  298. var up = 0;
  299. for (var i = parts.length - 1; i >= 0; i--) {
  300. var last = parts[i];
  301. if (last === '.') {
  302. parts.splice(i, 1);
  303. } else if (last === '..') {
  304. parts.splice(i, 1);
  305. up++;
  306. } else if (up) {
  307. parts.splice(i, 1);
  308. up--;
  309. }
  310. }
  311. // if the path is allowed to go above the root, restore leading ..s
  312. if (allowAboveRoot) {
  313. for (; up--; up) {
  314. parts.unshift('..');
  315. }
  316. }
  317. return parts;
  318. }
  319. // path.resolve([from ...], to)
  320. // posix version
  321. exports.resolve = function() {
  322. var resolvedPath = '',
  323. resolvedAbsolute = false;
  324. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  325. var path = (i >= 0) ? arguments[i] : process.cwd();
  326. // Skip empty and invalid entries
  327. if (typeof path !== 'string') {
  328. throw new TypeError('Arguments to path.resolve must be strings');
  329. } else if (!path) {
  330. continue;
  331. }
  332. resolvedPath = path + '/' + resolvedPath;
  333. resolvedAbsolute = path.charAt(0) === '/';
  334. }
  335. // At this point the path should be resolved to a full absolute path, but
  336. // handle relative paths to be safe (might happen when process.cwd() fails)
  337. // Normalize the path
  338. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  339. return !!p;
  340. }), !resolvedAbsolute).join('/');
  341. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  342. };
  343. // path.normalize(path)
  344. // posix version
  345. exports.normalize = function(path) {
  346. var isAbsolute = exports.isAbsolute(path),
  347. trailingSlash = substr(path, -1) === '/';
  348. // Normalize the path
  349. path = normalizeArray(filter(path.split('/'), function(p) {
  350. return !!p;
  351. }), !isAbsolute).join('/');
  352. if (!path && !isAbsolute) {
  353. path = '.';
  354. }
  355. if (path && trailingSlash) {
  356. path += '/';
  357. }
  358. return (isAbsolute ? '/' : '') + path;
  359. };
  360. // posix version
  361. exports.isAbsolute = function(path) {
  362. return path.charAt(0) === '/';
  363. };
  364. // posix version
  365. exports.join = function() {
  366. var paths = Array.prototype.slice.call(arguments, 0);
  367. return exports.normalize(filter(paths, function(p, index) {
  368. if (typeof p !== 'string') {
  369. throw new TypeError('Arguments to path.join must be strings');
  370. }
  371. return p;
  372. }).join('/'));
  373. };
  374. // path.relative(from, to)
  375. // posix version
  376. exports.relative = function(from, to) {
  377. from = exports.resolve(from).substr(1);
  378. to = exports.resolve(to).substr(1);
  379. function trim(arr) {
  380. var start = 0;
  381. for (; start < arr.length; start++) {
  382. if (arr[start] !== '') break;
  383. }
  384. var end = arr.length - 1;
  385. for (; end >= 0; end--) {
  386. if (arr[end] !== '') break;
  387. }
  388. if (start > end) return [];
  389. return arr.slice(start, end - start + 1);
  390. }
  391. var fromParts = trim(from.split('/'));
  392. var toParts = trim(to.split('/'));
  393. var length = Math.min(fromParts.length, toParts.length);
  394. var samePartsLength = length;
  395. for (var i = 0; i < length; i++) {
  396. if (fromParts[i] !== toParts[i]) {
  397. samePartsLength = i;
  398. break;
  399. }
  400. }
  401. var outputParts = [];
  402. for (var i = samePartsLength; i < fromParts.length; i++) {
  403. outputParts.push('..');
  404. }
  405. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  406. return outputParts.join('/');
  407. };
  408. exports.sep = '/';
  409. exports.delimiter = ':';
  410. exports.dirname = function (path) {
  411. if (typeof path !== 'string') path = path + '';
  412. if (path.length === 0) return '.';
  413. var code = path.charCodeAt(0);
  414. var hasRoot = code === 47 /*/*/;
  415. var end = -1;
  416. var matchedSlash = true;
  417. for (var i = path.length - 1; i >= 1; --i) {
  418. code = path.charCodeAt(i);
  419. if (code === 47 /*/*/) {
  420. if (!matchedSlash) {
  421. end = i;
  422. break;
  423. }
  424. } else {
  425. // We saw the first non-path separator
  426. matchedSlash = false;
  427. }
  428. }
  429. if (end === -1) return hasRoot ? '/' : '.';
  430. if (hasRoot && end === 1) {
  431. // return '//';
  432. // Backwards-compat fix:
  433. return '/';
  434. }
  435. return path.slice(0, end);
  436. };
  437. function basename(path) {
  438. if (typeof path !== 'string') path = path + '';
  439. var start = 0;
  440. var end = -1;
  441. var matchedSlash = true;
  442. var i;
  443. for (i = path.length - 1; i >= 0; --i) {
  444. if (path.charCodeAt(i) === 47 /*/*/) {
  445. // If we reached a path separator that was not part of a set of path
  446. // separators at the end of the string, stop now
  447. if (!matchedSlash) {
  448. start = i + 1;
  449. break;
  450. }
  451. } else if (end === -1) {
  452. // We saw the first non-path separator, mark this as the end of our
  453. // path component
  454. matchedSlash = false;
  455. end = i + 1;
  456. }
  457. }
  458. if (end === -1) return '';
  459. return path.slice(start, end);
  460. }
  461. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  462. // in new Node.js versions, so only basename() above is backported here
  463. exports.basename = function (path, ext) {
  464. var f = basename(path);
  465. if (ext && f.substr(-1 * ext.length) === ext) {
  466. f = f.substr(0, f.length - ext.length);
  467. }
  468. return f;
  469. };
  470. exports.extname = function (path) {
  471. if (typeof path !== 'string') path = path + '';
  472. var startDot = -1;
  473. var startPart = 0;
  474. var end = -1;
  475. var matchedSlash = true;
  476. // Track the state of characters (if any) we see before our first dot and
  477. // after any path separator we find
  478. var preDotState = 0;
  479. for (var i = path.length - 1; i >= 0; --i) {
  480. var code = path.charCodeAt(i);
  481. if (code === 47 /*/*/) {
  482. // If we reached a path separator that was not part of a set of path
  483. // separators at the end of the string, stop now
  484. if (!matchedSlash) {
  485. startPart = i + 1;
  486. break;
  487. }
  488. continue;
  489. }
  490. if (end === -1) {
  491. // We saw the first non-path separator, mark this as the end of our
  492. // extension
  493. matchedSlash = false;
  494. end = i + 1;
  495. }
  496. if (code === 46 /*.*/) {
  497. // If this is our first dot, mark it as the start of our extension
  498. if (startDot === -1)
  499. startDot = i;
  500. else if (preDotState !== 1)
  501. preDotState = 1;
  502. } else if (startDot !== -1) {
  503. // We saw a non-dot and non-path separator before our dot, so we should
  504. // have a good chance at having a non-empty extension
  505. preDotState = -1;
  506. }
  507. }
  508. if (startDot === -1 || end === -1 ||
  509. // We saw a non-dot character immediately before the dot
  510. preDotState === 0 ||
  511. // The (right-most) trimmed path component is exactly '..'
  512. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  513. return '';
  514. }
  515. return path.slice(startDot, end);
  516. };
  517. function filter (xs, f) {
  518. if (xs.filter) return xs.filter(f);
  519. var res = [];
  520. for (var i = 0; i < xs.length; i++) {
  521. if (f(xs[i], i, xs)) res.push(xs[i]);
  522. }
  523. return res;
  524. }
  525. // String.prototype.substr - negative index don't work in IE8
  526. var substr = 'ab'.substr(-1) === 'b'
  527. ? function (str, start, len) { return str.substr(start, len) }
  528. : function (str, start, len) {
  529. if (start < 0) start = str.length + start;
  530. return str.substr(start, len);
  531. }
  532. ;
  533. },{"process":"../node_modules/process/browser.js"}],"../src/utilities/LRUCache.js":[function(require,module,exports) {
  534. "use strict";
  535. Object.defineProperty(exports, "__esModule", {
  536. value: true
  537. });
  538. exports.LRUCache = void 0;
  539. class LRUCache {
  540. constructor() {
  541. // options
  542. this.maxSize = 800;
  543. this.minSize = 600;
  544. this.unloadPercent = 0.2;
  545. this.usedSet = new Set();
  546. this.itemSet = new Set();
  547. this.itemList = [];
  548. this.callbacks = new Map();
  549. } // Returns whether or not the cache has reached the maximum size
  550. isFull() {
  551. return this.itemSet.size >= this.maxSize;
  552. }
  553. add(item, removeCb) {
  554. const itemSet = this.itemSet;
  555. if (itemSet.has(item)) {
  556. return false;
  557. }
  558. if (this.isFull()) {
  559. return false;
  560. }
  561. const usedSet = this.usedSet;
  562. const itemList = this.itemList;
  563. const callbacks = this.callbacks;
  564. itemList.push(item);
  565. usedSet.add(item);
  566. itemSet.add(item);
  567. callbacks.set(item, removeCb);
  568. return true;
  569. }
  570. remove(item) {
  571. const usedSet = this.usedSet;
  572. const itemSet = this.itemSet;
  573. const itemList = this.itemList;
  574. const callbacks = this.callbacks;
  575. if (itemSet.has(item)) {
  576. callbacks.get(item)(item);
  577. const index = itemList.indexOf(item);
  578. itemList.splice(index, 1);
  579. usedSet.delete(item);
  580. itemSet.delete(item);
  581. callbacks.delete(item);
  582. return true;
  583. }
  584. return false;
  585. }
  586. markUsed(item) {
  587. const itemSet = this.itemSet;
  588. const usedSet = this.usedSet;
  589. if (itemSet.has(item) && !usedSet.has(item)) {
  590. const itemList = this.itemList;
  591. const index = itemList.indexOf(item);
  592. itemList.splice(index, 1);
  593. itemList.push(item);
  594. usedSet.add(item);
  595. }
  596. }
  597. markAllUnused() {
  598. this.usedSet.clear();
  599. }
  600. unloadUnusedContent(prioritySortCb) {
  601. const unloadPercent = this.unloadPercent;
  602. const targetSize = this.minSize;
  603. const itemList = this.itemList;
  604. const itemSet = this.itemSet;
  605. const usedSet = this.usedSet;
  606. const callbacks = this.callbacks;
  607. const unused = itemList.length - usedSet.size;
  608. if (itemList.length > targetSize && unused > 0) {
  609. // TODO: sort by priority
  610. let nodesToUnload = Math.max(itemList.length - targetSize, targetSize) * unloadPercent;
  611. nodesToUnload = Math.ceil(nodesToUnload);
  612. nodesToUnload = Math.min(unused, nodesToUnload);
  613. const removedItems = itemList.splice(0, nodesToUnload);
  614. for (let i = 0, l = removedItems.length; i < l; i++) {
  615. const item = removedItems[i];
  616. callbacks.get(item)(item);
  617. itemSet.delete(item);
  618. callbacks.delete(item);
  619. }
  620. }
  621. }
  622. scheduleUnload(prioritySortCb, markAllUnused = true) {
  623. if (!this.scheduled) {
  624. this.scheduled = true;
  625. Promise.resolve().then(() => {
  626. this.scheduled = false;
  627. this.unloadUnusedContent(prioritySortCb);
  628. if (markAllUnused) {
  629. this.markAllUnused();
  630. }
  631. });
  632. }
  633. }
  634. }
  635. exports.LRUCache = LRUCache;
  636. },{}],"../src/utilities/PriorityQueue.js":[function(require,module,exports) {
  637. "use strict";
  638. Object.defineProperty(exports, "__esModule", {
  639. value: true
  640. });
  641. exports.PriorityQueue = void 0;
  642. class PriorityQueue {
  643. constructor(maxJobs = 6) {
  644. // options
  645. this.maxJobs = maxJobs;
  646. this.items = [];
  647. this.currJobs = 0;
  648. this.scheduled = false;
  649. }
  650. add(item, priority, callback) {
  651. return new Promise((resolve, reject) => {
  652. const prCallback = (...args) => callback(...args).then(resolve).catch(reject);
  653. const items = this.items;
  654. for (let i = 0, l = items.length; i < l; i++) {
  655. const thisItem = items[i];
  656. if (thisItem.priority > priority) {
  657. items.splice(i, 0, {
  658. priority,
  659. item,
  660. callback: prCallback
  661. });
  662. this.scheduleJobRun();
  663. return;
  664. }
  665. }
  666. items.push({
  667. priority,
  668. item,
  669. callback: prCallback
  670. });
  671. this.scheduleJobRun();
  672. });
  673. }
  674. remove(item) {
  675. const items = this.items;
  676. for (let i = 0, l = items.length; i < l; i++) {
  677. const thisItem = items[i];
  678. if (thisItem.item === item) {
  679. items.splice(i, 1);
  680. break;
  681. }
  682. }
  683. }
  684. tryRunJobs() {
  685. const items = this.items;
  686. const maxJobs = this.maxJobs;
  687. while (maxJobs > this.currJobs && items.length > 0) {
  688. this.currJobs++;
  689. const {
  690. item,
  691. priority,
  692. callback
  693. } = items.pop();
  694. callback(item, priority).then(() => {
  695. this.currJobs--;
  696. this.scheduleJobRun();
  697. }).catch(() => {
  698. this.currJobs--;
  699. this.scheduleJobRun();
  700. });
  701. }
  702. }
  703. scheduleJobRun() {
  704. if (!this.scheduled) {
  705. Promise.resolve().then(() => {
  706. this.tryRunJobs();
  707. this.scheduled = false;
  708. });
  709. this.scheduled = true;
  710. }
  711. }
  712. }
  713. exports.PriorityQueue = PriorityQueue;
  714. },{}],"../src/base/constants.js":[function(require,module,exports) {
  715. "use strict";
  716. Object.defineProperty(exports, "__esModule", {
  717. value: true
  718. });
  719. exports.FAILED = exports.LOADED = exports.PARSING = exports.LOADING = exports.UNLOADED = void 0;
  720. const UNLOADED = 0;
  721. exports.UNLOADED = UNLOADED;
  722. const LOADING = 1;
  723. exports.LOADING = LOADING;
  724. const PARSING = 2;
  725. exports.PARSING = PARSING;
  726. const LOADED = 3;
  727. exports.LOADED = LOADED;
  728. const FAILED = 4;
  729. exports.FAILED = FAILED;
  730. },{}],"../src/base/traverseFunctions.js":[function(require,module,exports) {
  731. "use strict";
  732. Object.defineProperty(exports, "__esModule", {
  733. value: true
  734. });
  735. exports.traverseSet = traverseSet;
  736. exports.determineFrustumSet = determineFrustumSet;
  737. exports.markUsedSetLeaves = markUsedSetLeaves;
  738. exports.skipTraversal = skipTraversal;
  739. exports.toggleTiles = toggleTiles;
  740. var _constants = require("./constants.js");
  741. function isUsedThisFrame(tile, frameCount) {
  742. return tile.__lastFrameVisited === frameCount && tile.__used;
  743. }
  744. function resetFrameState(tile, frameCount) {
  745. if (tile.__lastFrameVisited !== frameCount) {
  746. tile.__lastFrameVisited = frameCount;
  747. tile.__used = false;
  748. tile.__inFrustum = false;
  749. tile.__isLeaf = false;
  750. tile.__visible = false;
  751. tile.__active = false;
  752. tile.__error = 0;
  753. }
  754. }
  755. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  756. resetFrameState(tile, frameCount);
  757. tile.__used = true;
  758. lruCache.markUsed(tile);
  759. if (tile.__contentEmpty) {
  760. const children = tile.children;
  761. for (let i = 0, l = children.length; i < l; i++) {
  762. recursivelyMarkUsed(children[i], frameCount, lruCache);
  763. }
  764. }
  765. }
  766. function traverseSet(tile, beforeCb = null, afterCb = null, parent = null, depth = 0) {
  767. if (beforeCb && beforeCb(tile, parent, depth)) {
  768. if (afterCb) {
  769. afterCb(tile, parent, depth);
  770. }
  771. return;
  772. }
  773. const children = tile.children;
  774. for (let i = 0, l = children.length; i < l; i++) {
  775. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  776. }
  777. if (afterCb) {
  778. afterCb(tile, parent, depth);
  779. }
  780. } // TODO: include frustum mask here?
  781. function determineFrustumSet(tile, renderer) {
  782. const stats = renderer.stats;
  783. const frameCount = renderer.frameCount;
  784. const errorTarget = renderer.errorTarget;
  785. const maxDepth = renderer.maxDepth;
  786. const loadSiblings = renderer.loadSiblings;
  787. const lruCache = renderer.lruCache;
  788. resetFrameState(tile, frameCount);
  789. const inFrustum = renderer.tileInView(tile);
  790. if (inFrustum === false) {
  791. return false;
  792. }
  793. tile.__used = true;
  794. lruCache.markUsed(tile);
  795. tile.__inFrustum = true;
  796. stats.inFrustum++;
  797. if (!tile.__contentEmpty) {
  798. const error = renderer.calculateError(tile);
  799. tile.__error = error;
  800. if (error <= errorTarget) {
  801. return true;
  802. }
  803. }
  804. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  805. return true;
  806. }
  807. let anyChildrenUsed = false;
  808. const children = tile.children;
  809. for (let i = 0, l = children.length; i < l; i++) {
  810. const c = children[i];
  811. const r = determineFrustumSet(c, renderer);
  812. anyChildrenUsed = anyChildrenUsed || r;
  813. }
  814. if (anyChildrenUsed && loadSiblings) {
  815. for (let i = 0, l = children.length; i < l; i++) {
  816. recursivelyMarkUsed(tile, frameCount, lruCache);
  817. }
  818. }
  819. return true;
  820. }
  821. function markUsedSetLeaves(tile, renderer) {
  822. const stats = renderer.stats;
  823. const frameCount = renderer.frameCount;
  824. if (!isUsedThisFrame(tile, frameCount)) {
  825. return;
  826. }
  827. stats.used++;
  828. const children = tile.children;
  829. let anyChildrenUsed = false;
  830. for (let i = 0, l = children.length; i < l; i++) {
  831. const c = children[i];
  832. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  833. }
  834. if (!anyChildrenUsed) {
  835. tile.__isLeaf = true; // TODO: stats
  836. } else {
  837. for (let i = 0, l = children.length; i < l; i++) {
  838. const c = children[i];
  839. markUsedSetLeaves(c, renderer);
  840. }
  841. }
  842. }
  843. function skipTraversal(tile, renderer) {
  844. const stats = renderer.stats;
  845. const frameCount = renderer.frameCount;
  846. if (!isUsedThisFrame(tile, frameCount)) {
  847. return;
  848. }
  849. const lruCache = renderer.lruCache;
  850. if (tile.__isLeaf) {
  851. if (tile.__loadingState === _constants.LOADED) {
  852. if (tile.__inFrustum) {
  853. tile.__visible = true;
  854. stats.visible++;
  855. }
  856. tile.__active = true;
  857. stats.active++;
  858. } else if (!lruCache.isFull()) {
  859. renderer.requestTileContents(tile);
  860. }
  861. return;
  862. }
  863. const errorRequirement = renderer.errorTarget * renderer.errorThreshold;
  864. const meetsSSE = tile.__error < errorRequirement;
  865. const hasContent = tile.__loadingState === _constants.LOADED && !tile.__contentEmpty;
  866. const children = tile.children;
  867. let allChildrenHaveContent = true;
  868. for (let i = 0, l = children.length; i < l; i++) {
  869. const c = children[i];
  870. if (isUsedThisFrame(c, frameCount)) {
  871. const childContent = c.__loadingState === _constants.LOADED || tile.__contentEmpty;
  872. allChildrenHaveContent = allChildrenHaveContent && childContent;
  873. }
  874. }
  875. if (meetsSSE && !hasContent && !lruCache.isFull()) {
  876. renderer.requestTileContents(tile);
  877. }
  878. if (meetsSSE && hasContent && !allChildrenHaveContent) {
  879. if (tile.__inFrustum) {
  880. tile.__visible = true;
  881. stats.visible++;
  882. }
  883. tile.__active = true;
  884. stats.active++;
  885. for (let i = 0, l = children.length; i < l; i++) {
  886. const c = children[i];
  887. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  888. renderer.requestTileContents(c);
  889. }
  890. }
  891. return;
  892. }
  893. for (let i = 0, l = children.length; i < l; i++) {
  894. const c = children[i];
  895. if (isUsedThisFrame(c, frameCount)) {
  896. skipTraversal(c, renderer);
  897. }
  898. }
  899. }
  900. function toggleTiles(tile, renderer) {
  901. const frameCount = renderer.frameCount;
  902. const isUsed = isUsedThisFrame(tile, frameCount);
  903. if (isUsed || tile.__usedLastFrame) {
  904. if (!isUsed) {
  905. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  906. renderer.setTileVisible(tile, false);
  907. renderer.setTileActive(tile, false);
  908. }
  909. tile.__usedLastFrame = false;
  910. } else {
  911. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  912. // enable visibility if active due to shadows
  913. renderer.setTileActive(tile, tile.__active);
  914. renderer.setTileVisible(tile, tile.__active || tile.__visible);
  915. }
  916. tile.__usedLastFrame = true;
  917. }
  918. const children = tile.children;
  919. for (let i = 0, l = children.length; i < l; i++) {
  920. const c = children[i];
  921. toggleTiles(c, renderer);
  922. }
  923. }
  924. }
  925. },{"./constants.js":"../src/base/constants.js"}],"../src/base/TilesRendererBase.js":[function(require,module,exports) {
  926. "use strict";
  927. Object.defineProperty(exports, "__esModule", {
  928. value: true
  929. });
  930. exports.TilesRendererBase = void 0;
  931. var _path = _interopRequireDefault(require("path"));
  932. var _LRUCache = require("../utilities/LRUCache.js");
  933. var _PriorityQueue = require("../utilities/PriorityQueue.js");
  934. var _traverseFunctions = require("./traverseFunctions.js");
  935. var _constants = require("./constants.js");
  936. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  937. // TODO: find out why tiles are left dangling in the hierarchy
  938. // TODO: Address the issue of too many promises, garbage collection
  939. // TODO: remove more redundant computation
  940. // TODO: See if using classes improves performance
  941. // TODO: See if declaring function inline improves performance
  942. // TODO: Make sure active state works as expected
  943. class TilesRendererBase {
  944. get root() {
  945. const tileSet = this.tileSets[this.rootSet];
  946. if (!tileSet || tileSet instanceof Promise) {
  947. return null;
  948. } else {
  949. return tileSet.root;
  950. }
  951. }
  952. constructor(url, cache = new _LRUCache.LRUCache(), downloadQueue = new _PriorityQueue.PriorityQueue(6), parseQueue = new _PriorityQueue.PriorityQueue(1)) {
  953. // state
  954. this.tileSets = {};
  955. this.rootSet = url;
  956. this.lruCache = cache;
  957. this.downloadQueue = downloadQueue;
  958. this.parseQueue = parseQueue;
  959. this.stats = {
  960. parsing: 0,
  961. downloading: 0,
  962. inFrustum: 0,
  963. used: 0,
  964. active: 0,
  965. visible: 0
  966. };
  967. this.frameCount = 0; // options
  968. this.errorTarget = 6.0;
  969. this.errorThreshold = 6.0;
  970. this.loadSiblings = true;
  971. this.maxDepth = Infinity;
  972. this.loadTileSet(url);
  973. }
  974. traverse(cb) {
  975. const tileSets = this.tileSets;
  976. const rootTileSet = tileSets[this.rootSet];
  977. if (!rootTileSet || !rootTileSet.root) return;
  978. (0, _traverseFunctions.traverseSet)(rootTileSet.root, cb);
  979. } // Public API
  980. update() {
  981. const stats = this.stats;
  982. const lruCache = this.lruCache;
  983. const tileSets = this.tileSets;
  984. const rootTileSet = tileSets[this.rootSet];
  985. if (!rootTileSet || !rootTileSet.root) return;
  986. const root = rootTileSet.root;
  987. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  988. (0, _traverseFunctions.determineFrustumSet)(root, this);
  989. (0, _traverseFunctions.markUsedSetLeaves)(root, this);
  990. (0, _traverseFunctions.skipTraversal)(root, this);
  991. (0, _traverseFunctions.toggleTiles)(root, this); // TODO: We may want to add this function in the requestTileContents function
  992. lruCache.scheduleUnload(null);
  993. } // Overrideable
  994. parseTile(buffer, tile) {
  995. return null;
  996. }
  997. disposeTile(tile) {}
  998. preprocessNode(tile, parentTile, tileSetDir) {
  999. if (tile.content) {
  1000. if (!('uri' in tile.content) && 'url' in tile.content) {
  1001. tile.content.uri = tile.content.url;
  1002. delete tile.content.url;
  1003. }
  1004. if (tile.content.uri) {
  1005. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  1006. } // TODO: fix for some cases where tilesets provide the bounding volume
  1007. // but volumes are not present. See
  1008. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  1009. delete tile.content.boundingVolume;
  1010. }
  1011. }
  1012. tile.parent = parentTile;
  1013. tile.children = tile.children || [];
  1014. tile.__contentEmpty = !tile.content || !tile.content.uri;
  1015. tile.__error = 0.0;
  1016. tile.__inFrustum = false;
  1017. tile.__isLeaf = false;
  1018. tile.__wasUsed = false;
  1019. tile.__used = false;
  1020. tile.__wasVisible = false;
  1021. tile.__visible = false;
  1022. tile.__wasActive = false;
  1023. tile.__active = false;
  1024. tile.__childrenActive = false;
  1025. tile.__loadingState = _constants.UNLOADED;
  1026. tile.__loadIndex = 0;
  1027. tile.__loadAbort = null;
  1028. if (parentTile === null) {
  1029. tile.__depth = 0;
  1030. } else {
  1031. tile.__depth = parentTile.__depth + 1;
  1032. }
  1033. }
  1034. setTileActive(tile, state) {}
  1035. setTileVisible(tile, state) {}
  1036. calculateError(tile) {
  1037. return 0;
  1038. }
  1039. tileInView(tile) {
  1040. return true;
  1041. } // Private Functions
  1042. loadTileSet(url) {
  1043. const tileSets = this.tileSets;
  1044. if (!(url in tileSets)) {
  1045. const pr = fetch(url, {
  1046. credentials: 'same-origin'
  1047. }).then(res => {
  1048. if (res.ok) {
  1049. return res.json();
  1050. } else {
  1051. throw new Error(`Status ${res.status} (${res.statusText})`);
  1052. }
  1053. }).then(json => {
  1054. // TODO: Add version query?
  1055. const version = json.asset.version;
  1056. console.assert(version === '1.0' || version === '0.0');
  1057. const basePath = _path.default.dirname(url);
  1058. (0, _traverseFunctions.traverseSet)(json.root, (node, parent) => this.preprocessNode(node, parent, basePath));
  1059. tileSets[url] = json; // TODO: schedule an update to avoid doing this too many times
  1060. this.update();
  1061. });
  1062. pr.catch(e => {
  1063. console.error(`TilesLoader: Failed to load tile set json "${url}"`);
  1064. console.error(e);
  1065. delete tileSets[url];
  1066. });
  1067. tileSets[url] = pr;
  1068. }
  1069. return Promise.resolve(tileSets[url]);
  1070. }
  1071. requestTileContents(tile) {
  1072. // If the tile is already being loaded then don't
  1073. // start it again.
  1074. if (tile.__loadingState !== _constants.UNLOADED) {
  1075. return;
  1076. } // TODO: reuse the functions created here?
  1077. const lruCache = this.lruCache;
  1078. const downloadQueue = this.downloadQueue;
  1079. const parseQueue = this.parseQueue;
  1080. lruCache.add(tile, t => {
  1081. if (t.__loadingState === _constants.LOADING) {
  1082. t.__loadAbort.abort();
  1083. t.__loadAbort = null;
  1084. } else {
  1085. this.disposeTile(t);
  1086. }
  1087. if (t.__loadingState === _constants.LOADING) {
  1088. stats.downloading--;
  1089. } else if (t.__loadingState === _constants.PARSING) {
  1090. stats.parsing--;
  1091. }
  1092. t.__loadingState = _constants.UNLOADED;
  1093. t.__loadIndex++; // TODO: Removing from the queues here is slow
  1094. // parseQueue.remove( t );
  1095. // downloadQueue.remove( t );
  1096. });
  1097. tile.__loadIndex++;
  1098. const loadIndex = tile.__loadIndex;
  1099. const priority = 1 / (tile.__depth + 1);
  1100. const stats = this.stats;
  1101. const controller = new AbortController();
  1102. const signal = controller.signal;
  1103. stats.downloading++;
  1104. tile.__loadAbort = controller;
  1105. tile.__loadingState = _constants.LOADING;
  1106. downloadQueue.add(tile, priority, tile => {
  1107. if (tile.__loadIndex !== loadIndex) {
  1108. return Promise.resolve();
  1109. }
  1110. return fetch(tile.content.uri, {
  1111. credentials: 'same-origin',
  1112. signal
  1113. });
  1114. }).then(res => {
  1115. if (tile.__loadIndex !== loadIndex) {
  1116. return;
  1117. }
  1118. if (res.ok) {
  1119. return res.arrayBuffer();
  1120. } else {
  1121. throw new Error(`Failed to load model with error code ${res.status}`);
  1122. }
  1123. }).then(buffer => {
  1124. if (tile.__loadIndex !== loadIndex) {
  1125. return;
  1126. }
  1127. stats.downloading--;
  1128. stats.parsing++;
  1129. tile.__loadAbort = null;
  1130. tile.__loadingState = _constants.PARSING;
  1131. return parseQueue.add(buffer, priority, buffer => {
  1132. if (tile.__loadIndex !== loadIndex) {
  1133. return Promise.resolve();
  1134. }
  1135. return this.parseTile(buffer, tile);
  1136. });
  1137. }).then(() => {
  1138. if (tile.__loadIndex !== loadIndex) {
  1139. return;
  1140. }
  1141. stats.parsing--;
  1142. tile.__loadingState = _constants.LOADED;
  1143. this.setTileActive(tile, tile.__active);
  1144. this.setTileVisible(tile, tile.__visible);
  1145. }).catch(e => {
  1146. // if it has been unloaded then the tile has been disposed
  1147. if (tile.__loadIndex !== loadIndex) {
  1148. return;
  1149. }
  1150. if (e.name !== 'AbortError') {
  1151. console.error('TilesRenderer : Failed to load tile.');
  1152. console.error(e);
  1153. tile.__loadingState = _constants.FAILED;
  1154. } else {
  1155. lruCache.remove(tile);
  1156. }
  1157. });
  1158. }
  1159. }
  1160. exports.TilesRendererBase = TilesRendererBase;
  1161. },{"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) {
  1162. "use strict";
  1163. Object.defineProperty(exports, "__esModule", {
  1164. value: true
  1165. });
  1166. exports.B3DMLoaderBase = void 0;
  1167. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  1168. // convert an array of numbers to a string
  1169. function arrayToString(array) {
  1170. let str = '';
  1171. for (let i = 0, l = array.length; i < l; i++) {
  1172. str += String.fromCharCode(array[i]);
  1173. }
  1174. return str;
  1175. }
  1176. class B3DMLoaderBase {
  1177. constructor() {
  1178. this.fetchOptions = {};
  1179. }
  1180. load(url) {
  1181. return fetch(url, this.fetchOptions).then(res => res.arrayBuffer()).then(buffer => this.parse(buffer));
  1182. }
  1183. parse(buffer) {
  1184. const dataView = new DataView(buffer); // 28-byte header
  1185. // 4 bytes
  1186. const magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  1187. console.assert(magic === 'b3dm'); // 4 bytes
  1188. const version = dataView.getUint32(4, true);
  1189. console.assert(version === 1); // 4 bytes
  1190. const byteLength = dataView.getUint32(8, true);
  1191. console.assert(byteLength === buffer.byteLength); // 4 bytes
  1192. const featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  1193. const featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  1194. const batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  1195. const batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  1196. const featureTableStart = 28;
  1197. const jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  1198. const jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData)); // const binFeatureTableData = new Uint8Array( buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength );
  1199. // TODO: dereference the json feature table data in to the binary array.
  1200. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1201. // Batch Table
  1202. const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  1203. const jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  1204. const jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData)); // const binBatchTableData = new Uint8Array( buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength );
  1205. // TODO: dereference the json batch table data in to the binary array.
  1206. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1207. const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  1208. const glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  1209. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  1210. return {
  1211. version,
  1212. featureTable: jsonFeatureTable,
  1213. batchTable: jsonBatchTable,
  1214. glbBytes
  1215. };
  1216. }
  1217. }
  1218. exports.B3DMLoaderBase = B3DMLoaderBase;
  1219. },{}],"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  1220. "use strict";
  1221. Object.defineProperty(exports, "__esModule", {
  1222. value: true
  1223. });
  1224. exports.AmbientLight = AmbientLight;
  1225. exports.AmbientLightProbe = AmbientLightProbe;
  1226. exports.AnimationClip = AnimationClip;
  1227. exports.AnimationLoader = AnimationLoader;
  1228. exports.AnimationMixer = AnimationMixer;
  1229. exports.AnimationObjectGroup = AnimationObjectGroup;
  1230. exports.ArcCurve = ArcCurve;
  1231. exports.ArrayCamera = ArrayCamera;
  1232. exports.ArrowHelper = ArrowHelper;
  1233. exports.Audio = Audio;
  1234. exports.AudioAnalyser = AudioAnalyser;
  1235. exports.AudioListener = AudioListener;
  1236. exports.AudioLoader = AudioLoader;
  1237. exports.AxesHelper = AxesHelper;
  1238. exports.AxisHelper = AxisHelper;
  1239. exports.BinaryTextureLoader = BinaryTextureLoader;
  1240. exports.Bone = Bone;
  1241. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  1242. exports.BoundingBoxHelper = BoundingBoxHelper;
  1243. exports.Box2 = Box2;
  1244. exports.Box3 = Box3;
  1245. exports.Box3Helper = Box3Helper;
  1246. exports.BoxHelper = BoxHelper;
  1247. exports.BufferAttribute = BufferAttribute;
  1248. exports.BufferGeometry = BufferGeometry;
  1249. exports.BufferGeometryLoader = BufferGeometryLoader;
  1250. exports.Camera = Camera;
  1251. exports.CameraHelper = CameraHelper;
  1252. exports.CanvasRenderer = CanvasRenderer;
  1253. exports.CanvasTexture = CanvasTexture;
  1254. exports.CatmullRomCurve3 = CatmullRomCurve3;
  1255. exports.CircleBufferGeometry = CircleBufferGeometry;
  1256. exports.CircleGeometry = CircleGeometry;
  1257. exports.Clock = Clock;
  1258. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  1259. exports.Color = Color;
  1260. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  1261. exports.CompressedTexture = CompressedTexture;
  1262. exports.CompressedTextureLoader = CompressedTextureLoader;
  1263. exports.ConeBufferGeometry = ConeBufferGeometry;
  1264. exports.ConeGeometry = ConeGeometry;
  1265. exports.CubeCamera = CubeCamera;
  1266. exports.CubeTexture = CubeTexture;
  1267. exports.CubeTextureLoader = CubeTextureLoader;
  1268. exports.CubicBezierCurve = CubicBezierCurve;
  1269. exports.CubicBezierCurve3 = CubicBezierCurve3;
  1270. exports.CubicInterpolant = CubicInterpolant;
  1271. exports.Curve = Curve;
  1272. exports.CurvePath = CurvePath;
  1273. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  1274. exports.CylinderGeometry = CylinderGeometry;
  1275. exports.Cylindrical = Cylindrical;
  1276. exports.DataTexture = DataTexture;
  1277. exports.DataTexture2DArray = DataTexture2DArray;
  1278. exports.DataTexture3D = DataTexture3D;
  1279. exports.DataTextureLoader = DataTextureLoader;
  1280. exports.DepthTexture = DepthTexture;
  1281. exports.DirectionalLight = DirectionalLight;
  1282. exports.DirectionalLightHelper = DirectionalLightHelper;
  1283. exports.DirectionalLightShadow = DirectionalLightShadow;
  1284. exports.DiscreteInterpolant = DiscreteInterpolant;
  1285. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  1286. exports.DodecahedronGeometry = DodecahedronGeometry;
  1287. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  1288. exports.EdgesGeometry = EdgesGeometry;
  1289. exports.EdgesHelper = EdgesHelper;
  1290. exports.EllipseCurve = EllipseCurve;
  1291. exports.Euler = Euler;
  1292. exports.EventDispatcher = EventDispatcher;
  1293. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  1294. exports.ExtrudeGeometry = ExtrudeGeometry;
  1295. exports.Face3 = Face3;
  1296. exports.Face4 = Face4;
  1297. exports.FaceNormalsHelper = FaceNormalsHelper;
  1298. exports.FileLoader = FileLoader;
  1299. exports.Float32Attribute = Float32Attribute;
  1300. exports.Float32BufferAttribute = Float32BufferAttribute;
  1301. exports.Float64Attribute = Float64Attribute;
  1302. exports.Float64BufferAttribute = Float64BufferAttribute;
  1303. exports.Fog = Fog;
  1304. exports.FogExp2 = FogExp2;
  1305. exports.Font = Font;
  1306. exports.FontLoader = FontLoader;
  1307. exports.Frustum = Frustum;
  1308. exports.Geometry = Geometry;
  1309. exports.GridHelper = GridHelper;
  1310. exports.Group = Group;
  1311. exports.HemisphereLight = HemisphereLight;
  1312. exports.HemisphereLightHelper = HemisphereLightHelper;
  1313. exports.HemisphereLightProbe = HemisphereLightProbe;
  1314. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  1315. exports.IcosahedronGeometry = IcosahedronGeometry;
  1316. exports.ImageBitmapLoader = ImageBitmapLoader;
  1317. exports.ImageLoader = ImageLoader;
  1318. exports.ImmediateRenderObject = ImmediateRenderObject;
  1319. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  1320. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  1321. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  1322. exports.InstancedMesh = InstancedMesh;
  1323. exports.Int16Attribute = Int16Attribute;
  1324. exports.Int16BufferAttribute = Int16BufferAttribute;
  1325. exports.Int32Attribute = Int32Attribute;
  1326. exports.Int32BufferAttribute = Int32BufferAttribute;
  1327. exports.Int8Attribute = Int8Attribute;
  1328. exports.Int8BufferAttribute = Int8BufferAttribute;
  1329. exports.InterleavedBuffer = InterleavedBuffer;
  1330. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  1331. exports.Interpolant = Interpolant;
  1332. exports.JSONLoader = JSONLoader;
  1333. exports.KeyframeTrack = KeyframeTrack;
  1334. exports.LOD = LOD;
  1335. exports.LatheBufferGeometry = LatheBufferGeometry;
  1336. exports.LatheGeometry = LatheGeometry;
  1337. exports.Layers = Layers;
  1338. exports.LensFlare = LensFlare;
  1339. exports.Light = Light;
  1340. exports.LightProbe = LightProbe;
  1341. exports.LightProbeHelper = LightProbeHelper;
  1342. exports.LightShadow = LightShadow;
  1343. exports.Line = Line;
  1344. exports.Line3 = Line3;
  1345. exports.LineBasicMaterial = LineBasicMaterial;
  1346. exports.LineCurve = LineCurve;
  1347. exports.LineCurve3 = LineCurve3;
  1348. exports.LineDashedMaterial = LineDashedMaterial;
  1349. exports.LineLoop = LineLoop;
  1350. exports.LineSegments = LineSegments;
  1351. exports.LinearInterpolant = LinearInterpolant;
  1352. exports.Loader = Loader;
  1353. exports.LoadingManager = LoadingManager;
  1354. exports.Material = Material;
  1355. exports.MaterialLoader = MaterialLoader;
  1356. exports.Matrix3 = Matrix3;
  1357. exports.Matrix4 = Matrix4;
  1358. exports.Mesh = Mesh;
  1359. exports.MeshBasicMaterial = MeshBasicMaterial;
  1360. exports.MeshDepthMaterial = MeshDepthMaterial;
  1361. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  1362. exports.MeshFaceMaterial = MeshFaceMaterial;
  1363. exports.MeshLambertMaterial = MeshLambertMaterial;
  1364. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  1365. exports.MeshNormalMaterial = MeshNormalMaterial;
  1366. exports.MeshPhongMaterial = MeshPhongMaterial;
  1367. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  1368. exports.MeshStandardMaterial = MeshStandardMaterial;
  1369. exports.MeshToonMaterial = MeshToonMaterial;
  1370. exports.MultiMaterial = MultiMaterial;
  1371. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  1372. exports.Object3D = Object3D;
  1373. exports.ObjectLoader = ObjectLoader;
  1374. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  1375. exports.OctahedronGeometry = OctahedronGeometry;
  1376. exports.OrthographicCamera = OrthographicCamera;
  1377. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  1378. exports.ParametricGeometry = ParametricGeometry;
  1379. exports.Particle = Particle;
  1380. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  1381. exports.ParticleSystem = ParticleSystem;
  1382. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  1383. exports.Path = Path;
  1384. exports.PerspectiveCamera = PerspectiveCamera;
  1385. exports.Plane = Plane;
  1386. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  1387. exports.PlaneGeometry = PlaneGeometry;
  1388. exports.PlaneHelper = PlaneHelper;
  1389. exports.PointCloud = PointCloud;
  1390. exports.PointCloudMaterial = PointCloudMaterial;
  1391. exports.PointLight = PointLight;
  1392. exports.PointLightHelper = PointLightHelper;
  1393. exports.Points = Points;
  1394. exports.PointsMaterial = PointsMaterial;
  1395. exports.PolarGridHelper = PolarGridHelper;
  1396. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  1397. exports.PolyhedronGeometry = PolyhedronGeometry;
  1398. exports.PositionalAudio = PositionalAudio;
  1399. exports.PositionalAudioHelper = PositionalAudioHelper;
  1400. exports.PropertyBinding = PropertyBinding;
  1401. exports.PropertyMixer = PropertyMixer;
  1402. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  1403. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  1404. exports.Quaternion = Quaternion;
  1405. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  1406. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  1407. exports.RawShaderMaterial = RawShaderMaterial;
  1408. exports.Ray = Ray;
  1409. exports.Raycaster = Raycaster;
  1410. exports.RectAreaLight = RectAreaLight;
  1411. exports.RectAreaLightHelper = RectAreaLightHelper;
  1412. exports.RingBufferGeometry = RingBufferGeometry;
  1413. exports.RingGeometry = RingGeometry;
  1414. exports.Scene = Scene;
  1415. exports.ShaderMaterial = ShaderMaterial;
  1416. exports.ShadowMaterial = ShadowMaterial;
  1417. exports.Shape = Shape;
  1418. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  1419. exports.ShapeGeometry = ShapeGeometry;
  1420. exports.ShapePath = ShapePath;
  1421. exports.Skeleton = Skeleton;
  1422. exports.SkeletonHelper = SkeletonHelper;
  1423. exports.SkinnedMesh = SkinnedMesh;
  1424. exports.Sphere = Sphere;
  1425. exports.SphereBufferGeometry = SphereBufferGeometry;
  1426. exports.SphereGeometry = SphereGeometry;
  1427. exports.Spherical = Spherical;
  1428. exports.SphericalHarmonics3 = SphericalHarmonics3;
  1429. exports.Spline = Spline;
  1430. exports.SplineCurve = SplineCurve;
  1431. exports.SplineCurve3 = SplineCurve3;
  1432. exports.SpotLight = SpotLight;
  1433. exports.SpotLightHelper = SpotLightHelper;
  1434. exports.SpotLightShadow = SpotLightShadow;
  1435. exports.Sprite = Sprite;
  1436. exports.SpriteMaterial = SpriteMaterial;
  1437. exports.StereoCamera = StereoCamera;
  1438. exports.StringKeyframeTrack = StringKeyframeTrack;
  1439. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  1440. exports.TetrahedronGeometry = TetrahedronGeometry;
  1441. exports.TextBufferGeometry = TextBufferGeometry;
  1442. exports.TextGeometry = TextGeometry;
  1443. exports.Texture = Texture;
  1444. exports.TextureLoader = TextureLoader;
  1445. exports.TorusBufferGeometry = TorusBufferGeometry;
  1446. exports.TorusGeometry = TorusGeometry;
  1447. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  1448. exports.TorusKnotGeometry = TorusKnotGeometry;
  1449. exports.Triangle = Triangle;
  1450. exports.TubeBufferGeometry = TubeBufferGeometry;
  1451. exports.TubeGeometry = TubeGeometry;
  1452. exports.Uint16Attribute = Uint16Attribute;
  1453. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  1454. exports.Uint32Attribute = Uint32Attribute;
  1455. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  1456. exports.Uint8Attribute = Uint8Attribute;
  1457. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  1458. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  1459. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  1460. exports.Uniform = Uniform;
  1461. exports.Vector2 = Vector2;
  1462. exports.Vector3 = Vector3;
  1463. exports.Vector4 = Vector4;
  1464. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  1465. exports.Vertex = Vertex;
  1466. exports.VertexNormalsHelper = VertexNormalsHelper;
  1467. exports.VideoTexture = VideoTexture;
  1468. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  1469. exports.WebGLRenderTarget = WebGLRenderTarget;
  1470. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  1471. exports.WebGLRenderer = WebGLRenderer;
  1472. exports.WebGLUtils = WebGLUtils;
  1473. exports.WireframeGeometry = WireframeGeometry;
  1474. exports.WireframeHelper = WireframeHelper;
  1475. exports.XHRLoader = XHRLoader;
  1476. exports.NoToneMapping = exports.NoColors = exports.NoBlending = exports.NeverStencilFunc = exports.NeverDepth = exports.NearestMipmapNearestFilter = exports.NearestMipmapLinearFilter = exports.NearestMipMapNearestFilter = exports.NearestMipMapLinearFilter = exports.NearestFilter = exports.MultiplyOperation = exports.MultiplyBlending = exports.MixOperation = exports.MirroredRepeatWrapping = exports.MinEquation = exports.MaxEquation = exports.Math = exports.MOUSE = exports.LuminanceFormat = exports.LuminanceAlphaFormat = exports.LoopRepeat = exports.LoopPingPong = exports.LoopOnce = exports.LogLuvEncoding = exports.LoaderUtils = exports.LinearToneMapping = exports.LinearMipmapNearestFilter = exports.LinearMipmapLinearFilter = exports.LinearMipMapNearestFilter = exports.LinearMipMapLinearFilter = exports.LinearFilter = exports.LinearEncoding = exports.LineStrip = exports.LinePieces = exports.LessStencilFunc = exports.LessEqualStencilFunc = exports.LessEqualDepth = exports.LessDepth = exports.KeepStencilOp = exports.InvertStencilOp = exports.InterpolateSmooth = exports.InterpolateLinear = exports.InterpolateDiscrete = exports.IntType = exports.IncrementWrapStencilOp = exports.IncrementStencilOp = exports.ImageUtils = exports.HalfFloatType = exports.GreaterStencilFunc = exports.GreaterEqualStencilFunc = exports.GreaterEqualDepth = exports.GreaterDepth = exports.GeometryUtils = exports.GammaEncoding = exports.FrontSide = exports.FrontFaceDirectionCW = exports.FrontFaceDirectionCCW = exports.FloatType = exports.FlatShading = exports.FaceColors = exports.EquirectangularRefractionMapping = exports.EquirectangularReflectionMapping = exports.EqualStencilFunc = exports.EqualDepth = exports.DstColorFactor = exports.DstAlphaFactor = exports.DoubleSide = exports.DepthStencilFormat = exports.DepthFormat = exports.DefaultLoadingManager = exports.DecrementWrapStencilOp = exports.DecrementStencilOp = exports.CustomBlending = exports.CullFaceNone = exports.CullFaceFrontBack = exports.CullFaceFront = exports.CullFaceBack = exports.CubeUVRefractionMapping = exports.CubeUVReflectionMapping = exports.CubeRefractionMapping = exports.CubeReflectionMapping = exports.ClampToEdgeWrapping = exports.CineonToneMapping = exports.Cache = exports.ByteType = exports.CubeGeometry = exports.BoxGeometry = exports.BoxBufferGeometry = exports.BasicShadowMap = exports.BasicDepthPacking = exports.BackSide = exports.AudioContext = exports.AnimationUtils = exports.AlwaysStencilFunc = exports.AlwaysDepth = exports.AlphaFormat = exports.AdditiveBlending = exports.AddOperation = exports.AddEquation = exports.ACESFilmicToneMapping = void 0;
  1477. exports.sRGBEncoding = exports.ZeroStencilOp = exports.ZeroSlopeEnding = exports.ZeroFactor = exports.ZeroCurvatureEnding = exports.WrapAroundEnding = exports.VertexColors = exports.VSMShadowMap = exports.UnsignedShortType = exports.UnsignedShort565Type = exports.UnsignedShort5551Type = exports.UnsignedShort4444Type = exports.UnsignedIntType = exports.UnsignedInt248Type = exports.UnsignedByteType = exports.UniformsUtils = exports.UniformsLib = exports.Uncharted2ToneMapping = exports.UVMapping = exports.TrianglesDrawMode = exports.TriangleStripDrawMode = exports.TriangleFanDrawMode = exports.TangentSpaceNormalMap = exports.TOUCH = exports.SubtractiveBlending = exports.SubtractEquation = exports.SrcColorFactor = exports.SrcAlphaSaturateFactor = exports.SrcAlphaFactor = exports.SphericalReflectionMapping = exports.SmoothShading = exports.ShortType = exports.ShapeUtils = exports.ShaderLib = exports.ShaderChunk = exports.SceneUtils = exports.ReverseSubtractEquation = exports.ReplaceStencilOp = exports.RepeatWrapping = exports.ReinhardToneMapping = exports.RedFormat = exports.RGB_S3TC_DXT1_Format = exports.RGB_PVRTC_4BPPV1_Format = exports.RGB_PVRTC_2BPPV1_Format = exports.RGB_ETC1_Format = exports.RGBM7Encoding = exports.RGBM16Encoding = exports.RGBFormat = exports.RGBEFormat = exports.RGBEEncoding = exports.RGBDEncoding = exports.RGBA_S3TC_DXT5_Format = exports.RGBA_S3TC_DXT3_Format = exports.RGBA_S3TC_DXT1_Format = exports.RGBA_PVRTC_4BPPV1_Format = exports.RGBA_PVRTC_2BPPV1_Format = exports.RGBA_ASTC_8x8_Format = exports.RGBA_ASTC_8x6_Format = exports.RGBA_ASTC_8x5_Format = exports.RGBA_ASTC_6x6_Format = exports.RGBA_ASTC_6x5_Format = exports.RGBA_ASTC_5x5_Format = exports.RGBA_ASTC_5x4_Format = exports.RGBA_ASTC_4x4_Format = exports.RGBA_ASTC_12x12_Format = exports.RGBA_ASTC_12x10_Format = exports.RGBA_ASTC_10x8_Format = exports.RGBA_ASTC_10x6_Format = exports.RGBA_ASTC_10x5_Format = exports.RGBA_ASTC_10x10_Format = exports.RGBAFormat = exports.RGBADepthPacking = exports.REVISION = exports.PCFSoftShadowMap = exports.PCFShadowMap = exports.OneMinusSrcColorFactor = exports.OneMinusSrcAlphaFactor = exports.OneMinusDstColorFactor = exports.OneMinusDstAlphaFactor = exports.OneFactor = exports.ObjectSpaceNormalMap = exports.NotEqualStencilFunc = exports.NotEqualDepth = exports.NormalBlending = void 0;
  1478. // Polyfills
  1479. if (Number.EPSILON === undefined) {
  1480. Number.EPSILON = Math.pow(2, -52);
  1481. }
  1482. if (Number.isInteger === undefined) {
  1483. // Missing in IE
  1484. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  1485. Number.isInteger = function (value) {
  1486. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  1487. };
  1488. } //
  1489. if (Math.sign === undefined) {
  1490. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  1491. Math.sign = function (x) {
  1492. return x < 0 ? -1 : x > 0 ? 1 : +x;
  1493. };
  1494. }
  1495. if ('name' in Function.prototype === false) {
  1496. // Missing in IE
  1497. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  1498. Object.defineProperty(Function.prototype, 'name', {
  1499. get: function () {
  1500. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  1501. }
  1502. });
  1503. }
  1504. if (Object.assign === undefined) {
  1505. // Missing in IE
  1506. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  1507. Object.assign = function (target) {
  1508. if (target === undefined || target === null) {
  1509. throw new TypeError('Cannot convert undefined or null to object');
  1510. }
  1511. var output = Object(target);
  1512. for (var index = 1; index < arguments.length; index++) {
  1513. var source = arguments[index];
  1514. if (source !== undefined && source !== null) {
  1515. for (var nextKey in source) {
  1516. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  1517. output[nextKey] = source[nextKey];
  1518. }
  1519. }
  1520. }
  1521. }
  1522. return output;
  1523. };
  1524. }
  1525. var REVISION = '109';
  1526. exports.REVISION = REVISION;
  1527. var MOUSE = {
  1528. LEFT: 0,
  1529. MIDDLE: 1,
  1530. RIGHT: 2,
  1531. ROTATE: 0,
  1532. DOLLY: 1,
  1533. PAN: 2
  1534. };
  1535. exports.MOUSE = MOUSE;
  1536. var TOUCH = {
  1537. ROTATE: 0,
  1538. PAN: 1,
  1539. DOLLY_PAN: 2,
  1540. DOLLY_ROTATE: 3
  1541. };
  1542. exports.TOUCH = TOUCH;
  1543. var CullFaceNone = 0;
  1544. exports.CullFaceNone = CullFaceNone;
  1545. var CullFaceBack = 1;
  1546. exports.CullFaceBack = CullFaceBack;
  1547. var CullFaceFront = 2;
  1548. exports.CullFaceFront = CullFaceFront;
  1549. var CullFaceFrontBack = 3;
  1550. exports.CullFaceFrontBack = CullFaceFrontBack;
  1551. var FrontFaceDirectionCW = 0;
  1552. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  1553. var FrontFaceDirectionCCW = 1;
  1554. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  1555. var BasicShadowMap = 0;
  1556. exports.BasicShadowMap = BasicShadowMap;
  1557. var PCFShadowMap = 1;
  1558. exports.PCFShadowMap = PCFShadowMap;
  1559. var PCFSoftShadowMap = 2;
  1560. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  1561. var VSMShadowMap = 3;
  1562. exports.VSMShadowMap = VSMShadowMap;
  1563. var FrontSide = 0;
  1564. exports.FrontSide = FrontSide;
  1565. var BackSide = 1;
  1566. exports.BackSide = BackSide;
  1567. var DoubleSide = 2;
  1568. exports.DoubleSide = DoubleSide;
  1569. var FlatShading = 1;
  1570. exports.FlatShading = FlatShading;
  1571. var SmoothShading = 2;
  1572. exports.SmoothShading = SmoothShading;
  1573. var NoColors = 0;
  1574. exports.NoColors = NoColors;
  1575. var FaceColors = 1;
  1576. exports.FaceColors = FaceColors;
  1577. var VertexColors = 2;
  1578. exports.VertexColors = VertexColors;
  1579. var NoBlending = 0;
  1580. exports.NoBlending = NoBlending;
  1581. var NormalBlending = 1;
  1582. exports.NormalBlending = NormalBlending;
  1583. var AdditiveBlending = 2;
  1584. exports.AdditiveBlending = AdditiveBlending;
  1585. var SubtractiveBlending = 3;
  1586. exports.SubtractiveBlending = SubtractiveBlending;
  1587. var MultiplyBlending = 4;
  1588. exports.MultiplyBlending = MultiplyBlending;
  1589. var CustomBlending = 5;
  1590. exports.CustomBlending = CustomBlending;
  1591. var AddEquation = 100;
  1592. exports.AddEquation = AddEquation;
  1593. var SubtractEquation = 101;
  1594. exports.SubtractEquation = SubtractEquation;
  1595. var ReverseSubtractEquation = 102;
  1596. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  1597. var MinEquation = 103;
  1598. exports.MinEquation = MinEquation;
  1599. var MaxEquation = 104;
  1600. exports.MaxEquation = MaxEquation;
  1601. var ZeroFactor = 200;
  1602. exports.ZeroFactor = ZeroFactor;
  1603. var OneFactor = 201;
  1604. exports.OneFactor = OneFactor;
  1605. var SrcColorFactor = 202;
  1606. exports.SrcColorFactor = SrcColorFactor;
  1607. var OneMinusSrcColorFactor = 203;
  1608. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  1609. var SrcAlphaFactor = 204;
  1610. exports.SrcAlphaFactor = SrcAlphaFactor;
  1611. var OneMinusSrcAlphaFactor = 205;
  1612. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  1613. var DstAlphaFactor = 206;
  1614. exports.DstAlphaFactor = DstAlphaFactor;
  1615. var OneMinusDstAlphaFactor = 207;
  1616. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  1617. var DstColorFactor = 208;
  1618. exports.DstColorFactor = DstColorFactor;
  1619. var OneMinusDstColorFactor = 209;
  1620. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  1621. var SrcAlphaSaturateFactor = 210;
  1622. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  1623. var NeverDepth = 0;
  1624. exports.NeverDepth = NeverDepth;
  1625. var AlwaysDepth = 1;
  1626. exports.AlwaysDepth = AlwaysDepth;
  1627. var LessDepth = 2;
  1628. exports.LessDepth = LessDepth;
  1629. var LessEqualDepth = 3;
  1630. exports.LessEqualDepth = LessEqualDepth;
  1631. var EqualDepth = 4;
  1632. exports.EqualDepth = EqualDepth;
  1633. var GreaterEqualDepth = 5;
  1634. exports.GreaterEqualDepth = GreaterEqualDepth;
  1635. var GreaterDepth = 6;
  1636. exports.GreaterDepth = GreaterDepth;
  1637. var NotEqualDepth = 7;
  1638. exports.NotEqualDepth = NotEqualDepth;
  1639. var MultiplyOperation = 0;
  1640. exports.MultiplyOperation = MultiplyOperation;
  1641. var MixOperation = 1;
  1642. exports.MixOperation = MixOperation;
  1643. var AddOperation = 2;
  1644. exports.AddOperation = AddOperation;
  1645. var NoToneMapping = 0;
  1646. exports.NoToneMapping = NoToneMapping;
  1647. var LinearToneMapping = 1;
  1648. exports.LinearToneMapping = LinearToneMapping;
  1649. var ReinhardToneMapping = 2;
  1650. exports.ReinhardToneMapping = ReinhardToneMapping;
  1651. var Uncharted2ToneMapping = 3;
  1652. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  1653. var CineonToneMapping = 4;
  1654. exports.CineonToneMapping = CineonToneMapping;
  1655. var ACESFilmicToneMapping = 5;
  1656. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  1657. var UVMapping = 300;
  1658. exports.UVMapping = UVMapping;
  1659. var CubeReflectionMapping = 301;
  1660. exports.CubeReflectionMapping = CubeReflectionMapping;
  1661. var CubeRefractionMapping = 302;
  1662. exports.CubeRefractionMapping = CubeRefractionMapping;
  1663. var EquirectangularReflectionMapping = 303;
  1664. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  1665. var EquirectangularRefractionMapping = 304;
  1666. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  1667. var SphericalReflectionMapping = 305;
  1668. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  1669. var CubeUVReflectionMapping = 306;
  1670. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  1671. var CubeUVRefractionMapping = 307;
  1672. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  1673. var RepeatWrapping = 1000;
  1674. exports.RepeatWrapping = RepeatWrapping;
  1675. var ClampToEdgeWrapping = 1001;
  1676. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  1677. var MirroredRepeatWrapping = 1002;
  1678. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  1679. var NearestFilter = 1003;
  1680. exports.NearestFilter = NearestFilter;
  1681. var NearestMipmapNearestFilter = 1004;
  1682. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  1683. var NearestMipMapNearestFilter = 1004;
  1684. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  1685. var NearestMipmapLinearFilter = 1005;
  1686. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  1687. var NearestMipMapLinearFilter = 1005;
  1688. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  1689. var LinearFilter = 1006;
  1690. exports.LinearFilter = LinearFilter;
  1691. var LinearMipmapNearestFilter = 1007;
  1692. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  1693. var LinearMipMapNearestFilter = 1007;
  1694. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  1695. var LinearMipmapLinearFilter = 1008;
  1696. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  1697. var LinearMipMapLinearFilter = 1008;
  1698. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  1699. var UnsignedByteType = 1009;
  1700. exports.UnsignedByteType = UnsignedByteType;
  1701. var ByteType = 1010;
  1702. exports.ByteType = ByteType;
  1703. var ShortType = 1011;
  1704. exports.ShortType = ShortType;
  1705. var UnsignedShortType = 1012;
  1706. exports.UnsignedShortType = UnsignedShortType;
  1707. var IntType = 1013;
  1708. exports.IntType = IntType;
  1709. var UnsignedIntType = 1014;
  1710. exports.UnsignedIntType = UnsignedIntType;
  1711. var FloatType = 1015;
  1712. exports.FloatType = FloatType;
  1713. var HalfFloatType = 1016;
  1714. exports.HalfFloatType = HalfFloatType;
  1715. var UnsignedShort4444Type = 1017;
  1716. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  1717. var UnsignedShort5551Type = 1018;
  1718. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  1719. var UnsignedShort565Type = 1019;
  1720. exports.UnsignedShort565Type = UnsignedShort565Type;
  1721. var UnsignedInt248Type = 1020;
  1722. exports.UnsignedInt248Type = UnsignedInt248Type;
  1723. var AlphaFormat = 1021;
  1724. exports.AlphaFormat = AlphaFormat;
  1725. var RGBFormat = 1022;
  1726. exports.RGBFormat = RGBFormat;
  1727. var RGBAFormat = 1023;
  1728. exports.RGBAFormat = RGBAFormat;
  1729. var LuminanceFormat = 1024;
  1730. exports.LuminanceFormat = LuminanceFormat;
  1731. var LuminanceAlphaFormat = 1025;
  1732. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  1733. var RGBEFormat = RGBAFormat;
  1734. exports.RGBEFormat = RGBEFormat;
  1735. var DepthFormat = 1026;
  1736. exports.DepthFormat = DepthFormat;
  1737. var DepthStencilFormat = 1027;
  1738. exports.DepthStencilFormat = DepthStencilFormat;
  1739. var RedFormat = 1028;
  1740. exports.RedFormat = RedFormat;
  1741. var RGB_S3TC_DXT1_Format = 33776;
  1742. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  1743. var RGBA_S3TC_DXT1_Format = 33777;
  1744. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  1745. var RGBA_S3TC_DXT3_Format = 33778;
  1746. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  1747. var RGBA_S3TC_DXT5_Format = 33779;
  1748. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  1749. var RGB_PVRTC_4BPPV1_Format = 35840;
  1750. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  1751. var RGB_PVRTC_2BPPV1_Format = 35841;
  1752. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  1753. var RGBA_PVRTC_4BPPV1_Format = 35842;
  1754. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  1755. var RGBA_PVRTC_2BPPV1_Format = 35843;
  1756. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  1757. var RGB_ETC1_Format = 36196;
  1758. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  1759. var RGBA_ASTC_4x4_Format = 37808;
  1760. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  1761. var RGBA_ASTC_5x4_Format = 37809;
  1762. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  1763. var RGBA_ASTC_5x5_Format = 37810;
  1764. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  1765. var RGBA_ASTC_6x5_Format = 37811;
  1766. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  1767. var RGBA_ASTC_6x6_Format = 37812;
  1768. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  1769. var RGBA_ASTC_8x5_Format = 37813;
  1770. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  1771. var RGBA_ASTC_8x6_Format = 37814;
  1772. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  1773. var RGBA_ASTC_8x8_Format = 37815;
  1774. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  1775. var RGBA_ASTC_10x5_Format = 37816;
  1776. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  1777. var RGBA_ASTC_10x6_Format = 37817;
  1778. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  1779. var RGBA_ASTC_10x8_Format = 37818;
  1780. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  1781. var RGBA_ASTC_10x10_Format = 37819;
  1782. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  1783. var RGBA_ASTC_12x10_Format = 37820;
  1784. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  1785. var RGBA_ASTC_12x12_Format = 37821;
  1786. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  1787. var LoopOnce = 2200;
  1788. exports.LoopOnce = LoopOnce;
  1789. var LoopRepeat = 2201;
  1790. exports.LoopRepeat = LoopRepeat;
  1791. var LoopPingPong = 2202;
  1792. exports.LoopPingPong = LoopPingPong;
  1793. var InterpolateDiscrete = 2300;
  1794. exports.InterpolateDiscrete = InterpolateDiscrete;
  1795. var InterpolateLinear = 2301;
  1796. exports.InterpolateLinear = InterpolateLinear;
  1797. var InterpolateSmooth = 2302;
  1798. exports.InterpolateSmooth = InterpolateSmooth;
  1799. var ZeroCurvatureEnding = 2400;
  1800. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  1801. var ZeroSlopeEnding = 2401;
  1802. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  1803. var WrapAroundEnding = 2402;
  1804. exports.WrapAroundEnding = WrapAroundEnding;
  1805. var TrianglesDrawMode = 0;
  1806. exports.TrianglesDrawMode = TrianglesDrawMode;
  1807. var TriangleStripDrawMode = 1;
  1808. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  1809. var TriangleFanDrawMode = 2;
  1810. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  1811. var LinearEncoding = 3000;
  1812. exports.LinearEncoding = LinearEncoding;
  1813. var sRGBEncoding = 3001;
  1814. exports.sRGBEncoding = sRGBEncoding;
  1815. var GammaEncoding = 3007;
  1816. exports.GammaEncoding = GammaEncoding;
  1817. var RGBEEncoding = 3002;
  1818. exports.RGBEEncoding = RGBEEncoding;
  1819. var LogLuvEncoding = 3003;
  1820. exports.LogLuvEncoding = LogLuvEncoding;
  1821. var RGBM7Encoding = 3004;
  1822. exports.RGBM7Encoding = RGBM7Encoding;
  1823. var RGBM16Encoding = 3005;
  1824. exports.RGBM16Encoding = RGBM16Encoding;
  1825. var RGBDEncoding = 3006;
  1826. exports.RGBDEncoding = RGBDEncoding;
  1827. var BasicDepthPacking = 3200;
  1828. exports.BasicDepthPacking = BasicDepthPacking;
  1829. var RGBADepthPacking = 3201;
  1830. exports.RGBADepthPacking = RGBADepthPacking;
  1831. var TangentSpaceNormalMap = 0;
  1832. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  1833. var ObjectSpaceNormalMap = 1;
  1834. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  1835. var ZeroStencilOp = 0;
  1836. exports.ZeroStencilOp = ZeroStencilOp;
  1837. var KeepStencilOp = 7680;
  1838. exports.KeepStencilOp = KeepStencilOp;
  1839. var ReplaceStencilOp = 7681;
  1840. exports.ReplaceStencilOp = ReplaceStencilOp;
  1841. var IncrementStencilOp = 7682;
  1842. exports.IncrementStencilOp = IncrementStencilOp;
  1843. var DecrementStencilOp = 7683;
  1844. exports.DecrementStencilOp = DecrementStencilOp;
  1845. var IncrementWrapStencilOp = 34055;
  1846. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  1847. var DecrementWrapStencilOp = 34056;
  1848. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  1849. var InvertStencilOp = 5386;
  1850. exports.InvertStencilOp = InvertStencilOp;
  1851. var NeverStencilFunc = 512;
  1852. exports.NeverStencilFunc = NeverStencilFunc;
  1853. var LessStencilFunc = 513;
  1854. exports.LessStencilFunc = LessStencilFunc;
  1855. var EqualStencilFunc = 514;
  1856. exports.EqualStencilFunc = EqualStencilFunc;
  1857. var LessEqualStencilFunc = 515;
  1858. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  1859. var GreaterStencilFunc = 516;
  1860. exports.GreaterStencilFunc = GreaterStencilFunc;
  1861. var NotEqualStencilFunc = 517;
  1862. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  1863. var GreaterEqualStencilFunc = 518;
  1864. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  1865. var AlwaysStencilFunc = 519;
  1866. /**
  1867. * https://github.com/mrdoob/eventdispatcher.js/
  1868. */
  1869. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  1870. function EventDispatcher() {}
  1871. Object.assign(EventDispatcher.prototype, {
  1872. addEventListener: function (type, listener) {
  1873. if (this._listeners === undefined) this._listeners = {};
  1874. var listeners = this._listeners;
  1875. if (listeners[type] === undefined) {
  1876. listeners[type] = [];
  1877. }
  1878. if (listeners[type].indexOf(listener) === -1) {
  1879. listeners[type].push(listener);
  1880. }
  1881. },
  1882. hasEventListener: function (type, listener) {
  1883. if (this._listeners === undefined) return false;
  1884. var listeners = this._listeners;
  1885. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  1886. },
  1887. removeEventListener: function (type, listener) {
  1888. if (this._listeners === undefined) return;
  1889. var listeners = this._listeners;
  1890. var listenerArray = listeners[type];
  1891. if (listenerArray !== undefined) {
  1892. var index = listenerArray.indexOf(listener);
  1893. if (index !== -1) {
  1894. listenerArray.splice(index, 1);
  1895. }
  1896. }
  1897. },
  1898. dispatchEvent: function (event) {
  1899. if (this._listeners === undefined) return;
  1900. var listeners = this._listeners;
  1901. var listenerArray = listeners[event.type];
  1902. if (listenerArray !== undefined) {
  1903. event.target = this;
  1904. var array = listenerArray.slice(0);
  1905. for (var i = 0, l = array.length; i < l; i++) {
  1906. array[i].call(this, event);
  1907. }
  1908. }
  1909. }
  1910. });
  1911. /**
  1912. * @author alteredq / http://alteredqualia.com/
  1913. * @author mrdoob / http://mrdoob.com/
  1914. */
  1915. var _lut = [];
  1916. for (var i = 0; i < 256; i++) {
  1917. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  1918. }
  1919. var _Math = {
  1920. DEG2RAD: Math.PI / 180,
  1921. RAD2DEG: 180 / Math.PI,
  1922. generateUUID: function () {
  1923. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1924. var d0 = Math.random() * 0xffffffff | 0;
  1925. var d1 = Math.random() * 0xffffffff | 0;
  1926. var d2 = Math.random() * 0xffffffff | 0;
  1927. var d3 = Math.random() * 0xffffffff | 0;
  1928. 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.
  1929. return uuid.toUpperCase();
  1930. },
  1931. clamp: function (value, min, max) {
  1932. return Math.max(min, Math.min(max, value));
  1933. },
  1934. // compute euclidian modulo of m % n
  1935. // https://en.wikipedia.org/wiki/Modulo_operation
  1936. euclideanModulo: function (n, m) {
  1937. return (n % m + m) % m;
  1938. },
  1939. // Linear mapping from range <a1, a2> to range <b1, b2>
  1940. mapLinear: function (x, a1, a2, b1, b2) {
  1941. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  1942. },
  1943. // https://en.wikipedia.org/wiki/Linear_interpolation
  1944. lerp: function (x, y, t) {
  1945. return (1 - t) * x + t * y;
  1946. },
  1947. // http://en.wikipedia.org/wiki/Smoothstep
  1948. smoothstep: function (x, min, max) {
  1949. if (x <= min) return 0;
  1950. if (x >= max) return 1;
  1951. x = (x - min) / (max - min);
  1952. return x * x * (3 - 2 * x);
  1953. },
  1954. smootherstep: function (x, min, max) {
  1955. if (x <= min) return 0;
  1956. if (x >= max) return 1;
  1957. x = (x - min) / (max - min);
  1958. return x * x * x * (x * (x * 6 - 15) + 10);
  1959. },
  1960. // Random integer from <low, high> interval
  1961. randInt: function (low, high) {
  1962. return low + Math.floor(Math.random() * (high - low + 1));
  1963. },
  1964. // Random float from <low, high> interval
  1965. randFloat: function (low, high) {
  1966. return low + Math.random() * (high - low);
  1967. },
  1968. // Random float from <-range/2, range/2> interval
  1969. randFloatSpread: function (range) {
  1970. return range * (0.5 - Math.random());
  1971. },
  1972. degToRad: function (degrees) {
  1973. return degrees * _Math.DEG2RAD;
  1974. },
  1975. radToDeg: function (radians) {
  1976. return radians * _Math.RAD2DEG;
  1977. },
  1978. isPowerOfTwo: function (value) {
  1979. return (value & value - 1) === 0 && value !== 0;
  1980. },
  1981. ceilPowerOfTwo: function (value) {
  1982. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  1983. },
  1984. floorPowerOfTwo: function (value) {
  1985. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  1986. }
  1987. };
  1988. /**
  1989. * @author mrdoob / http://mrdoob.com/
  1990. * @author philogb / http://blog.thejit.org/
  1991. * @author egraether / http://egraether.com/
  1992. * @author zz85 / http://www.lab4games.net/zz85/blog
  1993. */
  1994. exports.Math = _Math;
  1995. function Vector2(x, y) {
  1996. this.x = x || 0;
  1997. this.y = y || 0;
  1998. }
  1999. Object.defineProperties(Vector2.prototype, {
  2000. "width": {
  2001. get: function () {
  2002. return this.x;
  2003. },
  2004. set: function (value) {
  2005. this.x = value;
  2006. }
  2007. },
  2008. "height": {
  2009. get: function () {
  2010. return this.y;
  2011. },
  2012. set: function (value) {
  2013. this.y = value;
  2014. }
  2015. }
  2016. });
  2017. Object.assign(Vector2.prototype, {
  2018. isVector2: true,
  2019. set: function (x, y) {
  2020. this.x = x;
  2021. this.y = y;
  2022. return this;
  2023. },
  2024. setScalar: function (scalar) {
  2025. this.x = scalar;
  2026. this.y = scalar;
  2027. return this;
  2028. },
  2029. setX: function (x) {
  2030. this.x = x;
  2031. return this;
  2032. },
  2033. setY: function (y) {
  2034. this.y = y;
  2035. return this;
  2036. },
  2037. setComponent: function (index, value) {
  2038. switch (index) {
  2039. case 0:
  2040. this.x = value;
  2041. break;
  2042. case 1:
  2043. this.y = value;
  2044. break;
  2045. default:
  2046. throw new Error('index is out of range: ' + index);
  2047. }
  2048. return this;
  2049. },
  2050. getComponent: function (index) {
  2051. switch (index) {
  2052. case 0:
  2053. return this.x;
  2054. case 1:
  2055. return this.y;
  2056. default:
  2057. throw new Error('index is out of range: ' + index);
  2058. }
  2059. },
  2060. clone: function () {
  2061. return new this.constructor(this.x, this.y);
  2062. },
  2063. copy: function (v) {
  2064. this.x = v.x;
  2065. this.y = v.y;
  2066. return this;
  2067. },
  2068. add: function (v, w) {
  2069. if (w !== undefined) {
  2070. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2071. return this.addVectors(v, w);
  2072. }
  2073. this.x += v.x;
  2074. this.y += v.y;
  2075. return this;
  2076. },
  2077. addScalar: function (s) {
  2078. this.x += s;
  2079. this.y += s;
  2080. return this;
  2081. },
  2082. addVectors: function (a, b) {
  2083. this.x = a.x + b.x;
  2084. this.y = a.y + b.y;
  2085. return this;
  2086. },
  2087. addScaledVector: function (v, s) {
  2088. this.x += v.x * s;
  2089. this.y += v.y * s;
  2090. return this;
  2091. },
  2092. sub: function (v, w) {
  2093. if (w !== undefined) {
  2094. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2095. return this.subVectors(v, w);
  2096. }
  2097. this.x -= v.x;
  2098. this.y -= v.y;
  2099. return this;
  2100. },
  2101. subScalar: function (s) {
  2102. this.x -= s;
  2103. this.y -= s;
  2104. return this;
  2105. },
  2106. subVectors: function (a, b) {
  2107. this.x = a.x - b.x;
  2108. this.y = a.y - b.y;
  2109. return this;
  2110. },
  2111. multiply: function (v) {
  2112. this.x *= v.x;
  2113. this.y *= v.y;
  2114. return this;
  2115. },
  2116. multiplyScalar: function (scalar) {
  2117. this.x *= scalar;
  2118. this.y *= scalar;
  2119. return this;
  2120. },
  2121. divide: function (v) {
  2122. this.x /= v.x;
  2123. this.y /= v.y;
  2124. return this;
  2125. },
  2126. divideScalar: function (scalar) {
  2127. return this.multiplyScalar(1 / scalar);
  2128. },
  2129. applyMatrix3: function (m) {
  2130. var x = this.x,
  2131. y = this.y;
  2132. var e = m.elements;
  2133. this.x = e[0] * x + e[3] * y + e[6];
  2134. this.y = e[1] * x + e[4] * y + e[7];
  2135. return this;
  2136. },
  2137. min: function (v) {
  2138. this.x = Math.min(this.x, v.x);
  2139. this.y = Math.min(this.y, v.y);
  2140. return this;
  2141. },
  2142. max: function (v) {
  2143. this.x = Math.max(this.x, v.x);
  2144. this.y = Math.max(this.y, v.y);
  2145. return this;
  2146. },
  2147. clamp: function (min, max) {
  2148. // assumes min < max, componentwise
  2149. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2150. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2151. return this;
  2152. },
  2153. clampScalar: function (minVal, maxVal) {
  2154. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2155. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2156. return this;
  2157. },
  2158. clampLength: function (min, max) {
  2159. var length = this.length();
  2160. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2161. },
  2162. floor: function () {
  2163. this.x = Math.floor(this.x);
  2164. this.y = Math.floor(this.y);
  2165. return this;
  2166. },
  2167. ceil: function () {
  2168. this.x = Math.ceil(this.x);
  2169. this.y = Math.ceil(this.y);
  2170. return this;
  2171. },
  2172. round: function () {
  2173. this.x = Math.round(this.x);
  2174. this.y = Math.round(this.y);
  2175. return this;
  2176. },
  2177. roundToZero: function () {
  2178. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2179. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2180. return this;
  2181. },
  2182. negate: function () {
  2183. this.x = -this.x;
  2184. this.y = -this.y;
  2185. return this;
  2186. },
  2187. dot: function (v) {
  2188. return this.x * v.x + this.y * v.y;
  2189. },
  2190. cross: function (v) {
  2191. return this.x * v.y - this.y * v.x;
  2192. },
  2193. lengthSq: function () {
  2194. return this.x * this.x + this.y * this.y;
  2195. },
  2196. length: function () {
  2197. return Math.sqrt(this.x * this.x + this.y * this.y);
  2198. },
  2199. manhattanLength: function () {
  2200. return Math.abs(this.x) + Math.abs(this.y);
  2201. },
  2202. normalize: function () {
  2203. return this.divideScalar(this.length() || 1);
  2204. },
  2205. angle: function () {
  2206. // computes the angle in radians with respect to the positive x-axis
  2207. var angle = Math.atan2(this.y, this.x);
  2208. if (angle < 0) angle += 2 * Math.PI;
  2209. return angle;
  2210. },
  2211. distanceTo: function (v) {
  2212. return Math.sqrt(this.distanceToSquared(v));
  2213. },
  2214. distanceToSquared: function (v) {
  2215. var dx = this.x - v.x,
  2216. dy = this.y - v.y;
  2217. return dx * dx + dy * dy;
  2218. },
  2219. manhattanDistanceTo: function (v) {
  2220. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  2221. },
  2222. setLength: function (length) {
  2223. return this.normalize().multiplyScalar(length);
  2224. },
  2225. lerp: function (v, alpha) {
  2226. this.x += (v.x - this.x) * alpha;
  2227. this.y += (v.y - this.y) * alpha;
  2228. return this;
  2229. },
  2230. lerpVectors: function (v1, v2, alpha) {
  2231. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2232. },
  2233. equals: function (v) {
  2234. return v.x === this.x && v.y === this.y;
  2235. },
  2236. fromArray: function (array, offset) {
  2237. if (offset === undefined) offset = 0;
  2238. this.x = array[offset];
  2239. this.y = array[offset + 1];
  2240. return this;
  2241. },
  2242. toArray: function (array, offset) {
  2243. if (array === undefined) array = [];
  2244. if (offset === undefined) offset = 0;
  2245. array[offset] = this.x;
  2246. array[offset + 1] = this.y;
  2247. return array;
  2248. },
  2249. fromBufferAttribute: function (attribute, index, offset) {
  2250. if (offset !== undefined) {
  2251. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  2252. }
  2253. this.x = attribute.getX(index);
  2254. this.y = attribute.getY(index);
  2255. return this;
  2256. },
  2257. rotateAround: function (center, angle) {
  2258. var c = Math.cos(angle),
  2259. s = Math.sin(angle);
  2260. var x = this.x - center.x;
  2261. var y = this.y - center.y;
  2262. this.x = x * c - y * s + center.x;
  2263. this.y = x * s + y * c + center.y;
  2264. return this;
  2265. }
  2266. });
  2267. /**
  2268. * @author mikael emtinger / http://gomo.se/
  2269. * @author alteredq / http://alteredqualia.com/
  2270. * @author WestLangley / http://github.com/WestLangley
  2271. * @author bhouston / http://clara.io
  2272. */
  2273. function Quaternion(x, y, z, w) {
  2274. this._x = x || 0;
  2275. this._y = y || 0;
  2276. this._z = z || 0;
  2277. this._w = w !== undefined ? w : 1;
  2278. }
  2279. Object.assign(Quaternion, {
  2280. slerp: function (qa, qb, qm, t) {
  2281. return qm.copy(qa).slerp(qb, t);
  2282. },
  2283. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2284. // fuzz-free, array-based Quaternion SLERP operation
  2285. var x0 = src0[srcOffset0 + 0],
  2286. y0 = src0[srcOffset0 + 1],
  2287. z0 = src0[srcOffset0 + 2],
  2288. w0 = src0[srcOffset0 + 3],
  2289. x1 = src1[srcOffset1 + 0],
  2290. y1 = src1[srcOffset1 + 1],
  2291. z1 = src1[srcOffset1 + 2],
  2292. w1 = src1[srcOffset1 + 3];
  2293. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2294. var s = 1 - t,
  2295. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2296. dir = cos >= 0 ? 1 : -1,
  2297. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2298. if (sqrSin > Number.EPSILON) {
  2299. var sin = Math.sqrt(sqrSin),
  2300. len = Math.atan2(sin, cos * dir);
  2301. s = Math.sin(s * len) / sin;
  2302. t = Math.sin(t * len) / sin;
  2303. }
  2304. var tDir = t * dir;
  2305. x0 = x0 * s + x1 * tDir;
  2306. y0 = y0 * s + y1 * tDir;
  2307. z0 = z0 * s + z1 * tDir;
  2308. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2309. if (s === 1 - t) {
  2310. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2311. x0 *= f;
  2312. y0 *= f;
  2313. z0 *= f;
  2314. w0 *= f;
  2315. }
  2316. }
  2317. dst[dstOffset] = x0;
  2318. dst[dstOffset + 1] = y0;
  2319. dst[dstOffset + 2] = z0;
  2320. dst[dstOffset + 3] = w0;
  2321. }
  2322. });
  2323. Object.defineProperties(Quaternion.prototype, {
  2324. x: {
  2325. get: function () {
  2326. return this._x;
  2327. },
  2328. set: function (value) {
  2329. this._x = value;
  2330. this._onChangeCallback();
  2331. }
  2332. },
  2333. y: {
  2334. get: function () {
  2335. return this._y;
  2336. },
  2337. set: function (value) {
  2338. this._y = value;
  2339. this._onChangeCallback();
  2340. }
  2341. },
  2342. z: {
  2343. get: function () {
  2344. return this._z;
  2345. },
  2346. set: function (value) {
  2347. this._z = value;
  2348. this._onChangeCallback();
  2349. }
  2350. },
  2351. w: {
  2352. get: function () {
  2353. return this._w;
  2354. },
  2355. set: function (value) {
  2356. this._w = value;
  2357. this._onChangeCallback();
  2358. }
  2359. }
  2360. });
  2361. Object.assign(Quaternion.prototype, {
  2362. isQuaternion: true,
  2363. set: function (x, y, z, w) {
  2364. this._x = x;
  2365. this._y = y;
  2366. this._z = z;
  2367. this._w = w;
  2368. this._onChangeCallback();
  2369. return this;
  2370. },
  2371. clone: function () {
  2372. return new this.constructor(this._x, this._y, this._z, this._w);
  2373. },
  2374. copy: function (quaternion) {
  2375. this._x = quaternion.x;
  2376. this._y = quaternion.y;
  2377. this._z = quaternion.z;
  2378. this._w = quaternion.w;
  2379. this._onChangeCallback();
  2380. return this;
  2381. },
  2382. setFromEuler: function (euler, update) {
  2383. if (!(euler && euler.isEuler)) {
  2384. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2385. }
  2386. var x = euler._x,
  2387. y = euler._y,
  2388. z = euler._z,
  2389. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2390. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2391. // content/SpinCalc.m
  2392. var cos = Math.cos;
  2393. var sin = Math.sin;
  2394. var c1 = cos(x / 2);
  2395. var c2 = cos(y / 2);
  2396. var c3 = cos(z / 2);
  2397. var s1 = sin(x / 2);
  2398. var s2 = sin(y / 2);
  2399. var s3 = sin(z / 2);
  2400. if (order === 'XYZ') {
  2401. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2402. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2403. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2404. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2405. } else if (order === 'YXZ') {
  2406. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2407. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2408. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2409. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2410. } else if (order === 'ZXY') {
  2411. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2412. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2413. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2414. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2415. } else if (order === 'ZYX') {
  2416. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2417. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2418. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2419. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2420. } else if (order === 'YZX') {
  2421. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2422. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2423. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2424. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2425. } else if (order === 'XZY') {
  2426. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2427. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2428. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2429. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2430. }
  2431. if (update !== false) this._onChangeCallback();
  2432. return this;
  2433. },
  2434. setFromAxisAngle: function (axis, angle) {
  2435. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2436. // assumes axis is normalized
  2437. var halfAngle = angle / 2,
  2438. s = Math.sin(halfAngle);
  2439. this._x = axis.x * s;
  2440. this._y = axis.y * s;
  2441. this._z = axis.z * s;
  2442. this._w = Math.cos(halfAngle);
  2443. this._onChangeCallback();
  2444. return this;
  2445. },
  2446. setFromRotationMatrix: function (m) {
  2447. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2448. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2449. var te = m.elements,
  2450. m11 = te[0],
  2451. m12 = te[4],
  2452. m13 = te[8],
  2453. m21 = te[1],
  2454. m22 = te[5],
  2455. m23 = te[9],
  2456. m31 = te[2],
  2457. m32 = te[6],
  2458. m33 = te[10],
  2459. trace = m11 + m22 + m33,
  2460. s;
  2461. if (trace > 0) {
  2462. s = 0.5 / Math.sqrt(trace + 1.0);
  2463. this._w = 0.25 / s;
  2464. this._x = (m32 - m23) * s;
  2465. this._y = (m13 - m31) * s;
  2466. this._z = (m21 - m12) * s;
  2467. } else if (m11 > m22 && m11 > m33) {
  2468. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2469. this._w = (m32 - m23) / s;
  2470. this._x = 0.25 * s;
  2471. this._y = (m12 + m21) / s;
  2472. this._z = (m13 + m31) / s;
  2473. } else if (m22 > m33) {
  2474. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2475. this._w = (m13 - m31) / s;
  2476. this._x = (m12 + m21) / s;
  2477. this._y = 0.25 * s;
  2478. this._z = (m23 + m32) / s;
  2479. } else {
  2480. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2481. this._w = (m21 - m12) / s;
  2482. this._x = (m13 + m31) / s;
  2483. this._y = (m23 + m32) / s;
  2484. this._z = 0.25 * s;
  2485. }
  2486. this._onChangeCallback();
  2487. return this;
  2488. },
  2489. setFromUnitVectors: function (vFrom, vTo) {
  2490. // assumes direction vectors vFrom and vTo are normalized
  2491. var EPS = 0.000001;
  2492. var r = vFrom.dot(vTo) + 1;
  2493. if (r < EPS) {
  2494. r = 0;
  2495. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2496. this._x = -vFrom.y;
  2497. this._y = vFrom.x;
  2498. this._z = 0;
  2499. this._w = r;
  2500. } else {
  2501. this._x = 0;
  2502. this._y = -vFrom.z;
  2503. this._z = vFrom.y;
  2504. this._w = r;
  2505. }
  2506. } else {
  2507. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2508. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2509. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2510. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2511. this._w = r;
  2512. }
  2513. return this.normalize();
  2514. },
  2515. angleTo: function (q) {
  2516. return 2 * Math.acos(Math.abs(_Math.clamp(this.dot(q), -1, 1)));
  2517. },
  2518. rotateTowards: function (q, step) {
  2519. var angle = this.angleTo(q);
  2520. if (angle === 0) return this;
  2521. var t = Math.min(1, step / angle);
  2522. this.slerp(q, t);
  2523. return this;
  2524. },
  2525. inverse: function () {
  2526. // quaternion is assumed to have unit length
  2527. return this.conjugate();
  2528. },
  2529. conjugate: function () {
  2530. this._x *= -1;
  2531. this._y *= -1;
  2532. this._z *= -1;
  2533. this._onChangeCallback();
  2534. return this;
  2535. },
  2536. dot: function (v) {
  2537. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2538. },
  2539. lengthSq: function () {
  2540. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2541. },
  2542. length: function () {
  2543. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2544. },
  2545. normalize: function () {
  2546. var l = this.length();
  2547. if (l === 0) {
  2548. this._x = 0;
  2549. this._y = 0;
  2550. this._z = 0;
  2551. this._w = 1;
  2552. } else {
  2553. l = 1 / l;
  2554. this._x = this._x * l;
  2555. this._y = this._y * l;
  2556. this._z = this._z * l;
  2557. this._w = this._w * l;
  2558. }
  2559. this._onChangeCallback();
  2560. return this;
  2561. },
  2562. multiply: function (q, p) {
  2563. if (p !== undefined) {
  2564. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2565. return this.multiplyQuaternions(q, p);
  2566. }
  2567. return this.multiplyQuaternions(this, q);
  2568. },
  2569. premultiply: function (q) {
  2570. return this.multiplyQuaternions(q, this);
  2571. },
  2572. multiplyQuaternions: function (a, b) {
  2573. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2574. var qax = a._x,
  2575. qay = a._y,
  2576. qaz = a._z,
  2577. qaw = a._w;
  2578. var qbx = b._x,
  2579. qby = b._y,
  2580. qbz = b._z,
  2581. qbw = b._w;
  2582. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2583. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2584. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2585. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2586. this._onChangeCallback();
  2587. return this;
  2588. },
  2589. slerp: function (qb, t) {
  2590. if (t === 0) return this;
  2591. if (t === 1) return this.copy(qb);
  2592. var x = this._x,
  2593. y = this._y,
  2594. z = this._z,
  2595. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2596. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2597. if (cosHalfTheta < 0) {
  2598. this._w = -qb._w;
  2599. this._x = -qb._x;
  2600. this._y = -qb._y;
  2601. this._z = -qb._z;
  2602. cosHalfTheta = -cosHalfTheta;
  2603. } else {
  2604. this.copy(qb);
  2605. }
  2606. if (cosHalfTheta >= 1.0) {
  2607. this._w = w;
  2608. this._x = x;
  2609. this._y = y;
  2610. this._z = z;
  2611. return this;
  2612. }
  2613. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2614. if (sqrSinHalfTheta <= Number.EPSILON) {
  2615. var s = 1 - t;
  2616. this._w = s * w + t * this._w;
  2617. this._x = s * x + t * this._x;
  2618. this._y = s * y + t * this._y;
  2619. this._z = s * z + t * this._z;
  2620. this.normalize();
  2621. this._onChangeCallback();
  2622. return this;
  2623. }
  2624. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2625. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2626. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2627. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2628. this._w = w * ratioA + this._w * ratioB;
  2629. this._x = x * ratioA + this._x * ratioB;
  2630. this._y = y * ratioA + this._y * ratioB;
  2631. this._z = z * ratioA + this._z * ratioB;
  2632. this._onChangeCallback();
  2633. return this;
  2634. },
  2635. equals: function (quaternion) {
  2636. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2637. },
  2638. fromArray: function (array, offset) {
  2639. if (offset === undefined) offset = 0;
  2640. this._x = array[offset];
  2641. this._y = array[offset + 1];
  2642. this._z = array[offset + 2];
  2643. this._w = array[offset + 3];
  2644. this._onChangeCallback();
  2645. return this;
  2646. },
  2647. toArray: function (array, offset) {
  2648. if (array === undefined) array = [];
  2649. if (offset === undefined) offset = 0;
  2650. array[offset] = this._x;
  2651. array[offset + 1] = this._y;
  2652. array[offset + 2] = this._z;
  2653. array[offset + 3] = this._w;
  2654. return array;
  2655. },
  2656. _onChange: function (callback) {
  2657. this._onChangeCallback = callback;
  2658. return this;
  2659. },
  2660. _onChangeCallback: function () {}
  2661. });
  2662. /**
  2663. * @author mrdoob / http://mrdoob.com/
  2664. * @author kile / http://kile.stravaganza.org/
  2665. * @author philogb / http://blog.thejit.org/
  2666. * @author mikael emtinger / http://gomo.se/
  2667. * @author egraether / http://egraether.com/
  2668. * @author WestLangley / http://github.com/WestLangley
  2669. */
  2670. var _vector = new Vector3();
  2671. var _quaternion = new Quaternion();
  2672. function Vector3(x, y, z) {
  2673. this.x = x || 0;
  2674. this.y = y || 0;
  2675. this.z = z || 0;
  2676. }
  2677. Object.assign(Vector3.prototype, {
  2678. isVector3: true,
  2679. set: function (x, y, z) {
  2680. this.x = x;
  2681. this.y = y;
  2682. this.z = z;
  2683. return this;
  2684. },
  2685. setScalar: function (scalar) {
  2686. this.x = scalar;
  2687. this.y = scalar;
  2688. this.z = scalar;
  2689. return this;
  2690. },
  2691. setX: function (x) {
  2692. this.x = x;
  2693. return this;
  2694. },
  2695. setY: function (y) {
  2696. this.y = y;
  2697. return this;
  2698. },
  2699. setZ: function (z) {
  2700. this.z = z;
  2701. return this;
  2702. },
  2703. setComponent: function (index, value) {
  2704. switch (index) {
  2705. case 0:
  2706. this.x = value;
  2707. break;
  2708. case 1:
  2709. this.y = value;
  2710. break;
  2711. case 2:
  2712. this.z = value;
  2713. break;
  2714. default:
  2715. throw new Error('index is out of range: ' + index);
  2716. }
  2717. return this;
  2718. },
  2719. getComponent: function (index) {
  2720. switch (index) {
  2721. case 0:
  2722. return this.x;
  2723. case 1:
  2724. return this.y;
  2725. case 2:
  2726. return this.z;
  2727. default:
  2728. throw new Error('index is out of range: ' + index);
  2729. }
  2730. },
  2731. clone: function () {
  2732. return new this.constructor(this.x, this.y, this.z);
  2733. },
  2734. copy: function (v) {
  2735. this.x = v.x;
  2736. this.y = v.y;
  2737. this.z = v.z;
  2738. return this;
  2739. },
  2740. add: function (v, w) {
  2741. if (w !== undefined) {
  2742. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2743. return this.addVectors(v, w);
  2744. }
  2745. this.x += v.x;
  2746. this.y += v.y;
  2747. this.z += v.z;
  2748. return this;
  2749. },
  2750. addScalar: function (s) {
  2751. this.x += s;
  2752. this.y += s;
  2753. this.z += s;
  2754. return this;
  2755. },
  2756. addVectors: function (a, b) {
  2757. this.x = a.x + b.x;
  2758. this.y = a.y + b.y;
  2759. this.z = a.z + b.z;
  2760. return this;
  2761. },
  2762. addScaledVector: function (v, s) {
  2763. this.x += v.x * s;
  2764. this.y += v.y * s;
  2765. this.z += v.z * s;
  2766. return this;
  2767. },
  2768. sub: function (v, w) {
  2769. if (w !== undefined) {
  2770. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2771. return this.subVectors(v, w);
  2772. }
  2773. this.x -= v.x;
  2774. this.y -= v.y;
  2775. this.z -= v.z;
  2776. return this;
  2777. },
  2778. subScalar: function (s) {
  2779. this.x -= s;
  2780. this.y -= s;
  2781. this.z -= s;
  2782. return this;
  2783. },
  2784. subVectors: function (a, b) {
  2785. this.x = a.x - b.x;
  2786. this.y = a.y - b.y;
  2787. this.z = a.z - b.z;
  2788. return this;
  2789. },
  2790. multiply: function (v, w) {
  2791. if (w !== undefined) {
  2792. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2793. return this.multiplyVectors(v, w);
  2794. }
  2795. this.x *= v.x;
  2796. this.y *= v.y;
  2797. this.z *= v.z;
  2798. return this;
  2799. },
  2800. multiplyScalar: function (scalar) {
  2801. this.x *= scalar;
  2802. this.y *= scalar;
  2803. this.z *= scalar;
  2804. return this;
  2805. },
  2806. multiplyVectors: function (a, b) {
  2807. this.x = a.x * b.x;
  2808. this.y = a.y * b.y;
  2809. this.z = a.z * b.z;
  2810. return this;
  2811. },
  2812. applyEuler: function (euler) {
  2813. if (!(euler && euler.isEuler)) {
  2814. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2815. }
  2816. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2817. },
  2818. applyAxisAngle: function (axis, angle) {
  2819. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2820. },
  2821. applyMatrix3: function (m) {
  2822. var x = this.x,
  2823. y = this.y,
  2824. z = this.z;
  2825. var e = m.elements;
  2826. this.x = e[0] * x + e[3] * y + e[6] * z;
  2827. this.y = e[1] * x + e[4] * y + e[7] * z;
  2828. this.z = e[2] * x + e[5] * y + e[8] * z;
  2829. return this;
  2830. },
  2831. applyMatrix4: function (m) {
  2832. var x = this.x,
  2833. y = this.y,
  2834. z = this.z;
  2835. var e = m.elements;
  2836. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2837. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2838. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2839. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2840. return this;
  2841. },
  2842. applyQuaternion: function (q) {
  2843. var x = this.x,
  2844. y = this.y,
  2845. z = this.z;
  2846. var qx = q.x,
  2847. qy = q.y,
  2848. qz = q.z,
  2849. qw = q.w; // calculate quat * vector
  2850. var ix = qw * x + qy * z - qz * y;
  2851. var iy = qw * y + qz * x - qx * z;
  2852. var iz = qw * z + qx * y - qy * x;
  2853. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2854. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2855. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2856. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2857. return this;
  2858. },
  2859. project: function (camera) {
  2860. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2861. },
  2862. unproject: function (camera) {
  2863. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2864. },
  2865. transformDirection: function (m) {
  2866. // input: THREE.Matrix4 affine matrix
  2867. // vector interpreted as a direction
  2868. var x = this.x,
  2869. y = this.y,
  2870. z = this.z;
  2871. var e = m.elements;
  2872. this.x = e[0] * x + e[4] * y + e[8] * z;
  2873. this.y = e[1] * x + e[5] * y + e[9] * z;
  2874. this.z = e[2] * x + e[6] * y + e[10] * z;
  2875. return this.normalize();
  2876. },
  2877. divide: function (v) {
  2878. this.x /= v.x;
  2879. this.y /= v.y;
  2880. this.z /= v.z;
  2881. return this;
  2882. },
  2883. divideScalar: function (scalar) {
  2884. return this.multiplyScalar(1 / scalar);
  2885. },
  2886. min: function (v) {
  2887. this.x = Math.min(this.x, v.x);
  2888. this.y = Math.min(this.y, v.y);
  2889. this.z = Math.min(this.z, v.z);
  2890. return this;
  2891. },
  2892. max: function (v) {
  2893. this.x = Math.max(this.x, v.x);
  2894. this.y = Math.max(this.y, v.y);
  2895. this.z = Math.max(this.z, v.z);
  2896. return this;
  2897. },
  2898. clamp: function (min, max) {
  2899. // assumes min < max, componentwise
  2900. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2901. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2902. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2903. return this;
  2904. },
  2905. clampScalar: function (minVal, maxVal) {
  2906. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2907. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2908. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2909. return this;
  2910. },
  2911. clampLength: function (min, max) {
  2912. var length = this.length();
  2913. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2914. },
  2915. floor: function () {
  2916. this.x = Math.floor(this.x);
  2917. this.y = Math.floor(this.y);
  2918. this.z = Math.floor(this.z);
  2919. return this;
  2920. },
  2921. ceil: function () {
  2922. this.x = Math.ceil(this.x);
  2923. this.y = Math.ceil(this.y);
  2924. this.z = Math.ceil(this.z);
  2925. return this;
  2926. },
  2927. round: function () {
  2928. this.x = Math.round(this.x);
  2929. this.y = Math.round(this.y);
  2930. this.z = Math.round(this.z);
  2931. return this;
  2932. },
  2933. roundToZero: function () {
  2934. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2935. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2936. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2937. return this;
  2938. },
  2939. negate: function () {
  2940. this.x = -this.x;
  2941. this.y = -this.y;
  2942. this.z = -this.z;
  2943. return this;
  2944. },
  2945. dot: function (v) {
  2946. return this.x * v.x + this.y * v.y + this.z * v.z;
  2947. },
  2948. // TODO lengthSquared?
  2949. lengthSq: function () {
  2950. return this.x * this.x + this.y * this.y + this.z * this.z;
  2951. },
  2952. length: function () {
  2953. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2954. },
  2955. manhattanLength: function () {
  2956. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2957. },
  2958. normalize: function () {
  2959. return this.divideScalar(this.length() || 1);
  2960. },
  2961. setLength: function (length) {
  2962. return this.normalize().multiplyScalar(length);
  2963. },
  2964. lerp: function (v, alpha) {
  2965. this.x += (v.x - this.x) * alpha;
  2966. this.y += (v.y - this.y) * alpha;
  2967. this.z += (v.z - this.z) * alpha;
  2968. return this;
  2969. },
  2970. lerpVectors: function (v1, v2, alpha) {
  2971. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2972. },
  2973. cross: function (v, w) {
  2974. if (w !== undefined) {
  2975. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2976. return this.crossVectors(v, w);
  2977. }
  2978. return this.crossVectors(this, v);
  2979. },
  2980. crossVectors: function (a, b) {
  2981. var ax = a.x,
  2982. ay = a.y,
  2983. az = a.z;
  2984. var bx = b.x,
  2985. by = b.y,
  2986. bz = b.z;
  2987. this.x = ay * bz - az * by;
  2988. this.y = az * bx - ax * bz;
  2989. this.z = ax * by - ay * bx;
  2990. return this;
  2991. },
  2992. projectOnVector: function (v) {
  2993. // v cannot be the zero v
  2994. var scalar = v.dot(this) / v.lengthSq();
  2995. return this.copy(v).multiplyScalar(scalar);
  2996. },
  2997. projectOnPlane: function (planeNormal) {
  2998. _vector.copy(this).projectOnVector(planeNormal);
  2999. return this.sub(_vector);
  3000. },
  3001. reflect: function (normal) {
  3002. // reflect incident vector off plane orthogonal to normal
  3003. // normal is assumed to have unit length
  3004. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  3005. },
  3006. angleTo: function (v) {
  3007. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  3008. if (denominator === 0) console.error('THREE.Vector3: angleTo() can\'t handle zero length vectors.');
  3009. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  3010. return Math.acos(_Math.clamp(theta, -1, 1));
  3011. },
  3012. distanceTo: function (v) {
  3013. return Math.sqrt(this.distanceToSquared(v));
  3014. },
  3015. distanceToSquared: function (v) {
  3016. var dx = this.x - v.x,
  3017. dy = this.y - v.y,
  3018. dz = this.z - v.z;
  3019. return dx * dx + dy * dy + dz * dz;
  3020. },
  3021. manhattanDistanceTo: function (v) {
  3022. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  3023. },
  3024. setFromSpherical: function (s) {
  3025. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3026. },
  3027. setFromSphericalCoords: function (radius, phi, theta) {
  3028. var sinPhiRadius = Math.sin(phi) * radius;
  3029. this.x = sinPhiRadius * Math.sin(theta);
  3030. this.y = Math.cos(phi) * radius;
  3031. this.z = sinPhiRadius * Math.cos(theta);
  3032. return this;
  3033. },
  3034. setFromCylindrical: function (c) {
  3035. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3036. },
  3037. setFromCylindricalCoords: function (radius, theta, y) {
  3038. this.x = radius * Math.sin(theta);
  3039. this.y = y;
  3040. this.z = radius * Math.cos(theta);
  3041. return this;
  3042. },
  3043. setFromMatrixPosition: function (m) {
  3044. var e = m.elements;
  3045. this.x = e[12];
  3046. this.y = e[13];
  3047. this.z = e[14];
  3048. return this;
  3049. },
  3050. setFromMatrixScale: function (m) {
  3051. var sx = this.setFromMatrixColumn(m, 0).length();
  3052. var sy = this.setFromMatrixColumn(m, 1).length();
  3053. var sz = this.setFromMatrixColumn(m, 2).length();
  3054. this.x = sx;
  3055. this.y = sy;
  3056. this.z = sz;
  3057. return this;
  3058. },
  3059. setFromMatrixColumn: function (m, index) {
  3060. return this.fromArray(m.elements, index * 4);
  3061. },
  3062. equals: function (v) {
  3063. return v.x === this.x && v.y === this.y && v.z === this.z;
  3064. },
  3065. fromArray: function (array, offset) {
  3066. if (offset === undefined) offset = 0;
  3067. this.x = array[offset];
  3068. this.y = array[offset + 1];
  3069. this.z = array[offset + 2];
  3070. return this;
  3071. },
  3072. toArray: function (array, offset) {
  3073. if (array === undefined) array = [];
  3074. if (offset === undefined) offset = 0;
  3075. array[offset] = this.x;
  3076. array[offset + 1] = this.y;
  3077. array[offset + 2] = this.z;
  3078. return array;
  3079. },
  3080. fromBufferAttribute: function (attribute, index, offset) {
  3081. if (offset !== undefined) {
  3082. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  3083. }
  3084. this.x = attribute.getX(index);
  3085. this.y = attribute.getY(index);
  3086. this.z = attribute.getZ(index);
  3087. return this;
  3088. }
  3089. });
  3090. /**
  3091. * @author alteredq / http://alteredqualia.com/
  3092. * @author WestLangley / http://github.com/WestLangley
  3093. * @author bhouston / http://clara.io
  3094. * @author tschw
  3095. */
  3096. var _vector$1 = new Vector3();
  3097. function Matrix3() {
  3098. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3099. if (arguments.length > 0) {
  3100. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  3101. }
  3102. }
  3103. Object.assign(Matrix3.prototype, {
  3104. isMatrix3: true,
  3105. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  3106. var te = this.elements;
  3107. te[0] = n11;
  3108. te[1] = n21;
  3109. te[2] = n31;
  3110. te[3] = n12;
  3111. te[4] = n22;
  3112. te[5] = n32;
  3113. te[6] = n13;
  3114. te[7] = n23;
  3115. te[8] = n33;
  3116. return this;
  3117. },
  3118. identity: function () {
  3119. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  3120. return this;
  3121. },
  3122. clone: function () {
  3123. return new this.constructor().fromArray(this.elements);
  3124. },
  3125. copy: function (m) {
  3126. var te = this.elements;
  3127. var me = m.elements;
  3128. te[0] = me[0];
  3129. te[1] = me[1];
  3130. te[2] = me[2];
  3131. te[3] = me[3];
  3132. te[4] = me[4];
  3133. te[5] = me[5];
  3134. te[6] = me[6];
  3135. te[7] = me[7];
  3136. te[8] = me[8];
  3137. return this;
  3138. },
  3139. setFromMatrix4: function (m) {
  3140. var me = m.elements;
  3141. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  3142. return this;
  3143. },
  3144. applyToBufferAttribute: function (attribute) {
  3145. for (var i = 0, l = attribute.count; i < l; i++) {
  3146. _vector$1.x = attribute.getX(i);
  3147. _vector$1.y = attribute.getY(i);
  3148. _vector$1.z = attribute.getZ(i);
  3149. _vector$1.applyMatrix3(this);
  3150. attribute.setXYZ(i, _vector$1.x, _vector$1.y, _vector$1.z);
  3151. }
  3152. return attribute;
  3153. },
  3154. multiply: function (m) {
  3155. return this.multiplyMatrices(this, m);
  3156. },
  3157. premultiply: function (m) {
  3158. return this.multiplyMatrices(m, this);
  3159. },
  3160. multiplyMatrices: function (a, b) {
  3161. var ae = a.elements;
  3162. var be = b.elements;
  3163. var te = this.elements;
  3164. var a11 = ae[0],
  3165. a12 = ae[3],
  3166. a13 = ae[6];
  3167. var a21 = ae[1],
  3168. a22 = ae[4],
  3169. a23 = ae[7];
  3170. var a31 = ae[2],
  3171. a32 = ae[5],
  3172. a33 = ae[8];
  3173. var b11 = be[0],
  3174. b12 = be[3],
  3175. b13 = be[6];
  3176. var b21 = be[1],
  3177. b22 = be[4],
  3178. b23 = be[7];
  3179. var b31 = be[2],
  3180. b32 = be[5],
  3181. b33 = be[8];
  3182. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  3183. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  3184. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  3185. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  3186. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  3187. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  3188. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  3189. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  3190. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  3191. return this;
  3192. },
  3193. multiplyScalar: function (s) {
  3194. var te = this.elements;
  3195. te[0] *= s;
  3196. te[3] *= s;
  3197. te[6] *= s;
  3198. te[1] *= s;
  3199. te[4] *= s;
  3200. te[7] *= s;
  3201. te[2] *= s;
  3202. te[5] *= s;
  3203. te[8] *= s;
  3204. return this;
  3205. },
  3206. determinant: function () {
  3207. var te = this.elements;
  3208. var a = te[0],
  3209. b = te[1],
  3210. c = te[2],
  3211. d = te[3],
  3212. e = te[4],
  3213. f = te[5],
  3214. g = te[6],
  3215. h = te[7],
  3216. i = te[8];
  3217. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  3218. },
  3219. getInverse: function (matrix, throwOnDegenerate) {
  3220. if (matrix && matrix.isMatrix4) {
  3221. console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");
  3222. }
  3223. var me = matrix.elements,
  3224. te = this.elements,
  3225. n11 = me[0],
  3226. n21 = me[1],
  3227. n31 = me[2],
  3228. n12 = me[3],
  3229. n22 = me[4],
  3230. n32 = me[5],
  3231. n13 = me[6],
  3232. n23 = me[7],
  3233. n33 = me[8],
  3234. t11 = n33 * n22 - n32 * n23,
  3235. t12 = n32 * n13 - n33 * n12,
  3236. t13 = n23 * n12 - n22 * n13,
  3237. det = n11 * t11 + n21 * t12 + n31 * t13;
  3238. if (det === 0) {
  3239. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  3240. if (throwOnDegenerate === true) {
  3241. throw new Error(msg);
  3242. } else {
  3243. console.warn(msg);
  3244. }
  3245. return this.identity();
  3246. }
  3247. var detInv = 1 / det;
  3248. te[0] = t11 * detInv;
  3249. te[1] = (n31 * n23 - n33 * n21) * detInv;
  3250. te[2] = (n32 * n21 - n31 * n22) * detInv;
  3251. te[3] = t12 * detInv;
  3252. te[4] = (n33 * n11 - n31 * n13) * detInv;
  3253. te[5] = (n31 * n12 - n32 * n11) * detInv;
  3254. te[6] = t13 * detInv;
  3255. te[7] = (n21 * n13 - n23 * n11) * detInv;
  3256. te[8] = (n22 * n11 - n21 * n12) * detInv;
  3257. return this;
  3258. },
  3259. transpose: function () {
  3260. var tmp,
  3261. m = this.elements;
  3262. tmp = m[1];
  3263. m[1] = m[3];
  3264. m[3] = tmp;
  3265. tmp = m[2];
  3266. m[2] = m[6];
  3267. m[6] = tmp;
  3268. tmp = m[5];
  3269. m[5] = m[7];
  3270. m[7] = tmp;
  3271. return this;
  3272. },
  3273. getNormalMatrix: function (matrix4) {
  3274. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  3275. },
  3276. transposeIntoArray: function (r) {
  3277. var m = this.elements;
  3278. r[0] = m[0];
  3279. r[1] = m[3];
  3280. r[2] = m[6];
  3281. r[3] = m[1];
  3282. r[4] = m[4];
  3283. r[5] = m[7];
  3284. r[6] = m[2];
  3285. r[7] = m[5];
  3286. r[8] = m[8];
  3287. return this;
  3288. },
  3289. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  3290. var c = Math.cos(rotation);
  3291. var s = Math.sin(rotation);
  3292. 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);
  3293. },
  3294. scale: function (sx, sy) {
  3295. var te = this.elements;
  3296. te[0] *= sx;
  3297. te[3] *= sx;
  3298. te[6] *= sx;
  3299. te[1] *= sy;
  3300. te[4] *= sy;
  3301. te[7] *= sy;
  3302. return this;
  3303. },
  3304. rotate: function (theta) {
  3305. var c = Math.cos(theta);
  3306. var s = Math.sin(theta);
  3307. var te = this.elements;
  3308. var a11 = te[0],
  3309. a12 = te[3],
  3310. a13 = te[6];
  3311. var a21 = te[1],
  3312. a22 = te[4],
  3313. a23 = te[7];
  3314. te[0] = c * a11 + s * a21;
  3315. te[3] = c * a12 + s * a22;
  3316. te[6] = c * a13 + s * a23;
  3317. te[1] = -s * a11 + c * a21;
  3318. te[4] = -s * a12 + c * a22;
  3319. te[7] = -s * a13 + c * a23;
  3320. return this;
  3321. },
  3322. translate: function (tx, ty) {
  3323. var te = this.elements;
  3324. te[0] += tx * te[2];
  3325. te[3] += tx * te[5];
  3326. te[6] += tx * te[8];
  3327. te[1] += ty * te[2];
  3328. te[4] += ty * te[5];
  3329. te[7] += ty * te[8];
  3330. return this;
  3331. },
  3332. equals: function (matrix) {
  3333. var te = this.elements;
  3334. var me = matrix.elements;
  3335. for (var i = 0; i < 9; i++) {
  3336. if (te[i] !== me[i]) return false;
  3337. }
  3338. return true;
  3339. },
  3340. fromArray: function (array, offset) {
  3341. if (offset === undefined) offset = 0;
  3342. for (var i = 0; i < 9; i++) {
  3343. this.elements[i] = array[i + offset];
  3344. }
  3345. return this;
  3346. },
  3347. toArray: function (array, offset) {
  3348. if (array === undefined) array = [];
  3349. if (offset === undefined) offset = 0;
  3350. var te = this.elements;
  3351. array[offset] = te[0];
  3352. array[offset + 1] = te[1];
  3353. array[offset + 2] = te[2];
  3354. array[offset + 3] = te[3];
  3355. array[offset + 4] = te[4];
  3356. array[offset + 5] = te[5];
  3357. array[offset + 6] = te[6];
  3358. array[offset + 7] = te[7];
  3359. array[offset + 8] = te[8];
  3360. return array;
  3361. }
  3362. });
  3363. /**
  3364. * @author mrdoob / http://mrdoob.com/
  3365. * @author alteredq / http://alteredqualia.com/
  3366. * @author szimek / https://github.com/szimek/
  3367. */
  3368. var _canvas;
  3369. var ImageUtils = {
  3370. getDataURL: function (image) {
  3371. var canvas;
  3372. if (typeof HTMLCanvasElement == 'undefined') {
  3373. return image.src;
  3374. } else if (image instanceof HTMLCanvasElement) {
  3375. canvas = image;
  3376. } else {
  3377. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  3378. _canvas.width = image.width;
  3379. _canvas.height = image.height;
  3380. var context = _canvas.getContext('2d');
  3381. if (image instanceof ImageData) {
  3382. context.putImageData(image, 0, 0);
  3383. } else {
  3384. context.drawImage(image, 0, 0, image.width, image.height);
  3385. }
  3386. canvas = _canvas;
  3387. }
  3388. if (canvas.width > 2048 || canvas.height > 2048) {
  3389. return canvas.toDataURL('image/jpeg', 0.6);
  3390. } else {
  3391. return canvas.toDataURL('image/png');
  3392. }
  3393. }
  3394. };
  3395. /**
  3396. * @author mrdoob / http://mrdoob.com/
  3397. * @author alteredq / http://alteredqualia.com/
  3398. * @author szimek / https://github.com/szimek/
  3399. */
  3400. exports.ImageUtils = ImageUtils;
  3401. var textureId = 0;
  3402. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  3403. Object.defineProperty(this, 'id', {
  3404. value: textureId++
  3405. });
  3406. this.uuid = _Math.generateUUID();
  3407. this.name = '';
  3408. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  3409. this.mipmaps = [];
  3410. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  3411. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  3412. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  3413. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  3414. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  3415. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  3416. this.format = format !== undefined ? format : RGBAFormat;
  3417. this.type = type !== undefined ? type : UnsignedByteType;
  3418. this.offset = new Vector2(0, 0);
  3419. this.repeat = new Vector2(1, 1);
  3420. this.center = new Vector2(0, 0);
  3421. this.rotation = 0;
  3422. this.matrixAutoUpdate = true;
  3423. this.matrix = new Matrix3();
  3424. this.generateMipmaps = true;
  3425. this.premultiplyAlpha = false;
  3426. this.flipY = true;
  3427. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  3428. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  3429. //
  3430. // Also changing the encoding after already used by a Material will not automatically make the Material
  3431. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  3432. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  3433. this.version = 0;
  3434. this.onUpdate = null;
  3435. }
  3436. Texture.DEFAULT_IMAGE = undefined;
  3437. Texture.DEFAULT_MAPPING = UVMapping;
  3438. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3439. constructor: Texture,
  3440. isTexture: true,
  3441. updateMatrix: function () {
  3442. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  3443. },
  3444. clone: function () {
  3445. return new this.constructor().copy(this);
  3446. },
  3447. copy: function (source) {
  3448. this.name = source.name;
  3449. this.image = source.image;
  3450. this.mipmaps = source.mipmaps.slice(0);
  3451. this.mapping = source.mapping;
  3452. this.wrapS = source.wrapS;
  3453. this.wrapT = source.wrapT;
  3454. this.magFilter = source.magFilter;
  3455. this.minFilter = source.minFilter;
  3456. this.anisotropy = source.anisotropy;
  3457. this.format = source.format;
  3458. this.type = source.type;
  3459. this.offset.copy(source.offset);
  3460. this.repeat.copy(source.repeat);
  3461. this.center.copy(source.center);
  3462. this.rotation = source.rotation;
  3463. this.matrixAutoUpdate = source.matrixAutoUpdate;
  3464. this.matrix.copy(source.matrix);
  3465. this.generateMipmaps = source.generateMipmaps;
  3466. this.premultiplyAlpha = source.premultiplyAlpha;
  3467. this.flipY = source.flipY;
  3468. this.unpackAlignment = source.unpackAlignment;
  3469. this.encoding = source.encoding;
  3470. return this;
  3471. },
  3472. toJSON: function (meta) {
  3473. var isRootObject = meta === undefined || typeof meta === 'string';
  3474. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  3475. return meta.textures[this.uuid];
  3476. }
  3477. var output = {
  3478. metadata: {
  3479. version: 4.5,
  3480. type: 'Texture',
  3481. generator: 'Texture.toJSON'
  3482. },
  3483. uuid: this.uuid,
  3484. name: this.name,
  3485. mapping: this.mapping,
  3486. repeat: [this.repeat.x, this.repeat.y],
  3487. offset: [this.offset.x, this.offset.y],
  3488. center: [this.center.x, this.center.y],
  3489. rotation: this.rotation,
  3490. wrap: [this.wrapS, this.wrapT],
  3491. format: this.format,
  3492. type: this.type,
  3493. encoding: this.encoding,
  3494. minFilter: this.minFilter,
  3495. magFilter: this.magFilter,
  3496. anisotropy: this.anisotropy,
  3497. flipY: this.flipY,
  3498. premultiplyAlpha: this.premultiplyAlpha,
  3499. unpackAlignment: this.unpackAlignment
  3500. };
  3501. if (this.image !== undefined) {
  3502. // TODO: Move to THREE.Image
  3503. var image = this.image;
  3504. if (image.uuid === undefined) {
  3505. image.uuid = _Math.generateUUID(); // UGH
  3506. }
  3507. if (!isRootObject && meta.images[image.uuid] === undefined) {
  3508. var url;
  3509. if (Array.isArray(image)) {
  3510. // process array of images e.g. CubeTexture
  3511. url = [];
  3512. for (var i = 0, l = image.length; i < l; i++) {
  3513. url.push(ImageUtils.getDataURL(image[i]));
  3514. }
  3515. } else {
  3516. // process single image
  3517. url = ImageUtils.getDataURL(image);
  3518. }
  3519. meta.images[image.uuid] = {
  3520. uuid: image.uuid,
  3521. url: url
  3522. };
  3523. }
  3524. output.image = image.uuid;
  3525. }
  3526. if (!isRootObject) {
  3527. meta.textures[this.uuid] = output;
  3528. }
  3529. return output;
  3530. },
  3531. dispose: function () {
  3532. this.dispatchEvent({
  3533. type: 'dispose'
  3534. });
  3535. },
  3536. transformUv: function (uv) {
  3537. if (this.mapping !== UVMapping) return uv;
  3538. uv.applyMatrix3(this.matrix);
  3539. if (uv.x < 0 || uv.x > 1) {
  3540. switch (this.wrapS) {
  3541. case RepeatWrapping:
  3542. uv.x = uv.x - Math.floor(uv.x);
  3543. break;
  3544. case ClampToEdgeWrapping:
  3545. uv.x = uv.x < 0 ? 0 : 1;
  3546. break;
  3547. case MirroredRepeatWrapping:
  3548. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  3549. uv.x = Math.ceil(uv.x) - uv.x;
  3550. } else {
  3551. uv.x = uv.x - Math.floor(uv.x);
  3552. }
  3553. break;
  3554. }
  3555. }
  3556. if (uv.y < 0 || uv.y > 1) {
  3557. switch (this.wrapT) {
  3558. case RepeatWrapping:
  3559. uv.y = uv.y - Math.floor(uv.y);
  3560. break;
  3561. case ClampToEdgeWrapping:
  3562. uv.y = uv.y < 0 ? 0 : 1;
  3563. break;
  3564. case MirroredRepeatWrapping:
  3565. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  3566. uv.y = Math.ceil(uv.y) - uv.y;
  3567. } else {
  3568. uv.y = uv.y - Math.floor(uv.y);
  3569. }
  3570. break;
  3571. }
  3572. }
  3573. if (this.flipY) {
  3574. uv.y = 1 - uv.y;
  3575. }
  3576. return uv;
  3577. }
  3578. });
  3579. Object.defineProperty(Texture.prototype, "needsUpdate", {
  3580. set: function (value) {
  3581. if (value === true) this.version++;
  3582. }
  3583. });
  3584. /**
  3585. * @author supereggbert / http://www.paulbrunt.co.uk/
  3586. * @author philogb / http://blog.thejit.org/
  3587. * @author mikael emtinger / http://gomo.se/
  3588. * @author egraether / http://egraether.com/
  3589. * @author WestLangley / http://github.com/WestLangley
  3590. */
  3591. function Vector4(x, y, z, w) {
  3592. this.x = x || 0;
  3593. this.y = y || 0;
  3594. this.z = z || 0;
  3595. this.w = w !== undefined ? w : 1;
  3596. }
  3597. Object.defineProperties(Vector4.prototype, {
  3598. "width": {
  3599. get: function () {
  3600. return this.z;
  3601. },
  3602. set: function (value) {
  3603. this.z = value;
  3604. }
  3605. },
  3606. "height": {
  3607. get: function () {
  3608. return this.w;
  3609. },
  3610. set: function (value) {
  3611. this.w = value;
  3612. }
  3613. }
  3614. });
  3615. Object.assign(Vector4.prototype, {
  3616. isVector4: true,
  3617. set: function (x, y, z, w) {
  3618. this.x = x;
  3619. this.y = y;
  3620. this.z = z;
  3621. this.w = w;
  3622. return this;
  3623. },
  3624. setScalar: function (scalar) {
  3625. this.x = scalar;
  3626. this.y = scalar;
  3627. this.z = scalar;
  3628. this.w = scalar;
  3629. return this;
  3630. },
  3631. setX: function (x) {
  3632. this.x = x;
  3633. return this;
  3634. },
  3635. setY: function (y) {
  3636. this.y = y;
  3637. return this;
  3638. },
  3639. setZ: function (z) {
  3640. this.z = z;
  3641. return this;
  3642. },
  3643. setW: function (w) {
  3644. this.w = w;
  3645. return this;
  3646. },
  3647. setComponent: function (index, value) {
  3648. switch (index) {
  3649. case 0:
  3650. this.x = value;
  3651. break;
  3652. case 1:
  3653. this.y = value;
  3654. break;
  3655. case 2:
  3656. this.z = value;
  3657. break;
  3658. case 3:
  3659. this.w = value;
  3660. break;
  3661. default:
  3662. throw new Error('index is out of range: ' + index);
  3663. }
  3664. return this;
  3665. },
  3666. getComponent: function (index) {
  3667. switch (index) {
  3668. case 0:
  3669. return this.x;
  3670. case 1:
  3671. return this.y;
  3672. case 2:
  3673. return this.z;
  3674. case 3:
  3675. return this.w;
  3676. default:
  3677. throw new Error('index is out of range: ' + index);
  3678. }
  3679. },
  3680. clone: function () {
  3681. return new this.constructor(this.x, this.y, this.z, this.w);
  3682. },
  3683. copy: function (v) {
  3684. this.x = v.x;
  3685. this.y = v.y;
  3686. this.z = v.z;
  3687. this.w = v.w !== undefined ? v.w : 1;
  3688. return this;
  3689. },
  3690. add: function (v, w) {
  3691. if (w !== undefined) {
  3692. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  3693. return this.addVectors(v, w);
  3694. }
  3695. this.x += v.x;
  3696. this.y += v.y;
  3697. this.z += v.z;
  3698. this.w += v.w;
  3699. return this;
  3700. },
  3701. addScalar: function (s) {
  3702. this.x += s;
  3703. this.y += s;
  3704. this.z += s;
  3705. this.w += s;
  3706. return this;
  3707. },
  3708. addVectors: function (a, b) {
  3709. this.x = a.x + b.x;
  3710. this.y = a.y + b.y;
  3711. this.z = a.z + b.z;
  3712. this.w = a.w + b.w;
  3713. return this;
  3714. },
  3715. addScaledVector: function (v, s) {
  3716. this.x += v.x * s;
  3717. this.y += v.y * s;
  3718. this.z += v.z * s;
  3719. this.w += v.w * s;
  3720. return this;
  3721. },
  3722. sub: function (v, w) {
  3723. if (w !== undefined) {
  3724. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  3725. return this.subVectors(v, w);
  3726. }
  3727. this.x -= v.x;
  3728. this.y -= v.y;
  3729. this.z -= v.z;
  3730. this.w -= v.w;
  3731. return this;
  3732. },
  3733. subScalar: function (s) {
  3734. this.x -= s;
  3735. this.y -= s;
  3736. this.z -= s;
  3737. this.w -= s;
  3738. return this;
  3739. },
  3740. subVectors: function (a, b) {
  3741. this.x = a.x - b.x;
  3742. this.y = a.y - b.y;
  3743. this.z = a.z - b.z;
  3744. this.w = a.w - b.w;
  3745. return this;
  3746. },
  3747. multiplyScalar: function (scalar) {
  3748. this.x *= scalar;
  3749. this.y *= scalar;
  3750. this.z *= scalar;
  3751. this.w *= scalar;
  3752. return this;
  3753. },
  3754. applyMatrix4: function (m) {
  3755. var x = this.x,
  3756. y = this.y,
  3757. z = this.z,
  3758. w = this.w;
  3759. var e = m.elements;
  3760. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  3761. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  3762. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  3763. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  3764. return this;
  3765. },
  3766. divideScalar: function (scalar) {
  3767. return this.multiplyScalar(1 / scalar);
  3768. },
  3769. setAxisAngleFromQuaternion: function (q) {
  3770. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3771. // q is assumed to be normalized
  3772. this.w = 2 * Math.acos(q.w);
  3773. var s = Math.sqrt(1 - q.w * q.w);
  3774. if (s < 0.0001) {
  3775. this.x = 1;
  3776. this.y = 0;
  3777. this.z = 0;
  3778. } else {
  3779. this.x = q.x / s;
  3780. this.y = q.y / s;
  3781. this.z = q.z / s;
  3782. }
  3783. return this;
  3784. },
  3785. setAxisAngleFromRotationMatrix: function (m) {
  3786. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3787. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3788. var angle,
  3789. x,
  3790. y,
  3791. z,
  3792. // variables for result
  3793. epsilon = 0.01,
  3794. // margin to allow for rounding errors
  3795. epsilon2 = 0.1,
  3796. // margin to distinguish between 0 and 180 degrees
  3797. te = m.elements,
  3798. m11 = te[0],
  3799. m12 = te[4],
  3800. m13 = te[8],
  3801. m21 = te[1],
  3802. m22 = te[5],
  3803. m23 = te[9],
  3804. m31 = te[2],
  3805. m32 = te[6],
  3806. m33 = te[10];
  3807. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  3808. // singularity found
  3809. // first check for identity matrix which must have +1 for all terms
  3810. // in leading diagonal and zero in other terms
  3811. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  3812. // this singularity is identity matrix so angle = 0
  3813. this.set(1, 0, 0, 0);
  3814. return this; // zero angle, arbitrary axis
  3815. } // otherwise this singularity is angle = 180
  3816. angle = Math.PI;
  3817. var xx = (m11 + 1) / 2;
  3818. var yy = (m22 + 1) / 2;
  3819. var zz = (m33 + 1) / 2;
  3820. var xy = (m12 + m21) / 4;
  3821. var xz = (m13 + m31) / 4;
  3822. var yz = (m23 + m32) / 4;
  3823. if (xx > yy && xx > zz) {
  3824. // m11 is the largest diagonal term
  3825. if (xx < epsilon) {
  3826. x = 0;
  3827. y = 0.707106781;
  3828. z = 0.707106781;
  3829. } else {
  3830. x = Math.sqrt(xx);
  3831. y = xy / x;
  3832. z = xz / x;
  3833. }
  3834. } else if (yy > zz) {
  3835. // m22 is the largest diagonal term
  3836. if (yy < epsilon) {
  3837. x = 0.707106781;
  3838. y = 0;
  3839. z = 0.707106781;
  3840. } else {
  3841. y = Math.sqrt(yy);
  3842. x = xy / y;
  3843. z = yz / y;
  3844. }
  3845. } else {
  3846. // m33 is the largest diagonal term so base result on this
  3847. if (zz < epsilon) {
  3848. x = 0.707106781;
  3849. y = 0.707106781;
  3850. z = 0;
  3851. } else {
  3852. z = Math.sqrt(zz);
  3853. x = xz / z;
  3854. y = yz / z;
  3855. }
  3856. }
  3857. this.set(x, y, z, angle);
  3858. return this; // return 180 deg rotation
  3859. } // as we have reached here there are no singularities so we can handle normally
  3860. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  3861. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3862. // caught by singularity test above, but I've left it in just in case
  3863. this.x = (m32 - m23) / s;
  3864. this.y = (m13 - m31) / s;
  3865. this.z = (m21 - m12) / s;
  3866. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  3867. return this;
  3868. },
  3869. min: function (v) {
  3870. this.x = Math.min(this.x, v.x);
  3871. this.y = Math.min(this.y, v.y);
  3872. this.z = Math.min(this.z, v.z);
  3873. this.w = Math.min(this.w, v.w);
  3874. return this;
  3875. },
  3876. max: function (v) {
  3877. this.x = Math.max(this.x, v.x);
  3878. this.y = Math.max(this.y, v.y);
  3879. this.z = Math.max(this.z, v.z);
  3880. this.w = Math.max(this.w, v.w);
  3881. return this;
  3882. },
  3883. clamp: function (min, max) {
  3884. // assumes min < max, componentwise
  3885. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3886. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3887. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3888. this.w = Math.max(min.w, Math.min(max.w, this.w));
  3889. return this;
  3890. },
  3891. clampScalar: function (minVal, maxVal) {
  3892. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3893. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3894. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3895. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  3896. return this;
  3897. },
  3898. clampLength: function (min, max) {
  3899. var length = this.length();
  3900. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3901. },
  3902. floor: function () {
  3903. this.x = Math.floor(this.x);
  3904. this.y = Math.floor(this.y);
  3905. this.z = Math.floor(this.z);
  3906. this.w = Math.floor(this.w);
  3907. return this;
  3908. },
  3909. ceil: function () {
  3910. this.x = Math.ceil(this.x);
  3911. this.y = Math.ceil(this.y);
  3912. this.z = Math.ceil(this.z);
  3913. this.w = Math.ceil(this.w);
  3914. return this;
  3915. },
  3916. round: function () {
  3917. this.x = Math.round(this.x);
  3918. this.y = Math.round(this.y);
  3919. this.z = Math.round(this.z);
  3920. this.w = Math.round(this.w);
  3921. return this;
  3922. },
  3923. roundToZero: function () {
  3924. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3925. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3926. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3927. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  3928. return this;
  3929. },
  3930. negate: function () {
  3931. this.x = -this.x;
  3932. this.y = -this.y;
  3933. this.z = -this.z;
  3934. this.w = -this.w;
  3935. return this;
  3936. },
  3937. dot: function (v) {
  3938. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3939. },
  3940. lengthSq: function () {
  3941. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3942. },
  3943. length: function () {
  3944. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3945. },
  3946. manhattanLength: function () {
  3947. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  3948. },
  3949. normalize: function () {
  3950. return this.divideScalar(this.length() || 1);
  3951. },
  3952. setLength: function (length) {
  3953. return this.normalize().multiplyScalar(length);
  3954. },
  3955. lerp: function (v, alpha) {
  3956. this.x += (v.x - this.x) * alpha;
  3957. this.y += (v.y - this.y) * alpha;
  3958. this.z += (v.z - this.z) * alpha;
  3959. this.w += (v.w - this.w) * alpha;
  3960. return this;
  3961. },
  3962. lerpVectors: function (v1, v2, alpha) {
  3963. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  3964. },
  3965. equals: function (v) {
  3966. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  3967. },
  3968. fromArray: function (array, offset) {
  3969. if (offset === undefined) offset = 0;
  3970. this.x = array[offset];
  3971. this.y = array[offset + 1];
  3972. this.z = array[offset + 2];
  3973. this.w = array[offset + 3];
  3974. return this;
  3975. },
  3976. toArray: function (array, offset) {
  3977. if (array === undefined) array = [];
  3978. if (offset === undefined) offset = 0;
  3979. array[offset] = this.x;
  3980. array[offset + 1] = this.y;
  3981. array[offset + 2] = this.z;
  3982. array[offset + 3] = this.w;
  3983. return array;
  3984. },
  3985. fromBufferAttribute: function (attribute, index, offset) {
  3986. if (offset !== undefined) {
  3987. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  3988. }
  3989. this.x = attribute.getX(index);
  3990. this.y = attribute.getY(index);
  3991. this.z = attribute.getZ(index);
  3992. this.w = attribute.getW(index);
  3993. return this;
  3994. }
  3995. });
  3996. /**
  3997. * @author szimek / https://github.com/szimek/
  3998. * @author alteredq / http://alteredqualia.com/
  3999. * @author Marius Kintel / https://github.com/kintel
  4000. */
  4001. /*
  4002. In options, we can specify:
  4003. * Texture parameters for an auto-generated target texture
  4004. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  4005. */
  4006. function WebGLRenderTarget(width, height, options) {
  4007. this.width = width;
  4008. this.height = height;
  4009. this.scissor = new Vector4(0, 0, width, height);
  4010. this.scissorTest = false;
  4011. this.viewport = new Vector4(0, 0, width, height);
  4012. options = options || {};
  4013. this.texture = new Texture(undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  4014. this.texture.image = {};
  4015. this.texture.image.width = width;
  4016. this.texture.image.height = height;
  4017. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  4018. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  4019. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  4020. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  4021. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  4022. }
  4023. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4024. constructor: WebGLRenderTarget,
  4025. isWebGLRenderTarget: true,
  4026. setSize: function (width, height) {
  4027. if (this.width !== width || this.height !== height) {
  4028. this.width = width;
  4029. this.height = height;
  4030. this.texture.image.width = width;
  4031. this.texture.image.height = height;
  4032. this.dispose();
  4033. }
  4034. this.viewport.set(0, 0, width, height);
  4035. this.scissor.set(0, 0, width, height);
  4036. },
  4037. clone: function () {
  4038. return new this.constructor().copy(this);
  4039. },
  4040. copy: function (source) {
  4041. this.width = source.width;
  4042. this.height = source.height;
  4043. this.viewport.copy(source.viewport);
  4044. this.texture = source.texture.clone();
  4045. this.depthBuffer = source.depthBuffer;
  4046. this.stencilBuffer = source.stencilBuffer;
  4047. this.depthTexture = source.depthTexture;
  4048. return this;
  4049. },
  4050. dispose: function () {
  4051. this.dispatchEvent({
  4052. type: 'dispose'
  4053. });
  4054. }
  4055. });
  4056. /**
  4057. * @author Mugen87 / https://github.com/Mugen87
  4058. * @author Matt DesLauriers / @mattdesl
  4059. */
  4060. function WebGLMultisampleRenderTarget(width, height, options) {
  4061. WebGLRenderTarget.call(this, width, height, options);
  4062. this.samples = 4;
  4063. }
  4064. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  4065. constructor: WebGLMultisampleRenderTarget,
  4066. isWebGLMultisampleRenderTarget: true,
  4067. copy: function (source) {
  4068. WebGLRenderTarget.prototype.copy.call(this, source);
  4069. this.samples = source.samples;
  4070. return this;
  4071. }
  4072. });
  4073. var _v1 = new Vector3();
  4074. var _m1 = new Matrix4();
  4075. var _zero = new Vector3(0, 0, 0);
  4076. var _one = new Vector3(1, 1, 1);
  4077. var _x = new Vector3();
  4078. var _y = new Vector3();
  4079. var _z = new Vector3();
  4080. /**
  4081. * @author mrdoob / http://mrdoob.com/
  4082. * @author supereggbert / http://www.paulbrunt.co.uk/
  4083. * @author philogb / http://blog.thejit.org/
  4084. * @author jordi_ros / http://plattsoft.com
  4085. * @author D1plo1d / http://github.com/D1plo1d
  4086. * @author alteredq / http://alteredqualia.com/
  4087. * @author mikael emtinger / http://gomo.se/
  4088. * @author timknip / http://www.floorplanner.com/
  4089. * @author bhouston / http://clara.io
  4090. * @author WestLangley / http://github.com/WestLangley
  4091. */
  4092. function Matrix4() {
  4093. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4094. if (arguments.length > 0) {
  4095. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  4096. }
  4097. }
  4098. Object.assign(Matrix4.prototype, {
  4099. isMatrix4: true,
  4100. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  4101. var te = this.elements;
  4102. te[0] = n11;
  4103. te[4] = n12;
  4104. te[8] = n13;
  4105. te[12] = n14;
  4106. te[1] = n21;
  4107. te[5] = n22;
  4108. te[9] = n23;
  4109. te[13] = n24;
  4110. te[2] = n31;
  4111. te[6] = n32;
  4112. te[10] = n33;
  4113. te[14] = n34;
  4114. te[3] = n41;
  4115. te[7] = n42;
  4116. te[11] = n43;
  4117. te[15] = n44;
  4118. return this;
  4119. },
  4120. identity: function () {
  4121. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4122. return this;
  4123. },
  4124. clone: function () {
  4125. return new Matrix4().fromArray(this.elements);
  4126. },
  4127. copy: function (m) {
  4128. var te = this.elements;
  4129. var me = m.elements;
  4130. te[0] = me[0];
  4131. te[1] = me[1];
  4132. te[2] = me[2];
  4133. te[3] = me[3];
  4134. te[4] = me[4];
  4135. te[5] = me[5];
  4136. te[6] = me[6];
  4137. te[7] = me[7];
  4138. te[8] = me[8];
  4139. te[9] = me[9];
  4140. te[10] = me[10];
  4141. te[11] = me[11];
  4142. te[12] = me[12];
  4143. te[13] = me[13];
  4144. te[14] = me[14];
  4145. te[15] = me[15];
  4146. return this;
  4147. },
  4148. copyPosition: function (m) {
  4149. var te = this.elements,
  4150. me = m.elements;
  4151. te[12] = me[12];
  4152. te[13] = me[13];
  4153. te[14] = me[14];
  4154. return this;
  4155. },
  4156. extractBasis: function (xAxis, yAxis, zAxis) {
  4157. xAxis.setFromMatrixColumn(this, 0);
  4158. yAxis.setFromMatrixColumn(this, 1);
  4159. zAxis.setFromMatrixColumn(this, 2);
  4160. return this;
  4161. },
  4162. makeBasis: function (xAxis, yAxis, zAxis) {
  4163. 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);
  4164. return this;
  4165. },
  4166. extractRotation: function (m) {
  4167. // this method does not support reflection matrices
  4168. var te = this.elements;
  4169. var me = m.elements;
  4170. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  4171. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  4172. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  4173. te[0] = me[0] * scaleX;
  4174. te[1] = me[1] * scaleX;
  4175. te[2] = me[2] * scaleX;
  4176. te[3] = 0;
  4177. te[4] = me[4] * scaleY;
  4178. te[5] = me[5] * scaleY;
  4179. te[6] = me[6] * scaleY;
  4180. te[7] = 0;
  4181. te[8] = me[8] * scaleZ;
  4182. te[9] = me[9] * scaleZ;
  4183. te[10] = me[10] * scaleZ;
  4184. te[11] = 0;
  4185. te[12] = 0;
  4186. te[13] = 0;
  4187. te[14] = 0;
  4188. te[15] = 1;
  4189. return this;
  4190. },
  4191. makeRotationFromEuler: function (euler) {
  4192. if (!(euler && euler.isEuler)) {
  4193. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  4194. }
  4195. var te = this.elements;
  4196. var x = euler.x,
  4197. y = euler.y,
  4198. z = euler.z;
  4199. var a = Math.cos(x),
  4200. b = Math.sin(x);
  4201. var c = Math.cos(y),
  4202. d = Math.sin(y);
  4203. var e = Math.cos(z),
  4204. f = Math.sin(z);
  4205. if (euler.order === 'XYZ') {
  4206. var ae = a * e,
  4207. af = a * f,
  4208. be = b * e,
  4209. bf = b * f;
  4210. te[0] = c * e;
  4211. te[4] = -c * f;
  4212. te[8] = d;
  4213. te[1] = af + be * d;
  4214. te[5] = ae - bf * d;
  4215. te[9] = -b * c;
  4216. te[2] = bf - ae * d;
  4217. te[6] = be + af * d;
  4218. te[10] = a * c;
  4219. } else if (euler.order === 'YXZ') {
  4220. var ce = c * e,
  4221. cf = c * f,
  4222. de = d * e,
  4223. df = d * f;
  4224. te[0] = ce + df * b;
  4225. te[4] = de * b - cf;
  4226. te[8] = a * d;
  4227. te[1] = a * f;
  4228. te[5] = a * e;
  4229. te[9] = -b;
  4230. te[2] = cf * b - de;
  4231. te[6] = df + ce * b;
  4232. te[10] = a * c;
  4233. } else if (euler.order === 'ZXY') {
  4234. var ce = c * e,
  4235. cf = c * f,
  4236. de = d * e,
  4237. df = d * f;
  4238. te[0] = ce - df * b;
  4239. te[4] = -a * f;
  4240. te[8] = de + cf * b;
  4241. te[1] = cf + de * b;
  4242. te[5] = a * e;
  4243. te[9] = df - ce * b;
  4244. te[2] = -a * d;
  4245. te[6] = b;
  4246. te[10] = a * c;
  4247. } else if (euler.order === 'ZYX') {
  4248. var ae = a * e,
  4249. af = a * f,
  4250. be = b * e,
  4251. bf = b * f;
  4252. te[0] = c * e;
  4253. te[4] = be * d - af;
  4254. te[8] = ae * d + bf;
  4255. te[1] = c * f;
  4256. te[5] = bf * d + ae;
  4257. te[9] = af * d - be;
  4258. te[2] = -d;
  4259. te[6] = b * c;
  4260. te[10] = a * c;
  4261. } else if (euler.order === 'YZX') {
  4262. var ac = a * c,
  4263. ad = a * d,
  4264. bc = b * c,
  4265. bd = b * d;
  4266. te[0] = c * e;
  4267. te[4] = bd - ac * f;
  4268. te[8] = bc * f + ad;
  4269. te[1] = f;
  4270. te[5] = a * e;
  4271. te[9] = -b * e;
  4272. te[2] = -d * e;
  4273. te[6] = ad * f + bc;
  4274. te[10] = ac - bd * f;
  4275. } else if (euler.order === 'XZY') {
  4276. var ac = a * c,
  4277. ad = a * d,
  4278. bc = b * c,
  4279. bd = b * d;
  4280. te[0] = c * e;
  4281. te[4] = -f;
  4282. te[8] = d * e;
  4283. te[1] = ac * f + bd;
  4284. te[5] = a * e;
  4285. te[9] = ad * f - bc;
  4286. te[2] = bc * f - ad;
  4287. te[6] = b * e;
  4288. te[10] = bd * f + ac;
  4289. } // bottom row
  4290. te[3] = 0;
  4291. te[7] = 0;
  4292. te[11] = 0; // last column
  4293. te[12] = 0;
  4294. te[13] = 0;
  4295. te[14] = 0;
  4296. te[15] = 1;
  4297. return this;
  4298. },
  4299. makeRotationFromQuaternion: function (q) {
  4300. return this.compose(_zero, q, _one);
  4301. },
  4302. lookAt: function (eye, target, up) {
  4303. var te = this.elements;
  4304. _z.subVectors(eye, target);
  4305. if (_z.lengthSq() === 0) {
  4306. // eye and target are in the same position
  4307. _z.z = 1;
  4308. }
  4309. _z.normalize();
  4310. _x.crossVectors(up, _z);
  4311. if (_x.lengthSq() === 0) {
  4312. // up and z are parallel
  4313. if (Math.abs(up.z) === 1) {
  4314. _z.x += 0.0001;
  4315. } else {
  4316. _z.z += 0.0001;
  4317. }
  4318. _z.normalize();
  4319. _x.crossVectors(up, _z);
  4320. }
  4321. _x.normalize();
  4322. _y.crossVectors(_z, _x);
  4323. te[0] = _x.x;
  4324. te[4] = _y.x;
  4325. te[8] = _z.x;
  4326. te[1] = _x.y;
  4327. te[5] = _y.y;
  4328. te[9] = _z.y;
  4329. te[2] = _x.z;
  4330. te[6] = _y.z;
  4331. te[10] = _z.z;
  4332. return this;
  4333. },
  4334. multiply: function (m, n) {
  4335. if (n !== undefined) {
  4336. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  4337. return this.multiplyMatrices(m, n);
  4338. }
  4339. return this.multiplyMatrices(this, m);
  4340. },
  4341. premultiply: function (m) {
  4342. return this.multiplyMatrices(m, this);
  4343. },
  4344. multiplyMatrices: function (a, b) {
  4345. var ae = a.elements;
  4346. var be = b.elements;
  4347. var te = this.elements;
  4348. var a11 = ae[0],
  4349. a12 = ae[4],
  4350. a13 = ae[8],
  4351. a14 = ae[12];
  4352. var a21 = ae[1],
  4353. a22 = ae[5],
  4354. a23 = ae[9],
  4355. a24 = ae[13];
  4356. var a31 = ae[2],
  4357. a32 = ae[6],
  4358. a33 = ae[10],
  4359. a34 = ae[14];
  4360. var a41 = ae[3],
  4361. a42 = ae[7],
  4362. a43 = ae[11],
  4363. a44 = ae[15];
  4364. var b11 = be[0],
  4365. b12 = be[4],
  4366. b13 = be[8],
  4367. b14 = be[12];
  4368. var b21 = be[1],
  4369. b22 = be[5],
  4370. b23 = be[9],
  4371. b24 = be[13];
  4372. var b31 = be[2],
  4373. b32 = be[6],
  4374. b33 = be[10],
  4375. b34 = be[14];
  4376. var b41 = be[3],
  4377. b42 = be[7],
  4378. b43 = be[11],
  4379. b44 = be[15];
  4380. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4381. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4382. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4383. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4384. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4385. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4386. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4387. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4388. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4389. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4390. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4391. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4392. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4393. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4394. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4395. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4396. return this;
  4397. },
  4398. multiplyScalar: function (s) {
  4399. var te = this.elements;
  4400. te[0] *= s;
  4401. te[4] *= s;
  4402. te[8] *= s;
  4403. te[12] *= s;
  4404. te[1] *= s;
  4405. te[5] *= s;
  4406. te[9] *= s;
  4407. te[13] *= s;
  4408. te[2] *= s;
  4409. te[6] *= s;
  4410. te[10] *= s;
  4411. te[14] *= s;
  4412. te[3] *= s;
  4413. te[7] *= s;
  4414. te[11] *= s;
  4415. te[15] *= s;
  4416. return this;
  4417. },
  4418. applyToBufferAttribute: function (attribute) {
  4419. for (var i = 0, l = attribute.count; i < l; i++) {
  4420. _v1.x = attribute.getX(i);
  4421. _v1.y = attribute.getY(i);
  4422. _v1.z = attribute.getZ(i);
  4423. _v1.applyMatrix4(this);
  4424. attribute.setXYZ(i, _v1.x, _v1.y, _v1.z);
  4425. }
  4426. return attribute;
  4427. },
  4428. determinant: function () {
  4429. var te = this.elements;
  4430. var n11 = te[0],
  4431. n12 = te[4],
  4432. n13 = te[8],
  4433. n14 = te[12];
  4434. var n21 = te[1],
  4435. n22 = te[5],
  4436. n23 = te[9],
  4437. n24 = te[13];
  4438. var n31 = te[2],
  4439. n32 = te[6],
  4440. n33 = te[10],
  4441. n34 = te[14];
  4442. var n41 = te[3],
  4443. n42 = te[7],
  4444. n43 = te[11],
  4445. n44 = te[15]; //TODO: make this more efficient
  4446. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4447. 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);
  4448. },
  4449. transpose: function () {
  4450. var te = this.elements;
  4451. var tmp;
  4452. tmp = te[1];
  4453. te[1] = te[4];
  4454. te[4] = tmp;
  4455. tmp = te[2];
  4456. te[2] = te[8];
  4457. te[8] = tmp;
  4458. tmp = te[6];
  4459. te[6] = te[9];
  4460. te[9] = tmp;
  4461. tmp = te[3];
  4462. te[3] = te[12];
  4463. te[12] = tmp;
  4464. tmp = te[7];
  4465. te[7] = te[13];
  4466. te[13] = tmp;
  4467. tmp = te[11];
  4468. te[11] = te[14];
  4469. te[14] = tmp;
  4470. return this;
  4471. },
  4472. setPosition: function (x, y, z) {
  4473. var te = this.elements;
  4474. if (x.isVector3) {
  4475. te[12] = x.x;
  4476. te[13] = x.y;
  4477. te[14] = x.z;
  4478. } else {
  4479. te[12] = x;
  4480. te[13] = y;
  4481. te[14] = z;
  4482. }
  4483. return this;
  4484. },
  4485. getInverse: function (m, throwOnDegenerate) {
  4486. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4487. var te = this.elements,
  4488. me = m.elements,
  4489. n11 = me[0],
  4490. n21 = me[1],
  4491. n31 = me[2],
  4492. n41 = me[3],
  4493. n12 = me[4],
  4494. n22 = me[5],
  4495. n32 = me[6],
  4496. n42 = me[7],
  4497. n13 = me[8],
  4498. n23 = me[9],
  4499. n33 = me[10],
  4500. n43 = me[11],
  4501. n14 = me[12],
  4502. n24 = me[13],
  4503. n34 = me[14],
  4504. n44 = me[15],
  4505. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4506. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4507. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4508. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4509. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4510. if (det === 0) {
  4511. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  4512. if (throwOnDegenerate === true) {
  4513. throw new Error(msg);
  4514. } else {
  4515. console.warn(msg);
  4516. }
  4517. return this.identity();
  4518. }
  4519. var detInv = 1 / det;
  4520. te[0] = t11 * detInv;
  4521. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4522. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4523. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4524. te[4] = t12 * detInv;
  4525. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4526. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4527. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4528. te[8] = t13 * detInv;
  4529. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4530. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4531. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4532. te[12] = t14 * detInv;
  4533. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4534. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4535. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4536. return this;
  4537. },
  4538. scale: function (v) {
  4539. var te = this.elements;
  4540. var x = v.x,
  4541. y = v.y,
  4542. z = v.z;
  4543. te[0] *= x;
  4544. te[4] *= y;
  4545. te[8] *= z;
  4546. te[1] *= x;
  4547. te[5] *= y;
  4548. te[9] *= z;
  4549. te[2] *= x;
  4550. te[6] *= y;
  4551. te[10] *= z;
  4552. te[3] *= x;
  4553. te[7] *= y;
  4554. te[11] *= z;
  4555. return this;
  4556. },
  4557. getMaxScaleOnAxis: function () {
  4558. var te = this.elements;
  4559. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4560. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4561. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4562. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4563. },
  4564. makeTranslation: function (x, y, z) {
  4565. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4566. return this;
  4567. },
  4568. makeRotationX: function (theta) {
  4569. var c = Math.cos(theta),
  4570. s = Math.sin(theta);
  4571. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4572. return this;
  4573. },
  4574. makeRotationY: function (theta) {
  4575. var c = Math.cos(theta),
  4576. s = Math.sin(theta);
  4577. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4578. return this;
  4579. },
  4580. makeRotationZ: function (theta) {
  4581. var c = Math.cos(theta),
  4582. s = Math.sin(theta);
  4583. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4584. return this;
  4585. },
  4586. makeRotationAxis: function (axis, angle) {
  4587. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4588. var c = Math.cos(angle);
  4589. var s = Math.sin(angle);
  4590. var t = 1 - c;
  4591. var x = axis.x,
  4592. y = axis.y,
  4593. z = axis.z;
  4594. var tx = t * x,
  4595. ty = t * y;
  4596. 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);
  4597. return this;
  4598. },
  4599. makeScale: function (x, y, z) {
  4600. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4601. return this;
  4602. },
  4603. makeShear: function (x, y, z) {
  4604. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  4605. return this;
  4606. },
  4607. compose: function (position, quaternion, scale) {
  4608. var te = this.elements;
  4609. var x = quaternion._x,
  4610. y = quaternion._y,
  4611. z = quaternion._z,
  4612. w = quaternion._w;
  4613. var x2 = x + x,
  4614. y2 = y + y,
  4615. z2 = z + z;
  4616. var xx = x * x2,
  4617. xy = x * y2,
  4618. xz = x * z2;
  4619. var yy = y * y2,
  4620. yz = y * z2,
  4621. zz = z * z2;
  4622. var wx = w * x2,
  4623. wy = w * y2,
  4624. wz = w * z2;
  4625. var sx = scale.x,
  4626. sy = scale.y,
  4627. sz = scale.z;
  4628. te[0] = (1 - (yy + zz)) * sx;
  4629. te[1] = (xy + wz) * sx;
  4630. te[2] = (xz - wy) * sx;
  4631. te[3] = 0;
  4632. te[4] = (xy - wz) * sy;
  4633. te[5] = (1 - (xx + zz)) * sy;
  4634. te[6] = (yz + wx) * sy;
  4635. te[7] = 0;
  4636. te[8] = (xz + wy) * sz;
  4637. te[9] = (yz - wx) * sz;
  4638. te[10] = (1 - (xx + yy)) * sz;
  4639. te[11] = 0;
  4640. te[12] = position.x;
  4641. te[13] = position.y;
  4642. te[14] = position.z;
  4643. te[15] = 1;
  4644. return this;
  4645. },
  4646. decompose: function (position, quaternion, scale) {
  4647. var te = this.elements;
  4648. var sx = _v1.set(te[0], te[1], te[2]).length();
  4649. var sy = _v1.set(te[4], te[5], te[6]).length();
  4650. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4651. var det = this.determinant();
  4652. if (det < 0) sx = -sx;
  4653. position.x = te[12];
  4654. position.y = te[13];
  4655. position.z = te[14]; // scale the rotation part
  4656. _m1.copy(this);
  4657. var invSX = 1 / sx;
  4658. var invSY = 1 / sy;
  4659. var invSZ = 1 / sz;
  4660. _m1.elements[0] *= invSX;
  4661. _m1.elements[1] *= invSX;
  4662. _m1.elements[2] *= invSX;
  4663. _m1.elements[4] *= invSY;
  4664. _m1.elements[5] *= invSY;
  4665. _m1.elements[6] *= invSY;
  4666. _m1.elements[8] *= invSZ;
  4667. _m1.elements[9] *= invSZ;
  4668. _m1.elements[10] *= invSZ;
  4669. quaternion.setFromRotationMatrix(_m1);
  4670. scale.x = sx;
  4671. scale.y = sy;
  4672. scale.z = sz;
  4673. return this;
  4674. },
  4675. makePerspective: function (left, right, top, bottom, near, far) {
  4676. if (far === undefined) {
  4677. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  4678. }
  4679. var te = this.elements;
  4680. var x = 2 * near / (right - left);
  4681. var y = 2 * near / (top - bottom);
  4682. var a = (right + left) / (right - left);
  4683. var b = (top + bottom) / (top - bottom);
  4684. var c = -(far + near) / (far - near);
  4685. var d = -2 * far * near / (far - near);
  4686. te[0] = x;
  4687. te[4] = 0;
  4688. te[8] = a;
  4689. te[12] = 0;
  4690. te[1] = 0;
  4691. te[5] = y;
  4692. te[9] = b;
  4693. te[13] = 0;
  4694. te[2] = 0;
  4695. te[6] = 0;
  4696. te[10] = c;
  4697. te[14] = d;
  4698. te[3] = 0;
  4699. te[7] = 0;
  4700. te[11] = -1;
  4701. te[15] = 0;
  4702. return this;
  4703. },
  4704. makeOrthographic: function (left, right, top, bottom, near, far) {
  4705. var te = this.elements;
  4706. var w = 1.0 / (right - left);
  4707. var h = 1.0 / (top - bottom);
  4708. var p = 1.0 / (far - near);
  4709. var x = (right + left) * w;
  4710. var y = (top + bottom) * h;
  4711. var z = (far + near) * p;
  4712. te[0] = 2 * w;
  4713. te[4] = 0;
  4714. te[8] = 0;
  4715. te[12] = -x;
  4716. te[1] = 0;
  4717. te[5] = 2 * h;
  4718. te[9] = 0;
  4719. te[13] = -y;
  4720. te[2] = 0;
  4721. te[6] = 0;
  4722. te[10] = -2 * p;
  4723. te[14] = -z;
  4724. te[3] = 0;
  4725. te[7] = 0;
  4726. te[11] = 0;
  4727. te[15] = 1;
  4728. return this;
  4729. },
  4730. equals: function (matrix) {
  4731. var te = this.elements;
  4732. var me = matrix.elements;
  4733. for (var i = 0; i < 16; i++) {
  4734. if (te[i] !== me[i]) return false;
  4735. }
  4736. return true;
  4737. },
  4738. fromArray: function (array, offset) {
  4739. if (offset === undefined) offset = 0;
  4740. for (var i = 0; i < 16; i++) {
  4741. this.elements[i] = array[i + offset];
  4742. }
  4743. return this;
  4744. },
  4745. toArray: function (array, offset) {
  4746. if (array === undefined) array = [];
  4747. if (offset === undefined) offset = 0;
  4748. var te = this.elements;
  4749. array[offset] = te[0];
  4750. array[offset + 1] = te[1];
  4751. array[offset + 2] = te[2];
  4752. array[offset + 3] = te[3];
  4753. array[offset + 4] = te[4];
  4754. array[offset + 5] = te[5];
  4755. array[offset + 6] = te[6];
  4756. array[offset + 7] = te[7];
  4757. array[offset + 8] = te[8];
  4758. array[offset + 9] = te[9];
  4759. array[offset + 10] = te[10];
  4760. array[offset + 11] = te[11];
  4761. array[offset + 12] = te[12];
  4762. array[offset + 13] = te[13];
  4763. array[offset + 14] = te[14];
  4764. array[offset + 15] = te[15];
  4765. return array;
  4766. }
  4767. });
  4768. /**
  4769. * @author mrdoob / http://mrdoob.com/
  4770. * @author WestLangley / http://github.com/WestLangley
  4771. * @author bhouston / http://clara.io
  4772. */
  4773. var _matrix = new Matrix4();
  4774. var _quaternion$1 = new Quaternion();
  4775. function Euler(x, y, z, order) {
  4776. this._x = x || 0;
  4777. this._y = y || 0;
  4778. this._z = z || 0;
  4779. this._order = order || Euler.DefaultOrder;
  4780. }
  4781. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4782. Euler.DefaultOrder = 'XYZ';
  4783. Object.defineProperties(Euler.prototype, {
  4784. x: {
  4785. get: function () {
  4786. return this._x;
  4787. },
  4788. set: function (value) {
  4789. this._x = value;
  4790. this._onChangeCallback();
  4791. }
  4792. },
  4793. y: {
  4794. get: function () {
  4795. return this._y;
  4796. },
  4797. set: function (value) {
  4798. this._y = value;
  4799. this._onChangeCallback();
  4800. }
  4801. },
  4802. z: {
  4803. get: function () {
  4804. return this._z;
  4805. },
  4806. set: function (value) {
  4807. this._z = value;
  4808. this._onChangeCallback();
  4809. }
  4810. },
  4811. order: {
  4812. get: function () {
  4813. return this._order;
  4814. },
  4815. set: function (value) {
  4816. this._order = value;
  4817. this._onChangeCallback();
  4818. }
  4819. }
  4820. });
  4821. Object.assign(Euler.prototype, {
  4822. isEuler: true,
  4823. set: function (x, y, z, order) {
  4824. this._x = x;
  4825. this._y = y;
  4826. this._z = z;
  4827. this._order = order || this._order;
  4828. this._onChangeCallback();
  4829. return this;
  4830. },
  4831. clone: function () {
  4832. return new this.constructor(this._x, this._y, this._z, this._order);
  4833. },
  4834. copy: function (euler) {
  4835. this._x = euler._x;
  4836. this._y = euler._y;
  4837. this._z = euler._z;
  4838. this._order = euler._order;
  4839. this._onChangeCallback();
  4840. return this;
  4841. },
  4842. setFromRotationMatrix: function (m, order, update) {
  4843. var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4844. var te = m.elements;
  4845. var m11 = te[0],
  4846. m12 = te[4],
  4847. m13 = te[8];
  4848. var m21 = te[1],
  4849. m22 = te[5],
  4850. m23 = te[9];
  4851. var m31 = te[2],
  4852. m32 = te[6],
  4853. m33 = te[10];
  4854. order = order || this._order;
  4855. if (order === 'XYZ') {
  4856. this._y = Math.asin(clamp(m13, -1, 1));
  4857. if (Math.abs(m13) < 0.9999999) {
  4858. this._x = Math.atan2(-m23, m33);
  4859. this._z = Math.atan2(-m12, m11);
  4860. } else {
  4861. this._x = Math.atan2(m32, m22);
  4862. this._z = 0;
  4863. }
  4864. } else if (order === 'YXZ') {
  4865. this._x = Math.asin(-clamp(m23, -1, 1));
  4866. if (Math.abs(m23) < 0.9999999) {
  4867. this._y = Math.atan2(m13, m33);
  4868. this._z = Math.atan2(m21, m22);
  4869. } else {
  4870. this._y = Math.atan2(-m31, m11);
  4871. this._z = 0;
  4872. }
  4873. } else if (order === 'ZXY') {
  4874. this._x = Math.asin(clamp(m32, -1, 1));
  4875. if (Math.abs(m32) < 0.9999999) {
  4876. this._y = Math.atan2(-m31, m33);
  4877. this._z = Math.atan2(-m12, m22);
  4878. } else {
  4879. this._y = 0;
  4880. this._z = Math.atan2(m21, m11);
  4881. }
  4882. } else if (order === 'ZYX') {
  4883. this._y = Math.asin(-clamp(m31, -1, 1));
  4884. if (Math.abs(m31) < 0.9999999) {
  4885. this._x = Math.atan2(m32, m33);
  4886. this._z = Math.atan2(m21, m11);
  4887. } else {
  4888. this._x = 0;
  4889. this._z = Math.atan2(-m12, m22);
  4890. }
  4891. } else if (order === 'YZX') {
  4892. this._z = Math.asin(clamp(m21, -1, 1));
  4893. if (Math.abs(m21) < 0.9999999) {
  4894. this._x = Math.atan2(-m23, m22);
  4895. this._y = Math.atan2(-m31, m11);
  4896. } else {
  4897. this._x = 0;
  4898. this._y = Math.atan2(m13, m33);
  4899. }
  4900. } else if (order === 'XZY') {
  4901. this._z = Math.asin(-clamp(m12, -1, 1));
  4902. if (Math.abs(m12) < 0.9999999) {
  4903. this._x = Math.atan2(m32, m22);
  4904. this._y = Math.atan2(m13, m11);
  4905. } else {
  4906. this._x = Math.atan2(-m23, m33);
  4907. this._y = 0;
  4908. }
  4909. } else {
  4910. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  4911. }
  4912. this._order = order;
  4913. if (update !== false) this._onChangeCallback();
  4914. return this;
  4915. },
  4916. setFromQuaternion: function (q, order, update) {
  4917. _matrix.makeRotationFromQuaternion(q);
  4918. return this.setFromRotationMatrix(_matrix, order, update);
  4919. },
  4920. setFromVector3: function (v, order) {
  4921. return this.set(v.x, v.y, v.z, order || this._order);
  4922. },
  4923. reorder: function (newOrder) {
  4924. // WARNING: this discards revolution information -bhouston
  4925. _quaternion$1.setFromEuler(this);
  4926. return this.setFromQuaternion(_quaternion$1, newOrder);
  4927. },
  4928. equals: function (euler) {
  4929. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4930. },
  4931. fromArray: function (array) {
  4932. this._x = array[0];
  4933. this._y = array[1];
  4934. this._z = array[2];
  4935. if (array[3] !== undefined) this._order = array[3];
  4936. this._onChangeCallback();
  4937. return this;
  4938. },
  4939. toArray: function (array, offset) {
  4940. if (array === undefined) array = [];
  4941. if (offset === undefined) offset = 0;
  4942. array[offset] = this._x;
  4943. array[offset + 1] = this._y;
  4944. array[offset + 2] = this._z;
  4945. array[offset + 3] = this._order;
  4946. return array;
  4947. },
  4948. toVector3: function (optionalResult) {
  4949. if (optionalResult) {
  4950. return optionalResult.set(this._x, this._y, this._z);
  4951. } else {
  4952. return new Vector3(this._x, this._y, this._z);
  4953. }
  4954. },
  4955. _onChange: function (callback) {
  4956. this._onChangeCallback = callback;
  4957. return this;
  4958. },
  4959. _onChangeCallback: function () {}
  4960. });
  4961. /**
  4962. * @author mrdoob / http://mrdoob.com/
  4963. */
  4964. function Layers() {
  4965. this.mask = 1 | 0;
  4966. }
  4967. Object.assign(Layers.prototype, {
  4968. set: function (channel) {
  4969. this.mask = 1 << channel | 0;
  4970. },
  4971. enable: function (channel) {
  4972. this.mask |= 1 << channel | 0;
  4973. },
  4974. enableAll: function () {
  4975. this.mask = 0xffffffff | 0;
  4976. },
  4977. toggle: function (channel) {
  4978. this.mask ^= 1 << channel | 0;
  4979. },
  4980. disable: function (channel) {
  4981. this.mask &= ~(1 << channel | 0);
  4982. },
  4983. disableAll: function () {
  4984. this.mask = 0;
  4985. },
  4986. test: function (layers) {
  4987. return (this.mask & layers.mask) !== 0;
  4988. }
  4989. });
  4990. var _object3DId = 0;
  4991. var _v1$1 = new Vector3();
  4992. var _q1 = new Quaternion();
  4993. var _m1$1 = new Matrix4();
  4994. var _target = new Vector3();
  4995. var _position = new Vector3();
  4996. var _scale = new Vector3();
  4997. var _quaternion$2 = new Quaternion();
  4998. var _xAxis = new Vector3(1, 0, 0);
  4999. var _yAxis = new Vector3(0, 1, 0);
  5000. var _zAxis = new Vector3(0, 0, 1);
  5001. var _addedEvent = {
  5002. type: 'added'
  5003. };
  5004. var _removedEvent = {
  5005. type: 'removed'
  5006. };
  5007. /**
  5008. * @author mrdoob / http://mrdoob.com/
  5009. * @author mikael emtinger / http://gomo.se/
  5010. * @author alteredq / http://alteredqualia.com/
  5011. * @author WestLangley / http://github.com/WestLangley
  5012. * @author elephantatwork / www.elephantatwork.ch
  5013. */
  5014. function Object3D() {
  5015. Object.defineProperty(this, 'id', {
  5016. value: _object3DId++
  5017. });
  5018. this.uuid = _Math.generateUUID();
  5019. this.name = '';
  5020. this.type = 'Object3D';
  5021. this.parent = null;
  5022. this.children = [];
  5023. this.up = Object3D.DefaultUp.clone();
  5024. var position = new Vector3();
  5025. var rotation = new Euler();
  5026. var quaternion = new Quaternion();
  5027. var scale = new Vector3(1, 1, 1);
  5028. function onRotationChange() {
  5029. quaternion.setFromEuler(rotation, false);
  5030. }
  5031. function onQuaternionChange() {
  5032. rotation.setFromQuaternion(quaternion, undefined, false);
  5033. }
  5034. rotation._onChange(onRotationChange);
  5035. quaternion._onChange(onQuaternionChange);
  5036. Object.defineProperties(this, {
  5037. position: {
  5038. configurable: true,
  5039. enumerable: true,
  5040. value: position
  5041. },
  5042. rotation: {
  5043. configurable: true,
  5044. enumerable: true,
  5045. value: rotation
  5046. },
  5047. quaternion: {
  5048. configurable: true,
  5049. enumerable: true,
  5050. value: quaternion
  5051. },
  5052. scale: {
  5053. configurable: true,
  5054. enumerable: true,
  5055. value: scale
  5056. },
  5057. modelViewMatrix: {
  5058. value: new Matrix4()
  5059. },
  5060. normalMatrix: {
  5061. value: new Matrix3()
  5062. }
  5063. });
  5064. this.matrix = new Matrix4();
  5065. this.matrixWorld = new Matrix4();
  5066. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  5067. this.matrixWorldNeedsUpdate = false;
  5068. this.layers = new Layers();
  5069. this.visible = true;
  5070. this.castShadow = false;
  5071. this.receiveShadow = false;
  5072. this.frustumCulled = true;
  5073. this.renderOrder = 0;
  5074. this.userData = {};
  5075. }
  5076. Object3D.DefaultUp = new Vector3(0, 1, 0);
  5077. Object3D.DefaultMatrixAutoUpdate = true;
  5078. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5079. constructor: Object3D,
  5080. isObject3D: true,
  5081. onBeforeRender: function () {},
  5082. onAfterRender: function () {},
  5083. applyMatrix: function (matrix) {
  5084. if (this.matrixAutoUpdate) this.updateMatrix();
  5085. this.matrix.premultiply(matrix);
  5086. this.matrix.decompose(this.position, this.quaternion, this.scale);
  5087. },
  5088. applyQuaternion: function (q) {
  5089. this.quaternion.premultiply(q);
  5090. return this;
  5091. },
  5092. setRotationFromAxisAngle: function (axis, angle) {
  5093. // assumes axis is normalized
  5094. this.quaternion.setFromAxisAngle(axis, angle);
  5095. },
  5096. setRotationFromEuler: function (euler) {
  5097. this.quaternion.setFromEuler(euler, true);
  5098. },
  5099. setRotationFromMatrix: function (m) {
  5100. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5101. this.quaternion.setFromRotationMatrix(m);
  5102. },
  5103. setRotationFromQuaternion: function (q) {
  5104. // assumes q is normalized
  5105. this.quaternion.copy(q);
  5106. },
  5107. rotateOnAxis: function (axis, angle) {
  5108. // rotate object on axis in object space
  5109. // axis is assumed to be normalized
  5110. _q1.setFromAxisAngle(axis, angle);
  5111. this.quaternion.multiply(_q1);
  5112. return this;
  5113. },
  5114. rotateOnWorldAxis: function (axis, angle) {
  5115. // rotate object on axis in world space
  5116. // axis is assumed to be normalized
  5117. // method assumes no rotated parent
  5118. _q1.setFromAxisAngle(axis, angle);
  5119. this.quaternion.premultiply(_q1);
  5120. return this;
  5121. },
  5122. rotateX: function (angle) {
  5123. return this.rotateOnAxis(_xAxis, angle);
  5124. },
  5125. rotateY: function (angle) {
  5126. return this.rotateOnAxis(_yAxis, angle);
  5127. },
  5128. rotateZ: function (angle) {
  5129. return this.rotateOnAxis(_zAxis, angle);
  5130. },
  5131. translateOnAxis: function (axis, distance) {
  5132. // translate object by distance along axis in object space
  5133. // axis is assumed to be normalized
  5134. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  5135. this.position.add(_v1$1.multiplyScalar(distance));
  5136. return this;
  5137. },
  5138. translateX: function (distance) {
  5139. return this.translateOnAxis(_xAxis, distance);
  5140. },
  5141. translateY: function (distance) {
  5142. return this.translateOnAxis(_yAxis, distance);
  5143. },
  5144. translateZ: function (distance) {
  5145. return this.translateOnAxis(_zAxis, distance);
  5146. },
  5147. localToWorld: function (vector) {
  5148. return vector.applyMatrix4(this.matrixWorld);
  5149. },
  5150. worldToLocal: function (vector) {
  5151. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  5152. },
  5153. lookAt: function (x, y, z) {
  5154. // This method does not support objects having non-uniformly-scaled parent(s)
  5155. if (x.isVector3) {
  5156. _target.copy(x);
  5157. } else {
  5158. _target.set(x, y, z);
  5159. }
  5160. var parent = this.parent;
  5161. this.updateWorldMatrix(true, false);
  5162. _position.setFromMatrixPosition(this.matrixWorld);
  5163. if (this.isCamera || this.isLight) {
  5164. _m1$1.lookAt(_position, _target, this.up);
  5165. } else {
  5166. _m1$1.lookAt(_target, _position, this.up);
  5167. }
  5168. this.quaternion.setFromRotationMatrix(_m1$1);
  5169. if (parent) {
  5170. _m1$1.extractRotation(parent.matrixWorld);
  5171. _q1.setFromRotationMatrix(_m1$1);
  5172. this.quaternion.premultiply(_q1.inverse());
  5173. }
  5174. },
  5175. add: function (object) {
  5176. if (arguments.length > 1) {
  5177. for (var i = 0; i < arguments.length; i++) {
  5178. this.add(arguments[i]);
  5179. }
  5180. return this;
  5181. }
  5182. if (object === this) {
  5183. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  5184. return this;
  5185. }
  5186. if (object && object.isObject3D) {
  5187. if (object.parent !== null) {
  5188. object.parent.remove(object);
  5189. }
  5190. object.parent = this;
  5191. this.children.push(object);
  5192. object.dispatchEvent(_addedEvent);
  5193. } else {
  5194. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  5195. }
  5196. return this;
  5197. },
  5198. remove: function (object) {
  5199. if (arguments.length > 1) {
  5200. for (var i = 0; i < arguments.length; i++) {
  5201. this.remove(arguments[i]);
  5202. }
  5203. return this;
  5204. }
  5205. var index = this.children.indexOf(object);
  5206. if (index !== -1) {
  5207. object.parent = null;
  5208. this.children.splice(index, 1);
  5209. object.dispatchEvent(_removedEvent);
  5210. }
  5211. return this;
  5212. },
  5213. attach: function (object) {
  5214. // adds object as a child of this, while maintaining the object's world transform
  5215. this.updateWorldMatrix(true, false);
  5216. _m1$1.getInverse(this.matrixWorld);
  5217. if (object.parent !== null) {
  5218. object.parent.updateWorldMatrix(true, false);
  5219. _m1$1.multiply(object.parent.matrixWorld);
  5220. }
  5221. object.applyMatrix(_m1$1);
  5222. object.updateWorldMatrix(false, false);
  5223. this.add(object);
  5224. return this;
  5225. },
  5226. getObjectById: function (id) {
  5227. return this.getObjectByProperty('id', id);
  5228. },
  5229. getObjectByName: function (name) {
  5230. return this.getObjectByProperty('name', name);
  5231. },
  5232. getObjectByProperty: function (name, value) {
  5233. if (this[name] === value) return this;
  5234. for (var i = 0, l = this.children.length; i < l; i++) {
  5235. var child = this.children[i];
  5236. var object = child.getObjectByProperty(name, value);
  5237. if (object !== undefined) {
  5238. return object;
  5239. }
  5240. }
  5241. return undefined;
  5242. },
  5243. getWorldPosition: function (target) {
  5244. if (target === undefined) {
  5245. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  5246. target = new Vector3();
  5247. }
  5248. this.updateMatrixWorld(true);
  5249. return target.setFromMatrixPosition(this.matrixWorld);
  5250. },
  5251. getWorldQuaternion: function (target) {
  5252. if (target === undefined) {
  5253. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  5254. target = new Quaternion();
  5255. }
  5256. this.updateMatrixWorld(true);
  5257. this.matrixWorld.decompose(_position, target, _scale);
  5258. return target;
  5259. },
  5260. getWorldScale: function (target) {
  5261. if (target === undefined) {
  5262. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  5263. target = new Vector3();
  5264. }
  5265. this.updateMatrixWorld(true);
  5266. this.matrixWorld.decompose(_position, _quaternion$2, target);
  5267. return target;
  5268. },
  5269. getWorldDirection: function (target) {
  5270. if (target === undefined) {
  5271. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  5272. target = new Vector3();
  5273. }
  5274. this.updateMatrixWorld(true);
  5275. var e = this.matrixWorld.elements;
  5276. return target.set(e[8], e[9], e[10]).normalize();
  5277. },
  5278. raycast: function () {},
  5279. traverse: function (callback) {
  5280. callback(this);
  5281. var children = this.children;
  5282. for (var i = 0, l = children.length; i < l; i++) {
  5283. children[i].traverse(callback);
  5284. }
  5285. },
  5286. traverseVisible: function (callback) {
  5287. if (this.visible === false) return;
  5288. callback(this);
  5289. var children = this.children;
  5290. for (var i = 0, l = children.length; i < l; i++) {
  5291. children[i].traverseVisible(callback);
  5292. }
  5293. },
  5294. traverseAncestors: function (callback) {
  5295. var parent = this.parent;
  5296. if (parent !== null) {
  5297. callback(parent);
  5298. parent.traverseAncestors(callback);
  5299. }
  5300. },
  5301. updateMatrix: function () {
  5302. this.matrix.compose(this.position, this.quaternion, this.scale);
  5303. this.matrixWorldNeedsUpdate = true;
  5304. },
  5305. updateMatrixWorld: function (force) {
  5306. if (this.matrixAutoUpdate) this.updateMatrix();
  5307. if (this.matrixWorldNeedsUpdate || force) {
  5308. if (this.parent === null) {
  5309. this.matrixWorld.copy(this.matrix);
  5310. } else {
  5311. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5312. }
  5313. this.matrixWorldNeedsUpdate = false;
  5314. force = true;
  5315. } // update children
  5316. var children = this.children;
  5317. for (var i = 0, l = children.length; i < l; i++) {
  5318. children[i].updateMatrixWorld(force);
  5319. }
  5320. },
  5321. updateWorldMatrix: function (updateParents, updateChildren) {
  5322. var parent = this.parent;
  5323. if (updateParents === true && parent !== null) {
  5324. parent.updateWorldMatrix(true, false);
  5325. }
  5326. if (this.matrixAutoUpdate) this.updateMatrix();
  5327. if (this.parent === null) {
  5328. this.matrixWorld.copy(this.matrix);
  5329. } else {
  5330. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5331. } // update children
  5332. if (updateChildren === true) {
  5333. var children = this.children;
  5334. for (var i = 0, l = children.length; i < l; i++) {
  5335. children[i].updateWorldMatrix(false, true);
  5336. }
  5337. }
  5338. },
  5339. toJSON: function (meta) {
  5340. // meta is a string when called from JSON.stringify
  5341. var isRootObject = meta === undefined || typeof meta === 'string';
  5342. var output = {}; // meta is a hash used to collect geometries, materials.
  5343. // not providing it implies that this is the root object
  5344. // being serialized.
  5345. if (isRootObject) {
  5346. // initialize meta obj
  5347. meta = {
  5348. geometries: {},
  5349. materials: {},
  5350. textures: {},
  5351. images: {},
  5352. shapes: {}
  5353. };
  5354. output.metadata = {
  5355. version: 4.5,
  5356. type: 'Object',
  5357. generator: 'Object3D.toJSON'
  5358. };
  5359. } // standard Object3D serialization
  5360. var object = {};
  5361. object.uuid = this.uuid;
  5362. object.type = this.type;
  5363. if (this.name !== '') object.name = this.name;
  5364. if (this.castShadow === true) object.castShadow = true;
  5365. if (this.receiveShadow === true) object.receiveShadow = true;
  5366. if (this.visible === false) object.visible = false;
  5367. if (this.frustumCulled === false) object.frustumCulled = false;
  5368. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5369. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5370. object.layers = this.layers.mask;
  5371. object.matrix = this.matrix.toArray();
  5372. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5373. if (this.isMesh && this.drawMode !== TrianglesDrawMode) object.drawMode = this.drawMode; //
  5374. function serialize(library, element) {
  5375. if (library[element.uuid] === undefined) {
  5376. library[element.uuid] = element.toJSON(meta);
  5377. }
  5378. return element.uuid;
  5379. }
  5380. if (this.isMesh || this.isLine || this.isPoints) {
  5381. object.geometry = serialize(meta.geometries, this.geometry);
  5382. var parameters = this.geometry.parameters;
  5383. if (parameters !== undefined && parameters.shapes !== undefined) {
  5384. var shapes = parameters.shapes;
  5385. if (Array.isArray(shapes)) {
  5386. for (var i = 0, l = shapes.length; i < l; i++) {
  5387. var shape = shapes[i];
  5388. serialize(meta.shapes, shape);
  5389. }
  5390. } else {
  5391. serialize(meta.shapes, shapes);
  5392. }
  5393. }
  5394. }
  5395. if (this.material !== undefined) {
  5396. if (Array.isArray(this.material)) {
  5397. var uuids = [];
  5398. for (var i = 0, l = this.material.length; i < l; i++) {
  5399. uuids.push(serialize(meta.materials, this.material[i]));
  5400. }
  5401. object.material = uuids;
  5402. } else {
  5403. object.material = serialize(meta.materials, this.material);
  5404. }
  5405. } //
  5406. if (this.children.length > 0) {
  5407. object.children = [];
  5408. for (var i = 0; i < this.children.length; i++) {
  5409. object.children.push(this.children[i].toJSON(meta).object);
  5410. }
  5411. }
  5412. if (isRootObject) {
  5413. var geometries = extractFromCache(meta.geometries);
  5414. var materials = extractFromCache(meta.materials);
  5415. var textures = extractFromCache(meta.textures);
  5416. var images = extractFromCache(meta.images);
  5417. var shapes = extractFromCache(meta.shapes);
  5418. if (geometries.length > 0) output.geometries = geometries;
  5419. if (materials.length > 0) output.materials = materials;
  5420. if (textures.length > 0) output.textures = textures;
  5421. if (images.length > 0) output.images = images;
  5422. if (shapes.length > 0) output.shapes = shapes;
  5423. }
  5424. output.object = object;
  5425. return output; // extract data from the cache hash
  5426. // remove metadata on each item
  5427. // and return as array
  5428. function extractFromCache(cache) {
  5429. var values = [];
  5430. for (var key in cache) {
  5431. var data = cache[key];
  5432. delete data.metadata;
  5433. values.push(data);
  5434. }
  5435. return values;
  5436. }
  5437. },
  5438. clone: function (recursive) {
  5439. return new this.constructor().copy(this, recursive);
  5440. },
  5441. copy: function (source, recursive) {
  5442. if (recursive === undefined) recursive = true;
  5443. this.name = source.name;
  5444. this.up.copy(source.up);
  5445. this.position.copy(source.position);
  5446. this.quaternion.copy(source.quaternion);
  5447. this.scale.copy(source.scale);
  5448. this.matrix.copy(source.matrix);
  5449. this.matrixWorld.copy(source.matrixWorld);
  5450. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5451. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5452. this.layers.mask = source.layers.mask;
  5453. this.visible = source.visible;
  5454. this.castShadow = source.castShadow;
  5455. this.receiveShadow = source.receiveShadow;
  5456. this.frustumCulled = source.frustumCulled;
  5457. this.renderOrder = source.renderOrder;
  5458. this.userData = JSON.parse(JSON.stringify(source.userData));
  5459. if (recursive === true) {
  5460. for (var i = 0; i < source.children.length; i++) {
  5461. var child = source.children[i];
  5462. this.add(child.clone());
  5463. }
  5464. }
  5465. return this;
  5466. }
  5467. });
  5468. /**
  5469. * @author mrdoob / http://mrdoob.com/
  5470. */
  5471. function Scene() {
  5472. Object3D.call(this);
  5473. this.type = 'Scene';
  5474. this.background = null;
  5475. this.fog = null;
  5476. this.overrideMaterial = null;
  5477. this.autoUpdate = true; // checked by the renderer
  5478. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  5479. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  5480. detail: this
  5481. })); // eslint-disable-line no-undef
  5482. }
  5483. }
  5484. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  5485. constructor: Scene,
  5486. isScene: true,
  5487. copy: function (source, recursive) {
  5488. Object3D.prototype.copy.call(this, source, recursive);
  5489. if (source.background !== null) this.background = source.background.clone();
  5490. if (source.fog !== null) this.fog = source.fog.clone();
  5491. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  5492. this.autoUpdate = source.autoUpdate;
  5493. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5494. return this;
  5495. },
  5496. toJSON: function (meta) {
  5497. var data = Object3D.prototype.toJSON.call(this, meta);
  5498. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  5499. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  5500. return data;
  5501. },
  5502. dispose: function () {
  5503. this.dispatchEvent({
  5504. type: 'dispose'
  5505. });
  5506. }
  5507. });
  5508. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  5509. var _vector$2 = new Vector3(); // triangle centered vertices
  5510. var _v0 = new Vector3();
  5511. var _v1$2 = new Vector3();
  5512. var _v2 = new Vector3(); // triangle edge vectors
  5513. var _f0 = new Vector3();
  5514. var _f1 = new Vector3();
  5515. var _f2 = new Vector3();
  5516. var _center = new Vector3();
  5517. var _extents = new Vector3();
  5518. var _triangleNormal = new Vector3();
  5519. var _testAxis = new Vector3();
  5520. /**
  5521. * @author bhouston / http://clara.io
  5522. * @author WestLangley / http://github.com/WestLangley
  5523. */
  5524. function Box3(min, max) {
  5525. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  5526. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  5527. }
  5528. Object.assign(Box3.prototype, {
  5529. isBox3: true,
  5530. set: function (min, max) {
  5531. this.min.copy(min);
  5532. this.max.copy(max);
  5533. return this;
  5534. },
  5535. setFromArray: function (array) {
  5536. var minX = +Infinity;
  5537. var minY = +Infinity;
  5538. var minZ = +Infinity;
  5539. var maxX = -Infinity;
  5540. var maxY = -Infinity;
  5541. var maxZ = -Infinity;
  5542. for (var i = 0, l = array.length; i < l; i += 3) {
  5543. var x = array[i];
  5544. var y = array[i + 1];
  5545. var z = array[i + 2];
  5546. if (x < minX) minX = x;
  5547. if (y < minY) minY = y;
  5548. if (z < minZ) minZ = z;
  5549. if (x > maxX) maxX = x;
  5550. if (y > maxY) maxY = y;
  5551. if (z > maxZ) maxZ = z;
  5552. }
  5553. this.min.set(minX, minY, minZ);
  5554. this.max.set(maxX, maxY, maxZ);
  5555. return this;
  5556. },
  5557. setFromBufferAttribute: function (attribute) {
  5558. var minX = +Infinity;
  5559. var minY = +Infinity;
  5560. var minZ = +Infinity;
  5561. var maxX = -Infinity;
  5562. var maxY = -Infinity;
  5563. var maxZ = -Infinity;
  5564. for (var i = 0, l = attribute.count; i < l; i++) {
  5565. var x = attribute.getX(i);
  5566. var y = attribute.getY(i);
  5567. var z = attribute.getZ(i);
  5568. if (x < minX) minX = x;
  5569. if (y < minY) minY = y;
  5570. if (z < minZ) minZ = z;
  5571. if (x > maxX) maxX = x;
  5572. if (y > maxY) maxY = y;
  5573. if (z > maxZ) maxZ = z;
  5574. }
  5575. this.min.set(minX, minY, minZ);
  5576. this.max.set(maxX, maxY, maxZ);
  5577. return this;
  5578. },
  5579. setFromPoints: function (points) {
  5580. this.makeEmpty();
  5581. for (var i = 0, il = points.length; i < il; i++) {
  5582. this.expandByPoint(points[i]);
  5583. }
  5584. return this;
  5585. },
  5586. setFromCenterAndSize: function (center, size) {
  5587. var halfSize = _vector$2.copy(size).multiplyScalar(0.5);
  5588. this.min.copy(center).sub(halfSize);
  5589. this.max.copy(center).add(halfSize);
  5590. return this;
  5591. },
  5592. setFromObject: function (object) {
  5593. this.makeEmpty();
  5594. return this.expandByObject(object);
  5595. },
  5596. clone: function () {
  5597. return new this.constructor().copy(this);
  5598. },
  5599. copy: function (box) {
  5600. this.min.copy(box.min);
  5601. this.max.copy(box.max);
  5602. return this;
  5603. },
  5604. makeEmpty: function () {
  5605. this.min.x = this.min.y = this.min.z = +Infinity;
  5606. this.max.x = this.max.y = this.max.z = -Infinity;
  5607. return this;
  5608. },
  5609. isEmpty: function () {
  5610. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5611. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  5612. },
  5613. getCenter: function (target) {
  5614. if (target === undefined) {
  5615. console.warn('THREE.Box3: .getCenter() target is now required');
  5616. target = new Vector3();
  5617. }
  5618. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  5619. },
  5620. getSize: function (target) {
  5621. if (target === undefined) {
  5622. console.warn('THREE.Box3: .getSize() target is now required');
  5623. target = new Vector3();
  5624. }
  5625. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  5626. },
  5627. expandByPoint: function (point) {
  5628. this.min.min(point);
  5629. this.max.max(point);
  5630. return this;
  5631. },
  5632. expandByVector: function (vector) {
  5633. this.min.sub(vector);
  5634. this.max.add(vector);
  5635. return this;
  5636. },
  5637. expandByScalar: function (scalar) {
  5638. this.min.addScalar(-scalar);
  5639. this.max.addScalar(scalar);
  5640. return this;
  5641. },
  5642. expandByObject: function (object) {
  5643. var i, l; // Computes the world-axis-aligned bounding box of an object (including its children),
  5644. // accounting for both the object's, and children's, world transforms
  5645. object.updateWorldMatrix(false, false);
  5646. var geometry = object.geometry;
  5647. if (geometry !== undefined) {
  5648. if (geometry.isGeometry) {
  5649. var vertices = geometry.vertices;
  5650. for (i = 0, l = vertices.length; i < l; i++) {
  5651. _vector$2.copy(vertices[i]);
  5652. _vector$2.applyMatrix4(object.matrixWorld);
  5653. this.expandByPoint(_vector$2);
  5654. }
  5655. } else if (geometry.isBufferGeometry) {
  5656. var attribute = geometry.attributes.position;
  5657. if (attribute !== undefined) {
  5658. for (i = 0, l = attribute.count; i < l; i++) {
  5659. _vector$2.fromBufferAttribute(attribute, i).applyMatrix4(object.matrixWorld);
  5660. this.expandByPoint(_vector$2);
  5661. }
  5662. }
  5663. }
  5664. } //
  5665. var children = object.children;
  5666. for (i = 0, l = children.length; i < l; i++) {
  5667. this.expandByObject(children[i]);
  5668. }
  5669. return this;
  5670. },
  5671. containsPoint: function (point) {
  5672. 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;
  5673. },
  5674. containsBox: function (box) {
  5675. 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;
  5676. },
  5677. getParameter: function (point, target) {
  5678. // This can potentially have a divide by zero if the box
  5679. // has a size dimension of 0.
  5680. if (target === undefined) {
  5681. console.warn('THREE.Box3: .getParameter() target is now required');
  5682. target = new Vector3();
  5683. }
  5684. 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));
  5685. },
  5686. intersectsBox: function (box) {
  5687. // using 6 splitting planes to rule out intersections.
  5688. 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;
  5689. },
  5690. intersectsSphere: function (sphere) {
  5691. // Find the point on the AABB closest to the sphere center.
  5692. this.clampPoint(sphere.center, _vector$2); // If that point is inside the sphere, the AABB and sphere intersect.
  5693. return _vector$2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  5694. },
  5695. intersectsPlane: function (plane) {
  5696. // We compute the minimum and maximum dot product values. If those values
  5697. // are on the same side (back or front) of the plane, then there is no intersection.
  5698. var min, max;
  5699. if (plane.normal.x > 0) {
  5700. min = plane.normal.x * this.min.x;
  5701. max = plane.normal.x * this.max.x;
  5702. } else {
  5703. min = plane.normal.x * this.max.x;
  5704. max = plane.normal.x * this.min.x;
  5705. }
  5706. if (plane.normal.y > 0) {
  5707. min += plane.normal.y * this.min.y;
  5708. max += plane.normal.y * this.max.y;
  5709. } else {
  5710. min += plane.normal.y * this.max.y;
  5711. max += plane.normal.y * this.min.y;
  5712. }
  5713. if (plane.normal.z > 0) {
  5714. min += plane.normal.z * this.min.z;
  5715. max += plane.normal.z * this.max.z;
  5716. } else {
  5717. min += plane.normal.z * this.max.z;
  5718. max += plane.normal.z * this.min.z;
  5719. }
  5720. return min <= -plane.constant && max >= -plane.constant;
  5721. },
  5722. intersectsTriangle: function (triangle) {
  5723. if (this.isEmpty()) {
  5724. return false;
  5725. } // compute box center and extents
  5726. this.getCenter(_center);
  5727. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  5728. _v0.subVectors(triangle.a, _center);
  5729. _v1$2.subVectors(triangle.b, _center);
  5730. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  5731. _f0.subVectors(_v1$2, _v0);
  5732. _f1.subVectors(_v2, _v1$2);
  5733. _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
  5734. // 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
  5735. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  5736. 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];
  5737. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5738. return false;
  5739. } // test 3 face normals from the aabb
  5740. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  5741. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5742. return false;
  5743. } // finally testing the face normal of the triangle
  5744. // use already existing triangle edge vectors here
  5745. _triangleNormal.crossVectors(_f0, _f1);
  5746. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  5747. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  5748. },
  5749. clampPoint: function (point, target) {
  5750. if (target === undefined) {
  5751. console.warn('THREE.Box3: .clampPoint() target is now required');
  5752. target = new Vector3();
  5753. }
  5754. return target.copy(point).clamp(this.min, this.max);
  5755. },
  5756. distanceToPoint: function (point) {
  5757. var clampedPoint = _vector$2.copy(point).clamp(this.min, this.max);
  5758. return clampedPoint.sub(point).length();
  5759. },
  5760. getBoundingSphere: function (target) {
  5761. if (target === undefined) {
  5762. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  5763. }
  5764. this.getCenter(target.center);
  5765. target.radius = this.getSize(_vector$2).length() * 0.5;
  5766. return target;
  5767. },
  5768. intersect: function (box) {
  5769. this.min.max(box.min);
  5770. 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.
  5771. if (this.isEmpty()) this.makeEmpty();
  5772. return this;
  5773. },
  5774. union: function (box) {
  5775. this.min.min(box.min);
  5776. this.max.max(box.max);
  5777. return this;
  5778. },
  5779. applyMatrix4: function (matrix) {
  5780. // transform of empty box is an empty box.
  5781. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5782. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  5783. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  5784. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  5785. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  5786. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  5787. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  5788. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  5789. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  5790. this.setFromPoints(_points);
  5791. return this;
  5792. },
  5793. translate: function (offset) {
  5794. this.min.add(offset);
  5795. this.max.add(offset);
  5796. return this;
  5797. },
  5798. equals: function (box) {
  5799. return box.min.equals(this.min) && box.max.equals(this.max);
  5800. }
  5801. });
  5802. function satForAxes(axes, v0, v1, v2, extents) {
  5803. var i, j;
  5804. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  5805. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  5806. 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
  5807. var p0 = v0.dot(_testAxis);
  5808. var p1 = v1.dot(_testAxis);
  5809. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  5810. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  5811. // points of the projected triangle are outside the projected half-length of the aabb
  5812. // the axis is seperating and we can exit
  5813. return false;
  5814. }
  5815. }
  5816. return true;
  5817. }
  5818. var _box = new Box3();
  5819. /**
  5820. * @author bhouston / http://clara.io
  5821. * @author mrdoob / http://mrdoob.com/
  5822. */
  5823. function Sphere(center, radius) {
  5824. this.center = center !== undefined ? center : new Vector3();
  5825. this.radius = radius !== undefined ? radius : 0;
  5826. }
  5827. Object.assign(Sphere.prototype, {
  5828. set: function (center, radius) {
  5829. this.center.copy(center);
  5830. this.radius = radius;
  5831. return this;
  5832. },
  5833. setFromPoints: function (points, optionalCenter) {
  5834. var center = this.center;
  5835. if (optionalCenter !== undefined) {
  5836. center.copy(optionalCenter);
  5837. } else {
  5838. _box.setFromPoints(points).getCenter(center);
  5839. }
  5840. var maxRadiusSq = 0;
  5841. for (var i = 0, il = points.length; i < il; i++) {
  5842. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  5843. }
  5844. this.radius = Math.sqrt(maxRadiusSq);
  5845. return this;
  5846. },
  5847. clone: function () {
  5848. return new this.constructor().copy(this);
  5849. },
  5850. copy: function (sphere) {
  5851. this.center.copy(sphere.center);
  5852. this.radius = sphere.radius;
  5853. return this;
  5854. },
  5855. empty: function () {
  5856. return this.radius <= 0;
  5857. },
  5858. containsPoint: function (point) {
  5859. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  5860. },
  5861. distanceToPoint: function (point) {
  5862. return point.distanceTo(this.center) - this.radius;
  5863. },
  5864. intersectsSphere: function (sphere) {
  5865. var radiusSum = this.radius + sphere.radius;
  5866. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  5867. },
  5868. intersectsBox: function (box) {
  5869. return box.intersectsSphere(this);
  5870. },
  5871. intersectsPlane: function (plane) {
  5872. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  5873. },
  5874. clampPoint: function (point, target) {
  5875. var deltaLengthSq = this.center.distanceToSquared(point);
  5876. if (target === undefined) {
  5877. console.warn('THREE.Sphere: .clampPoint() target is now required');
  5878. target = new Vector3();
  5879. }
  5880. target.copy(point);
  5881. if (deltaLengthSq > this.radius * this.radius) {
  5882. target.sub(this.center).normalize();
  5883. target.multiplyScalar(this.radius).add(this.center);
  5884. }
  5885. return target;
  5886. },
  5887. getBoundingBox: function (target) {
  5888. if (target === undefined) {
  5889. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  5890. target = new Box3();
  5891. }
  5892. target.set(this.center, this.center);
  5893. target.expandByScalar(this.radius);
  5894. return target;
  5895. },
  5896. applyMatrix4: function (matrix) {
  5897. this.center.applyMatrix4(matrix);
  5898. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5899. return this;
  5900. },
  5901. translate: function (offset) {
  5902. this.center.add(offset);
  5903. return this;
  5904. },
  5905. equals: function (sphere) {
  5906. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  5907. }
  5908. });
  5909. var _vector$3 = new Vector3();
  5910. var _segCenter = new Vector3();
  5911. var _segDir = new Vector3();
  5912. var _diff = new Vector3();
  5913. var _edge1 = new Vector3();
  5914. var _edge2 = new Vector3();
  5915. var _normal = new Vector3();
  5916. /**
  5917. * @author bhouston / http://clara.io
  5918. */
  5919. function Ray(origin, direction) {
  5920. this.origin = origin !== undefined ? origin : new Vector3();
  5921. this.direction = direction !== undefined ? direction : new Vector3();
  5922. }
  5923. Object.assign(Ray.prototype, {
  5924. set: function (origin, direction) {
  5925. this.origin.copy(origin);
  5926. this.direction.copy(direction);
  5927. return this;
  5928. },
  5929. clone: function () {
  5930. return new this.constructor().copy(this);
  5931. },
  5932. copy: function (ray) {
  5933. this.origin.copy(ray.origin);
  5934. this.direction.copy(ray.direction);
  5935. return this;
  5936. },
  5937. at: function (t, target) {
  5938. if (target === undefined) {
  5939. console.warn('THREE.Ray: .at() target is now required');
  5940. target = new Vector3();
  5941. }
  5942. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  5943. },
  5944. lookAt: function (v) {
  5945. this.direction.copy(v).sub(this.origin).normalize();
  5946. return this;
  5947. },
  5948. recast: function (t) {
  5949. this.origin.copy(this.at(t, _vector$3));
  5950. return this;
  5951. },
  5952. closestPointToPoint: function (point, target) {
  5953. if (target === undefined) {
  5954. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  5955. target = new Vector3();
  5956. }
  5957. target.subVectors(point, this.origin);
  5958. var directionDistance = target.dot(this.direction);
  5959. if (directionDistance < 0) {
  5960. return target.copy(this.origin);
  5961. }
  5962. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5963. },
  5964. distanceToPoint: function (point) {
  5965. return Math.sqrt(this.distanceSqToPoint(point));
  5966. },
  5967. distanceSqToPoint: function (point) {
  5968. var directionDistance = _vector$3.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  5969. if (directionDistance < 0) {
  5970. return this.origin.distanceToSquared(point);
  5971. }
  5972. _vector$3.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5973. return _vector$3.distanceToSquared(point);
  5974. },
  5975. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  5976. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5977. // It returns the min distance between the ray and the segment
  5978. // defined by v0 and v1
  5979. // It can also set two optional targets :
  5980. // - The closest point on the ray
  5981. // - The closest point on the segment
  5982. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  5983. _segDir.copy(v1).sub(v0).normalize();
  5984. _diff.copy(this.origin).sub(_segCenter);
  5985. var segExtent = v0.distanceTo(v1) * 0.5;
  5986. var a01 = -this.direction.dot(_segDir);
  5987. var b0 = _diff.dot(this.direction);
  5988. var b1 = -_diff.dot(_segDir);
  5989. var c = _diff.lengthSq();
  5990. var det = Math.abs(1 - a01 * a01);
  5991. var s0, s1, sqrDist, extDet;
  5992. if (det > 0) {
  5993. // The ray and segment are not parallel.
  5994. s0 = a01 * b1 - b0;
  5995. s1 = a01 * b0 - b1;
  5996. extDet = segExtent * det;
  5997. if (s0 >= 0) {
  5998. if (s1 >= -extDet) {
  5999. if (s1 <= extDet) {
  6000. // region 0
  6001. // Minimum at interior points of ray and segment.
  6002. var invDet = 1 / det;
  6003. s0 *= invDet;
  6004. s1 *= invDet;
  6005. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  6006. } else {
  6007. // region 1
  6008. s1 = segExtent;
  6009. s0 = Math.max(0, -(a01 * s1 + b0));
  6010. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6011. }
  6012. } else {
  6013. // region 5
  6014. s1 = -segExtent;
  6015. s0 = Math.max(0, -(a01 * s1 + b0));
  6016. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6017. }
  6018. } else {
  6019. if (s1 <= -extDet) {
  6020. // region 4
  6021. s0 = Math.max(0, -(-a01 * segExtent + b0));
  6022. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  6023. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6024. } else if (s1 <= extDet) {
  6025. // region 3
  6026. s0 = 0;
  6027. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  6028. sqrDist = s1 * (s1 + 2 * b1) + c;
  6029. } else {
  6030. // region 2
  6031. s0 = Math.max(0, -(a01 * segExtent + b0));
  6032. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  6033. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6034. }
  6035. }
  6036. } else {
  6037. // Ray and segment are parallel.
  6038. s1 = a01 > 0 ? -segExtent : segExtent;
  6039. s0 = Math.max(0, -(a01 * s1 + b0));
  6040. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6041. }
  6042. if (optionalPointOnRay) {
  6043. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  6044. }
  6045. if (optionalPointOnSegment) {
  6046. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  6047. }
  6048. return sqrDist;
  6049. },
  6050. intersectSphere: function (sphere, target) {
  6051. _vector$3.subVectors(sphere.center, this.origin);
  6052. var tca = _vector$3.dot(this.direction);
  6053. var d2 = _vector$3.dot(_vector$3) - tca * tca;
  6054. var radius2 = sphere.radius * sphere.radius;
  6055. if (d2 > radius2) return null;
  6056. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  6057. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  6058. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  6059. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  6060. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6061. // in order to always return an intersect point that is in front of the ray.
  6062. 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
  6063. return this.at(t0, target);
  6064. },
  6065. intersectsSphere: function (sphere) {
  6066. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  6067. },
  6068. distanceToPlane: function (plane) {
  6069. var denominator = plane.normal.dot(this.direction);
  6070. if (denominator === 0) {
  6071. // line is coplanar, return origin
  6072. if (plane.distanceToPoint(this.origin) === 0) {
  6073. return 0;
  6074. } // Null is preferable to undefined since undefined means.... it is undefined
  6075. return null;
  6076. }
  6077. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  6078. return t >= 0 ? t : null;
  6079. },
  6080. intersectPlane: function (plane, target) {
  6081. var t = this.distanceToPlane(plane);
  6082. if (t === null) {
  6083. return null;
  6084. }
  6085. return this.at(t, target);
  6086. },
  6087. intersectsPlane: function (plane) {
  6088. // check if the ray lies on the plane first
  6089. var distToPoint = plane.distanceToPoint(this.origin);
  6090. if (distToPoint === 0) {
  6091. return true;
  6092. }
  6093. var denominator = plane.normal.dot(this.direction);
  6094. if (denominator * distToPoint < 0) {
  6095. return true;
  6096. } // ray origin is behind the plane (and is pointing behind it)
  6097. return false;
  6098. },
  6099. intersectBox: function (box, target) {
  6100. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6101. var invdirx = 1 / this.direction.x,
  6102. invdiry = 1 / this.direction.y,
  6103. invdirz = 1 / this.direction.z;
  6104. var origin = this.origin;
  6105. if (invdirx >= 0) {
  6106. tmin = (box.min.x - origin.x) * invdirx;
  6107. tmax = (box.max.x - origin.x) * invdirx;
  6108. } else {
  6109. tmin = (box.max.x - origin.x) * invdirx;
  6110. tmax = (box.min.x - origin.x) * invdirx;
  6111. }
  6112. if (invdiry >= 0) {
  6113. tymin = (box.min.y - origin.y) * invdiry;
  6114. tymax = (box.max.y - origin.y) * invdiry;
  6115. } else {
  6116. tymin = (box.max.y - origin.y) * invdiry;
  6117. tymax = (box.min.y - origin.y) * invdiry;
  6118. }
  6119. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  6120. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6121. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  6122. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  6123. if (invdirz >= 0) {
  6124. tzmin = (box.min.z - origin.z) * invdirz;
  6125. tzmax = (box.max.z - origin.z) * invdirz;
  6126. } else {
  6127. tzmin = (box.max.z - origin.z) * invdirz;
  6128. tzmax = (box.min.z - origin.z) * invdirz;
  6129. }
  6130. if (tmin > tzmax || tzmin > tmax) return null;
  6131. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  6132. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  6133. if (tmax < 0) return null;
  6134. return this.at(tmin >= 0 ? tmin : tmax, target);
  6135. },
  6136. intersectsBox: function (box) {
  6137. return this.intersectBox(box, _vector$3) !== null;
  6138. },
  6139. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  6140. // Compute the offset origin, edges, and normal.
  6141. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6142. _edge1.subVectors(b, a);
  6143. _edge2.subVectors(c, a);
  6144. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6145. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6146. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6147. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6148. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6149. var DdN = this.direction.dot(_normal);
  6150. var sign;
  6151. if (DdN > 0) {
  6152. if (backfaceCulling) return null;
  6153. sign = 1;
  6154. } else if (DdN < 0) {
  6155. sign = -1;
  6156. DdN = -DdN;
  6157. } else {
  6158. return null;
  6159. }
  6160. _diff.subVectors(this.origin, a);
  6161. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  6162. if (DdQxE2 < 0) {
  6163. return null;
  6164. }
  6165. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  6166. if (DdE1xQ < 0) {
  6167. return null;
  6168. } // b1+b2 > 1, no intersection
  6169. if (DdQxE2 + DdE1xQ > DdN) {
  6170. return null;
  6171. } // Line intersects triangle, check if ray does.
  6172. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  6173. if (QdN < 0) {
  6174. return null;
  6175. } // Ray intersects triangle.
  6176. return this.at(QdN / DdN, target);
  6177. },
  6178. applyMatrix4: function (matrix4) {
  6179. this.origin.applyMatrix4(matrix4);
  6180. this.direction.transformDirection(matrix4);
  6181. return this;
  6182. },
  6183. equals: function (ray) {
  6184. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  6185. }
  6186. });
  6187. /**
  6188. * @author bhouston / http://clara.io
  6189. * @author mrdoob / http://mrdoob.com/
  6190. */
  6191. var _v0$1 = new Vector3();
  6192. var _v1$3 = new Vector3();
  6193. var _v2$1 = new Vector3();
  6194. var _v3 = new Vector3();
  6195. var _vab = new Vector3();
  6196. var _vac = new Vector3();
  6197. var _vbc = new Vector3();
  6198. var _vap = new Vector3();
  6199. var _vbp = new Vector3();
  6200. var _vcp = new Vector3();
  6201. function Triangle(a, b, c) {
  6202. this.a = a !== undefined ? a : new Vector3();
  6203. this.b = b !== undefined ? b : new Vector3();
  6204. this.c = c !== undefined ? c : new Vector3();
  6205. }
  6206. Object.assign(Triangle, {
  6207. getNormal: function (a, b, c, target) {
  6208. if (target === undefined) {
  6209. console.warn('THREE.Triangle: .getNormal() target is now required');
  6210. target = new Vector3();
  6211. }
  6212. target.subVectors(c, b);
  6213. _v0$1.subVectors(a, b);
  6214. target.cross(_v0$1);
  6215. var targetLengthSq = target.lengthSq();
  6216. if (targetLengthSq > 0) {
  6217. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  6218. }
  6219. return target.set(0, 0, 0);
  6220. },
  6221. // static/instance method to calculate barycentric coordinates
  6222. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6223. getBarycoord: function (point, a, b, c, target) {
  6224. _v0$1.subVectors(c, a);
  6225. _v1$3.subVectors(b, a);
  6226. _v2$1.subVectors(point, a);
  6227. var dot00 = _v0$1.dot(_v0$1);
  6228. var dot01 = _v0$1.dot(_v1$3);
  6229. var dot02 = _v0$1.dot(_v2$1);
  6230. var dot11 = _v1$3.dot(_v1$3);
  6231. var dot12 = _v1$3.dot(_v2$1);
  6232. var denom = dot00 * dot11 - dot01 * dot01;
  6233. if (target === undefined) {
  6234. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  6235. target = new Vector3();
  6236. } // collinear or singular triangle
  6237. if (denom === 0) {
  6238. // arbitrary location outside of triangle?
  6239. // not sure if this is the best idea, maybe should be returning undefined
  6240. return target.set(-2, -1, -1);
  6241. }
  6242. var invDenom = 1 / denom;
  6243. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  6244. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  6245. return target.set(1 - u - v, v, u);
  6246. },
  6247. containsPoint: function (point, a, b, c) {
  6248. Triangle.getBarycoord(point, a, b, c, _v3);
  6249. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  6250. },
  6251. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  6252. this.getBarycoord(point, p1, p2, p3, _v3);
  6253. target.set(0, 0);
  6254. target.addScaledVector(uv1, _v3.x);
  6255. target.addScaledVector(uv2, _v3.y);
  6256. target.addScaledVector(uv3, _v3.z);
  6257. return target;
  6258. },
  6259. isFrontFacing: function (a, b, c, direction) {
  6260. _v0$1.subVectors(c, b);
  6261. _v1$3.subVectors(a, b); // strictly front facing
  6262. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  6263. }
  6264. });
  6265. Object.assign(Triangle.prototype, {
  6266. set: function (a, b, c) {
  6267. this.a.copy(a);
  6268. this.b.copy(b);
  6269. this.c.copy(c);
  6270. return this;
  6271. },
  6272. setFromPointsAndIndices: function (points, i0, i1, i2) {
  6273. this.a.copy(points[i0]);
  6274. this.b.copy(points[i1]);
  6275. this.c.copy(points[i2]);
  6276. return this;
  6277. },
  6278. clone: function () {
  6279. return new this.constructor().copy(this);
  6280. },
  6281. copy: function (triangle) {
  6282. this.a.copy(triangle.a);
  6283. this.b.copy(triangle.b);
  6284. this.c.copy(triangle.c);
  6285. return this;
  6286. },
  6287. getArea: function () {
  6288. _v0$1.subVectors(this.c, this.b);
  6289. _v1$3.subVectors(this.a, this.b);
  6290. return _v0$1.cross(_v1$3).length() * 0.5;
  6291. },
  6292. getMidpoint: function (target) {
  6293. if (target === undefined) {
  6294. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  6295. target = new Vector3();
  6296. }
  6297. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  6298. },
  6299. getNormal: function (target) {
  6300. return Triangle.getNormal(this.a, this.b, this.c, target);
  6301. },
  6302. getPlane: function (target) {
  6303. if (target === undefined) {
  6304. console.warn('THREE.Triangle: .getPlane() target is now required');
  6305. target = new Vector3();
  6306. }
  6307. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  6308. },
  6309. getBarycoord: function (point, target) {
  6310. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  6311. },
  6312. getUV: function (point, uv1, uv2, uv3, target) {
  6313. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  6314. },
  6315. containsPoint: function (point) {
  6316. return Triangle.containsPoint(point, this.a, this.b, this.c);
  6317. },
  6318. isFrontFacing: function (direction) {
  6319. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  6320. },
  6321. intersectsBox: function (box) {
  6322. return box.intersectsTriangle(this);
  6323. },
  6324. closestPointToPoint: function (p, target) {
  6325. if (target === undefined) {
  6326. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  6327. target = new Vector3();
  6328. }
  6329. var a = this.a,
  6330. b = this.b,
  6331. c = this.c;
  6332. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  6333. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  6334. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  6335. // basically, we're distinguishing which of the voronoi regions of the triangle
  6336. // the point lies in with the minimum amount of redundant computation.
  6337. _vab.subVectors(b, a);
  6338. _vac.subVectors(c, a);
  6339. _vap.subVectors(p, a);
  6340. var d1 = _vab.dot(_vap);
  6341. var d2 = _vac.dot(_vap);
  6342. if (d1 <= 0 && d2 <= 0) {
  6343. // vertex region of A; barycentric coords (1, 0, 0)
  6344. return target.copy(a);
  6345. }
  6346. _vbp.subVectors(p, b);
  6347. var d3 = _vab.dot(_vbp);
  6348. var d4 = _vac.dot(_vbp);
  6349. if (d3 >= 0 && d4 <= d3) {
  6350. // vertex region of B; barycentric coords (0, 1, 0)
  6351. return target.copy(b);
  6352. }
  6353. var vc = d1 * d4 - d3 * d2;
  6354. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  6355. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  6356. return target.copy(a).addScaledVector(_vab, v);
  6357. }
  6358. _vcp.subVectors(p, c);
  6359. var d5 = _vab.dot(_vcp);
  6360. var d6 = _vac.dot(_vcp);
  6361. if (d6 >= 0 && d5 <= d6) {
  6362. // vertex region of C; barycentric coords (0, 0, 1)
  6363. return target.copy(c);
  6364. }
  6365. var vb = d5 * d2 - d1 * d6;
  6366. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  6367. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  6368. return target.copy(a).addScaledVector(_vac, w);
  6369. }
  6370. var va = d3 * d6 - d5 * d4;
  6371. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  6372. _vbc.subVectors(c, b);
  6373. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  6374. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  6375. } // face region
  6376. var denom = 1 / (va + vb + vc); // u = va * denom
  6377. v = vb * denom;
  6378. w = vc * denom;
  6379. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  6380. },
  6381. equals: function (triangle) {
  6382. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  6383. }
  6384. });
  6385. /**
  6386. * @author mrdoob / http://mrdoob.com/
  6387. */
  6388. var _colorKeywords = {
  6389. 'aliceblue': 0xF0F8FF,
  6390. 'antiquewhite': 0xFAEBD7,
  6391. 'aqua': 0x00FFFF,
  6392. 'aquamarine': 0x7FFFD4,
  6393. 'azure': 0xF0FFFF,
  6394. 'beige': 0xF5F5DC,
  6395. 'bisque': 0xFFE4C4,
  6396. 'black': 0x000000,
  6397. 'blanchedalmond': 0xFFEBCD,
  6398. 'blue': 0x0000FF,
  6399. 'blueviolet': 0x8A2BE2,
  6400. 'brown': 0xA52A2A,
  6401. 'burlywood': 0xDEB887,
  6402. 'cadetblue': 0x5F9EA0,
  6403. 'chartreuse': 0x7FFF00,
  6404. 'chocolate': 0xD2691E,
  6405. 'coral': 0xFF7F50,
  6406. 'cornflowerblue': 0x6495ED,
  6407. 'cornsilk': 0xFFF8DC,
  6408. 'crimson': 0xDC143C,
  6409. 'cyan': 0x00FFFF,
  6410. 'darkblue': 0x00008B,
  6411. 'darkcyan': 0x008B8B,
  6412. 'darkgoldenrod': 0xB8860B,
  6413. 'darkgray': 0xA9A9A9,
  6414. 'darkgreen': 0x006400,
  6415. 'darkgrey': 0xA9A9A9,
  6416. 'darkkhaki': 0xBDB76B,
  6417. 'darkmagenta': 0x8B008B,
  6418. 'darkolivegreen': 0x556B2F,
  6419. 'darkorange': 0xFF8C00,
  6420. 'darkorchid': 0x9932CC,
  6421. 'darkred': 0x8B0000,
  6422. 'darksalmon': 0xE9967A,
  6423. 'darkseagreen': 0x8FBC8F,
  6424. 'darkslateblue': 0x483D8B,
  6425. 'darkslategray': 0x2F4F4F,
  6426. 'darkslategrey': 0x2F4F4F,
  6427. 'darkturquoise': 0x00CED1,
  6428. 'darkviolet': 0x9400D3,
  6429. 'deeppink': 0xFF1493,
  6430. 'deepskyblue': 0x00BFFF,
  6431. 'dimgray': 0x696969,
  6432. 'dimgrey': 0x696969,
  6433. 'dodgerblue': 0x1E90FF,
  6434. 'firebrick': 0xB22222,
  6435. 'floralwhite': 0xFFFAF0,
  6436. 'forestgreen': 0x228B22,
  6437. 'fuchsia': 0xFF00FF,
  6438. 'gainsboro': 0xDCDCDC,
  6439. 'ghostwhite': 0xF8F8FF,
  6440. 'gold': 0xFFD700,
  6441. 'goldenrod': 0xDAA520,
  6442. 'gray': 0x808080,
  6443. 'green': 0x008000,
  6444. 'greenyellow': 0xADFF2F,
  6445. 'grey': 0x808080,
  6446. 'honeydew': 0xF0FFF0,
  6447. 'hotpink': 0xFF69B4,
  6448. 'indianred': 0xCD5C5C,
  6449. 'indigo': 0x4B0082,
  6450. 'ivory': 0xFFFFF0,
  6451. 'khaki': 0xF0E68C,
  6452. 'lavender': 0xE6E6FA,
  6453. 'lavenderblush': 0xFFF0F5,
  6454. 'lawngreen': 0x7CFC00,
  6455. 'lemonchiffon': 0xFFFACD,
  6456. 'lightblue': 0xADD8E6,
  6457. 'lightcoral': 0xF08080,
  6458. 'lightcyan': 0xE0FFFF,
  6459. 'lightgoldenrodyellow': 0xFAFAD2,
  6460. 'lightgray': 0xD3D3D3,
  6461. 'lightgreen': 0x90EE90,
  6462. 'lightgrey': 0xD3D3D3,
  6463. 'lightpink': 0xFFB6C1,
  6464. 'lightsalmon': 0xFFA07A,
  6465. 'lightseagreen': 0x20B2AA,
  6466. 'lightskyblue': 0x87CEFA,
  6467. 'lightslategray': 0x778899,
  6468. 'lightslategrey': 0x778899,
  6469. 'lightsteelblue': 0xB0C4DE,
  6470. 'lightyellow': 0xFFFFE0,
  6471. 'lime': 0x00FF00,
  6472. 'limegreen': 0x32CD32,
  6473. 'linen': 0xFAF0E6,
  6474. 'magenta': 0xFF00FF,
  6475. 'maroon': 0x800000,
  6476. 'mediumaquamarine': 0x66CDAA,
  6477. 'mediumblue': 0x0000CD,
  6478. 'mediumorchid': 0xBA55D3,
  6479. 'mediumpurple': 0x9370DB,
  6480. 'mediumseagreen': 0x3CB371,
  6481. 'mediumslateblue': 0x7B68EE,
  6482. 'mediumspringgreen': 0x00FA9A,
  6483. 'mediumturquoise': 0x48D1CC,
  6484. 'mediumvioletred': 0xC71585,
  6485. 'midnightblue': 0x191970,
  6486. 'mintcream': 0xF5FFFA,
  6487. 'mistyrose': 0xFFE4E1,
  6488. 'moccasin': 0xFFE4B5,
  6489. 'navajowhite': 0xFFDEAD,
  6490. 'navy': 0x000080,
  6491. 'oldlace': 0xFDF5E6,
  6492. 'olive': 0x808000,
  6493. 'olivedrab': 0x6B8E23,
  6494. 'orange': 0xFFA500,
  6495. 'orangered': 0xFF4500,
  6496. 'orchid': 0xDA70D6,
  6497. 'palegoldenrod': 0xEEE8AA,
  6498. 'palegreen': 0x98FB98,
  6499. 'paleturquoise': 0xAFEEEE,
  6500. 'palevioletred': 0xDB7093,
  6501. 'papayawhip': 0xFFEFD5,
  6502. 'peachpuff': 0xFFDAB9,
  6503. 'peru': 0xCD853F,
  6504. 'pink': 0xFFC0CB,
  6505. 'plum': 0xDDA0DD,
  6506. 'powderblue': 0xB0E0E6,
  6507. 'purple': 0x800080,
  6508. 'rebeccapurple': 0x663399,
  6509. 'red': 0xFF0000,
  6510. 'rosybrown': 0xBC8F8F,
  6511. 'royalblue': 0x4169E1,
  6512. 'saddlebrown': 0x8B4513,
  6513. 'salmon': 0xFA8072,
  6514. 'sandybrown': 0xF4A460,
  6515. 'seagreen': 0x2E8B57,
  6516. 'seashell': 0xFFF5EE,
  6517. 'sienna': 0xA0522D,
  6518. 'silver': 0xC0C0C0,
  6519. 'skyblue': 0x87CEEB,
  6520. 'slateblue': 0x6A5ACD,
  6521. 'slategray': 0x708090,
  6522. 'slategrey': 0x708090,
  6523. 'snow': 0xFFFAFA,
  6524. 'springgreen': 0x00FF7F,
  6525. 'steelblue': 0x4682B4,
  6526. 'tan': 0xD2B48C,
  6527. 'teal': 0x008080,
  6528. 'thistle': 0xD8BFD8,
  6529. 'tomato': 0xFF6347,
  6530. 'turquoise': 0x40E0D0,
  6531. 'violet': 0xEE82EE,
  6532. 'wheat': 0xF5DEB3,
  6533. 'white': 0xFFFFFF,
  6534. 'whitesmoke': 0xF5F5F5,
  6535. 'yellow': 0xFFFF00,
  6536. 'yellowgreen': 0x9ACD32
  6537. };
  6538. var _hslA = {
  6539. h: 0,
  6540. s: 0,
  6541. l: 0
  6542. };
  6543. var _hslB = {
  6544. h: 0,
  6545. s: 0,
  6546. l: 0
  6547. };
  6548. function Color(r, g, b) {
  6549. if (g === undefined && b === undefined) {
  6550. // r is THREE.Color, hex or string
  6551. return this.set(r);
  6552. }
  6553. return this.setRGB(r, g, b);
  6554. }
  6555. function hue2rgb(p, q, t) {
  6556. if (t < 0) t += 1;
  6557. if (t > 1) t -= 1;
  6558. if (t < 1 / 6) return p + (q - p) * 6 * t;
  6559. if (t < 1 / 2) return q;
  6560. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  6561. return p;
  6562. }
  6563. function SRGBToLinear(c) {
  6564. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  6565. }
  6566. function LinearToSRGB(c) {
  6567. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  6568. }
  6569. Object.assign(Color.prototype, {
  6570. isColor: true,
  6571. r: 1,
  6572. g: 1,
  6573. b: 1,
  6574. set: function (value) {
  6575. if (value && value.isColor) {
  6576. this.copy(value);
  6577. } else if (typeof value === 'number') {
  6578. this.setHex(value);
  6579. } else if (typeof value === 'string') {
  6580. this.setStyle(value);
  6581. }
  6582. return this;
  6583. },
  6584. setScalar: function (scalar) {
  6585. this.r = scalar;
  6586. this.g = scalar;
  6587. this.b = scalar;
  6588. return this;
  6589. },
  6590. setHex: function (hex) {
  6591. hex = Math.floor(hex);
  6592. this.r = (hex >> 16 & 255) / 255;
  6593. this.g = (hex >> 8 & 255) / 255;
  6594. this.b = (hex & 255) / 255;
  6595. return this;
  6596. },
  6597. setRGB: function (r, g, b) {
  6598. this.r = r;
  6599. this.g = g;
  6600. this.b = b;
  6601. return this;
  6602. },
  6603. setHSL: function (h, s, l) {
  6604. // h,s,l ranges are in 0.0 - 1.0
  6605. h = _Math.euclideanModulo(h, 1);
  6606. s = _Math.clamp(s, 0, 1);
  6607. l = _Math.clamp(l, 0, 1);
  6608. if (s === 0) {
  6609. this.r = this.g = this.b = l;
  6610. } else {
  6611. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  6612. var q = 2 * l - p;
  6613. this.r = hue2rgb(q, p, h + 1 / 3);
  6614. this.g = hue2rgb(q, p, h);
  6615. this.b = hue2rgb(q, p, h - 1 / 3);
  6616. }
  6617. return this;
  6618. },
  6619. setStyle: function (style) {
  6620. function handleAlpha(string) {
  6621. if (string === undefined) return;
  6622. if (parseFloat(string) < 1) {
  6623. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  6624. }
  6625. }
  6626. var m;
  6627. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  6628. // rgb / hsl
  6629. var color;
  6630. var name = m[1];
  6631. var components = m[2];
  6632. switch (name) {
  6633. case 'rgb':
  6634. case 'rgba':
  6635. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6636. // rgb(255,0,0) rgba(255,0,0,0.5)
  6637. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  6638. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  6639. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  6640. handleAlpha(color[5]);
  6641. return this;
  6642. }
  6643. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6644. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  6645. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  6646. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  6647. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  6648. handleAlpha(color[5]);
  6649. return this;
  6650. }
  6651. break;
  6652. case 'hsl':
  6653. case 'hsla':
  6654. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6655. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  6656. var h = parseFloat(color[1]) / 360;
  6657. var s = parseInt(color[2], 10) / 100;
  6658. var l = parseInt(color[3], 10) / 100;
  6659. handleAlpha(color[5]);
  6660. return this.setHSL(h, s, l);
  6661. }
  6662. break;
  6663. }
  6664. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  6665. // hex color
  6666. var hex = m[1];
  6667. var size = hex.length;
  6668. if (size === 3) {
  6669. // #ff0
  6670. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  6671. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  6672. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  6673. return this;
  6674. } else if (size === 6) {
  6675. // #ff0000
  6676. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  6677. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  6678. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  6679. return this;
  6680. }
  6681. }
  6682. if (style && style.length > 0) {
  6683. // color keywords
  6684. var hex = _colorKeywords[style];
  6685. if (hex !== undefined) {
  6686. // red
  6687. this.setHex(hex);
  6688. } else {
  6689. // unknown color
  6690. console.warn('THREE.Color: Unknown color ' + style);
  6691. }
  6692. }
  6693. return this;
  6694. },
  6695. clone: function () {
  6696. return new this.constructor(this.r, this.g, this.b);
  6697. },
  6698. copy: function (color) {
  6699. this.r = color.r;
  6700. this.g = color.g;
  6701. this.b = color.b;
  6702. return this;
  6703. },
  6704. copyGammaToLinear: function (color, gammaFactor) {
  6705. if (gammaFactor === undefined) gammaFactor = 2.0;
  6706. this.r = Math.pow(color.r, gammaFactor);
  6707. this.g = Math.pow(color.g, gammaFactor);
  6708. this.b = Math.pow(color.b, gammaFactor);
  6709. return this;
  6710. },
  6711. copyLinearToGamma: function (color, gammaFactor) {
  6712. if (gammaFactor === undefined) gammaFactor = 2.0;
  6713. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  6714. this.r = Math.pow(color.r, safeInverse);
  6715. this.g = Math.pow(color.g, safeInverse);
  6716. this.b = Math.pow(color.b, safeInverse);
  6717. return this;
  6718. },
  6719. convertGammaToLinear: function (gammaFactor) {
  6720. this.copyGammaToLinear(this, gammaFactor);
  6721. return this;
  6722. },
  6723. convertLinearToGamma: function (gammaFactor) {
  6724. this.copyLinearToGamma(this, gammaFactor);
  6725. return this;
  6726. },
  6727. copySRGBToLinear: function (color) {
  6728. this.r = SRGBToLinear(color.r);
  6729. this.g = SRGBToLinear(color.g);
  6730. this.b = SRGBToLinear(color.b);
  6731. return this;
  6732. },
  6733. copyLinearToSRGB: function (color) {
  6734. this.r = LinearToSRGB(color.r);
  6735. this.g = LinearToSRGB(color.g);
  6736. this.b = LinearToSRGB(color.b);
  6737. return this;
  6738. },
  6739. convertSRGBToLinear: function () {
  6740. this.copySRGBToLinear(this);
  6741. return this;
  6742. },
  6743. convertLinearToSRGB: function () {
  6744. this.copyLinearToSRGB(this);
  6745. return this;
  6746. },
  6747. getHex: function () {
  6748. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  6749. },
  6750. getHexString: function () {
  6751. return ('000000' + this.getHex().toString(16)).slice(-6);
  6752. },
  6753. getHSL: function (target) {
  6754. // h,s,l ranges are in 0.0 - 1.0
  6755. if (target === undefined) {
  6756. console.warn('THREE.Color: .getHSL() target is now required');
  6757. target = {
  6758. h: 0,
  6759. s: 0,
  6760. l: 0
  6761. };
  6762. }
  6763. var r = this.r,
  6764. g = this.g,
  6765. b = this.b;
  6766. var max = Math.max(r, g, b);
  6767. var min = Math.min(r, g, b);
  6768. var hue, saturation;
  6769. var lightness = (min + max) / 2.0;
  6770. if (min === max) {
  6771. hue = 0;
  6772. saturation = 0;
  6773. } else {
  6774. var delta = max - min;
  6775. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  6776. switch (max) {
  6777. case r:
  6778. hue = (g - b) / delta + (g < b ? 6 : 0);
  6779. break;
  6780. case g:
  6781. hue = (b - r) / delta + 2;
  6782. break;
  6783. case b:
  6784. hue = (r - g) / delta + 4;
  6785. break;
  6786. }
  6787. hue /= 6;
  6788. }
  6789. target.h = hue;
  6790. target.s = saturation;
  6791. target.l = lightness;
  6792. return target;
  6793. },
  6794. getStyle: function () {
  6795. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  6796. },
  6797. offsetHSL: function (h, s, l) {
  6798. this.getHSL(_hslA);
  6799. _hslA.h += h;
  6800. _hslA.s += s;
  6801. _hslA.l += l;
  6802. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  6803. return this;
  6804. },
  6805. add: function (color) {
  6806. this.r += color.r;
  6807. this.g += color.g;
  6808. this.b += color.b;
  6809. return this;
  6810. },
  6811. addColors: function (color1, color2) {
  6812. this.r = color1.r + color2.r;
  6813. this.g = color1.g + color2.g;
  6814. this.b = color1.b + color2.b;
  6815. return this;
  6816. },
  6817. addScalar: function (s) {
  6818. this.r += s;
  6819. this.g += s;
  6820. this.b += s;
  6821. return this;
  6822. },
  6823. sub: function (color) {
  6824. this.r = Math.max(0, this.r - color.r);
  6825. this.g = Math.max(0, this.g - color.g);
  6826. this.b = Math.max(0, this.b - color.b);
  6827. return this;
  6828. },
  6829. multiply: function (color) {
  6830. this.r *= color.r;
  6831. this.g *= color.g;
  6832. this.b *= color.b;
  6833. return this;
  6834. },
  6835. multiplyScalar: function (s) {
  6836. this.r *= s;
  6837. this.g *= s;
  6838. this.b *= s;
  6839. return this;
  6840. },
  6841. lerp: function (color, alpha) {
  6842. this.r += (color.r - this.r) * alpha;
  6843. this.g += (color.g - this.g) * alpha;
  6844. this.b += (color.b - this.b) * alpha;
  6845. return this;
  6846. },
  6847. lerpHSL: function (color, alpha) {
  6848. this.getHSL(_hslA);
  6849. color.getHSL(_hslB);
  6850. var h = _Math.lerp(_hslA.h, _hslB.h, alpha);
  6851. var s = _Math.lerp(_hslA.s, _hslB.s, alpha);
  6852. var l = _Math.lerp(_hslA.l, _hslB.l, alpha);
  6853. this.setHSL(h, s, l);
  6854. return this;
  6855. },
  6856. equals: function (c) {
  6857. return c.r === this.r && c.g === this.g && c.b === this.b;
  6858. },
  6859. fromArray: function (array, offset) {
  6860. if (offset === undefined) offset = 0;
  6861. this.r = array[offset];
  6862. this.g = array[offset + 1];
  6863. this.b = array[offset + 2];
  6864. return this;
  6865. },
  6866. toArray: function (array, offset) {
  6867. if (array === undefined) array = [];
  6868. if (offset === undefined) offset = 0;
  6869. array[offset] = this.r;
  6870. array[offset + 1] = this.g;
  6871. array[offset + 2] = this.b;
  6872. return array;
  6873. },
  6874. toJSON: function () {
  6875. return this.getHex();
  6876. }
  6877. });
  6878. /**
  6879. * @author mrdoob / http://mrdoob.com/
  6880. * @author alteredq / http://alteredqualia.com/
  6881. */
  6882. function Face3(a, b, c, normal, color, materialIndex) {
  6883. this.a = a;
  6884. this.b = b;
  6885. this.c = c;
  6886. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  6887. this.vertexNormals = Array.isArray(normal) ? normal : [];
  6888. this.color = color && color.isColor ? color : new Color();
  6889. this.vertexColors = Array.isArray(color) ? color : [];
  6890. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6891. }
  6892. Object.assign(Face3.prototype, {
  6893. clone: function () {
  6894. return new this.constructor().copy(this);
  6895. },
  6896. copy: function (source) {
  6897. this.a = source.a;
  6898. this.b = source.b;
  6899. this.c = source.c;
  6900. this.normal.copy(source.normal);
  6901. this.color.copy(source.color);
  6902. this.materialIndex = source.materialIndex;
  6903. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  6904. this.vertexNormals[i] = source.vertexNormals[i].clone();
  6905. }
  6906. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  6907. this.vertexColors[i] = source.vertexColors[i].clone();
  6908. }
  6909. return this;
  6910. }
  6911. });
  6912. /**
  6913. * @author mrdoob / http://mrdoob.com/
  6914. * @author alteredq / http://alteredqualia.com/
  6915. */
  6916. var materialId = 0;
  6917. function Material() {
  6918. Object.defineProperty(this, 'id', {
  6919. value: materialId++
  6920. });
  6921. this.uuid = _Math.generateUUID();
  6922. this.name = '';
  6923. this.type = 'Material';
  6924. this.fog = true;
  6925. this.blending = NormalBlending;
  6926. this.side = FrontSide;
  6927. this.flatShading = false;
  6928. this.vertexTangents = false;
  6929. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  6930. this.opacity = 1;
  6931. this.transparent = false;
  6932. this.blendSrc = SrcAlphaFactor;
  6933. this.blendDst = OneMinusSrcAlphaFactor;
  6934. this.blendEquation = AddEquation;
  6935. this.blendSrcAlpha = null;
  6936. this.blendDstAlpha = null;
  6937. this.blendEquationAlpha = null;
  6938. this.depthFunc = LessEqualDepth;
  6939. this.depthTest = true;
  6940. this.depthWrite = true;
  6941. this.stencilWriteMask = 0xff;
  6942. this.stencilFunc = AlwaysStencilFunc;
  6943. this.stencilRef = 0;
  6944. this.stencilFuncMask = 0xff;
  6945. this.stencilFail = KeepStencilOp;
  6946. this.stencilZFail = KeepStencilOp;
  6947. this.stencilZPass = KeepStencilOp;
  6948. this.stencilWrite = false;
  6949. this.clippingPlanes = null;
  6950. this.clipIntersection = false;
  6951. this.clipShadows = false;
  6952. this.shadowSide = null;
  6953. this.colorWrite = true;
  6954. this.precision = null; // override the renderer's default precision for this material
  6955. this.polygonOffset = false;
  6956. this.polygonOffsetFactor = 0;
  6957. this.polygonOffsetUnits = 0;
  6958. this.dithering = false;
  6959. this.alphaTest = 0;
  6960. this.premultipliedAlpha = false;
  6961. this.visible = true;
  6962. this.toneMapped = true;
  6963. this.userData = {};
  6964. this.needsUpdate = true;
  6965. }
  6966. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6967. constructor: Material,
  6968. isMaterial: true,
  6969. onBeforeCompile: function () {},
  6970. setValues: function (values) {
  6971. if (values === undefined) return;
  6972. for (var key in values) {
  6973. var newValue = values[key];
  6974. if (newValue === undefined) {
  6975. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  6976. continue;
  6977. } // for backward compatability if shading is set in the constructor
  6978. if (key === 'shading') {
  6979. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  6980. this.flatShading = newValue === FlatShading ? true : false;
  6981. continue;
  6982. }
  6983. var currentValue = this[key];
  6984. if (currentValue === undefined) {
  6985. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6986. continue;
  6987. }
  6988. if (currentValue && currentValue.isColor) {
  6989. currentValue.set(newValue);
  6990. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6991. currentValue.copy(newValue);
  6992. } else {
  6993. this[key] = newValue;
  6994. }
  6995. }
  6996. },
  6997. toJSON: function (meta) {
  6998. var isRoot = meta === undefined || typeof meta === 'string';
  6999. if (isRoot) {
  7000. meta = {
  7001. textures: {},
  7002. images: {}
  7003. };
  7004. }
  7005. var data = {
  7006. metadata: {
  7007. version: 4.5,
  7008. type: 'Material',
  7009. generator: 'Material.toJSON'
  7010. }
  7011. }; // standard Material serialization
  7012. data.uuid = this.uuid;
  7013. data.type = this.type;
  7014. if (this.name !== '') data.name = this.name;
  7015. if (this.color && this.color.isColor) data.color = this.color.getHex();
  7016. if (this.roughness !== undefined) data.roughness = this.roughness;
  7017. if (this.metalness !== undefined) data.metalness = this.metalness;
  7018. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  7019. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  7020. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  7021. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  7022. if (this.shininess !== undefined) data.shininess = this.shininess;
  7023. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  7024. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  7025. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  7026. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  7027. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  7028. }
  7029. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  7030. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  7031. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  7032. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  7033. if (this.aoMap && this.aoMap.isTexture) {
  7034. data.aoMap = this.aoMap.toJSON(meta).uuid;
  7035. data.aoMapIntensity = this.aoMapIntensity;
  7036. }
  7037. if (this.bumpMap && this.bumpMap.isTexture) {
  7038. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  7039. data.bumpScale = this.bumpScale;
  7040. }
  7041. if (this.normalMap && this.normalMap.isTexture) {
  7042. data.normalMap = this.normalMap.toJSON(meta).uuid;
  7043. data.normalMapType = this.normalMapType;
  7044. data.normalScale = this.normalScale.toArray();
  7045. }
  7046. if (this.displacementMap && this.displacementMap.isTexture) {
  7047. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  7048. data.displacementScale = this.displacementScale;
  7049. data.displacementBias = this.displacementBias;
  7050. }
  7051. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  7052. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  7053. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  7054. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  7055. if (this.envMap && this.envMap.isTexture) {
  7056. data.envMap = this.envMap.toJSON(meta).uuid;
  7057. data.reflectivity = this.reflectivity; // Scale behind envMap
  7058. data.refractionRatio = this.refractionRatio;
  7059. if (this.combine !== undefined) data.combine = this.combine;
  7060. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  7061. }
  7062. if (this.gradientMap && this.gradientMap.isTexture) {
  7063. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  7064. }
  7065. if (this.size !== undefined) data.size = this.size;
  7066. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  7067. if (this.blending !== NormalBlending) data.blending = this.blending;
  7068. if (this.flatShading === true) data.flatShading = this.flatShading;
  7069. if (this.side !== FrontSide) data.side = this.side;
  7070. if (this.vertexColors !== NoColors) data.vertexColors = this.vertexColors;
  7071. if (this.opacity < 1) data.opacity = this.opacity;
  7072. if (this.transparent === true) data.transparent = this.transparent;
  7073. data.depthFunc = this.depthFunc;
  7074. data.depthTest = this.depthTest;
  7075. data.depthWrite = this.depthWrite;
  7076. data.stencilWrite = this.stencilWrite;
  7077. data.stencilWriteMask = this.stencilWriteMask;
  7078. data.stencilFunc = this.stencilFunc;
  7079. data.stencilRef = this.stencilRef;
  7080. data.stencilFuncMask = this.stencilFuncMask;
  7081. data.stencilFail = this.stencilFail;
  7082. data.stencilZFail = this.stencilZFail;
  7083. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  7084. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  7085. if (this.polygonOffset === true) data.polygonOffset = true;
  7086. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  7087. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  7088. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  7089. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  7090. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  7091. if (this.scale !== undefined) data.scale = this.scale;
  7092. if (this.dithering === true) data.dithering = true;
  7093. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  7094. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  7095. if (this.wireframe === true) data.wireframe = this.wireframe;
  7096. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  7097. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  7098. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  7099. if (this.morphTargets === true) data.morphTargets = true;
  7100. if (this.morphNormals === true) data.morphNormals = true;
  7101. if (this.skinning === true) data.skinning = true;
  7102. if (this.visible === false) data.visible = false;
  7103. if (this.toneMapped === false) data.toneMapped = false;
  7104. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  7105. function extractFromCache(cache) {
  7106. var values = [];
  7107. for (var key in cache) {
  7108. var data = cache[key];
  7109. delete data.metadata;
  7110. values.push(data);
  7111. }
  7112. return values;
  7113. }
  7114. if (isRoot) {
  7115. var textures = extractFromCache(meta.textures);
  7116. var images = extractFromCache(meta.images);
  7117. if (textures.length > 0) data.textures = textures;
  7118. if (images.length > 0) data.images = images;
  7119. }
  7120. return data;
  7121. },
  7122. clone: function () {
  7123. return new this.constructor().copy(this);
  7124. },
  7125. copy: function (source) {
  7126. this.name = source.name;
  7127. this.fog = source.fog;
  7128. this.blending = source.blending;
  7129. this.side = source.side;
  7130. this.flatShading = source.flatShading;
  7131. this.vertexColors = source.vertexColors;
  7132. this.opacity = source.opacity;
  7133. this.transparent = source.transparent;
  7134. this.blendSrc = source.blendSrc;
  7135. this.blendDst = source.blendDst;
  7136. this.blendEquation = source.blendEquation;
  7137. this.blendSrcAlpha = source.blendSrcAlpha;
  7138. this.blendDstAlpha = source.blendDstAlpha;
  7139. this.blendEquationAlpha = source.blendEquationAlpha;
  7140. this.depthFunc = source.depthFunc;
  7141. this.depthTest = source.depthTest;
  7142. this.depthWrite = source.depthWrite;
  7143. this.stencilWrite = source.stencilWrite;
  7144. this.stencilWriteMask = source.stencilWriteMask;
  7145. this.stencilFunc = source.stencilFunc;
  7146. this.stencilRef = source.stencilRef;
  7147. this.stencilFuncMask = source.stencilFuncMask;
  7148. this.stencilFail = source.stencilFail;
  7149. this.stencilZFail = source.stencilZFail;
  7150. this.stencilZPass = source.stencilZPass;
  7151. this.colorWrite = source.colorWrite;
  7152. this.precision = source.precision;
  7153. this.polygonOffset = source.polygonOffset;
  7154. this.polygonOffsetFactor = source.polygonOffsetFactor;
  7155. this.polygonOffsetUnits = source.polygonOffsetUnits;
  7156. this.dithering = source.dithering;
  7157. this.alphaTest = source.alphaTest;
  7158. this.premultipliedAlpha = source.premultipliedAlpha;
  7159. this.visible = source.visible;
  7160. this.toneMapped = source.toneMapped;
  7161. this.userData = JSON.parse(JSON.stringify(source.userData));
  7162. this.clipShadows = source.clipShadows;
  7163. this.clipIntersection = source.clipIntersection;
  7164. var srcPlanes = source.clippingPlanes,
  7165. dstPlanes = null;
  7166. if (srcPlanes !== null) {
  7167. var n = srcPlanes.length;
  7168. dstPlanes = new Array(n);
  7169. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  7170. }
  7171. this.clippingPlanes = dstPlanes;
  7172. this.shadowSide = source.shadowSide;
  7173. return this;
  7174. },
  7175. dispose: function () {
  7176. this.dispatchEvent({
  7177. type: 'dispose'
  7178. });
  7179. }
  7180. });
  7181. /**
  7182. * @author mrdoob / http://mrdoob.com/
  7183. * @author alteredq / http://alteredqualia.com/
  7184. *
  7185. * parameters = {
  7186. * color: <hex>,
  7187. * opacity: <float>,
  7188. * map: new THREE.Texture( <Image> ),
  7189. *
  7190. * lightMap: new THREE.Texture( <Image> ),
  7191. * lightMapIntensity: <float>
  7192. *
  7193. * aoMap: new THREE.Texture( <Image> ),
  7194. * aoMapIntensity: <float>
  7195. *
  7196. * specularMap: new THREE.Texture( <Image> ),
  7197. *
  7198. * alphaMap: new THREE.Texture( <Image> ),
  7199. *
  7200. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  7201. * combine: THREE.Multiply,
  7202. * reflectivity: <float>,
  7203. * refractionRatio: <float>,
  7204. *
  7205. * depthTest: <bool>,
  7206. * depthWrite: <bool>,
  7207. *
  7208. * wireframe: <boolean>,
  7209. * wireframeLinewidth: <float>,
  7210. *
  7211. * skinning: <bool>,
  7212. * morphTargets: <bool>
  7213. * }
  7214. */
  7215. function MeshBasicMaterial(parameters) {
  7216. Material.call(this);
  7217. this.type = 'MeshBasicMaterial';
  7218. this.color = new Color(0xffffff); // emissive
  7219. this.map = null;
  7220. this.lightMap = null;
  7221. this.lightMapIntensity = 1.0;
  7222. this.aoMap = null;
  7223. this.aoMapIntensity = 1.0;
  7224. this.specularMap = null;
  7225. this.alphaMap = null;
  7226. this.envMap = null;
  7227. this.combine = MultiplyOperation;
  7228. this.reflectivity = 1;
  7229. this.refractionRatio = 0.98;
  7230. this.wireframe = false;
  7231. this.wireframeLinewidth = 1;
  7232. this.wireframeLinecap = 'round';
  7233. this.wireframeLinejoin = 'round';
  7234. this.skinning = false;
  7235. this.morphTargets = false;
  7236. this.setValues(parameters);
  7237. }
  7238. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  7239. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7240. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7241. MeshBasicMaterial.prototype.copy = function (source) {
  7242. Material.prototype.copy.call(this, source);
  7243. this.color.copy(source.color);
  7244. this.map = source.map;
  7245. this.lightMap = source.lightMap;
  7246. this.lightMapIntensity = source.lightMapIntensity;
  7247. this.aoMap = source.aoMap;
  7248. this.aoMapIntensity = source.aoMapIntensity;
  7249. this.specularMap = source.specularMap;
  7250. this.alphaMap = source.alphaMap;
  7251. this.envMap = source.envMap;
  7252. this.combine = source.combine;
  7253. this.reflectivity = source.reflectivity;
  7254. this.refractionRatio = source.refractionRatio;
  7255. this.wireframe = source.wireframe;
  7256. this.wireframeLinewidth = source.wireframeLinewidth;
  7257. this.wireframeLinecap = source.wireframeLinecap;
  7258. this.wireframeLinejoin = source.wireframeLinejoin;
  7259. this.skinning = source.skinning;
  7260. this.morphTargets = source.morphTargets;
  7261. return this;
  7262. };
  7263. /**
  7264. * @author mrdoob / http://mrdoob.com/
  7265. */
  7266. function BufferAttribute(array, itemSize, normalized) {
  7267. if (Array.isArray(array)) {
  7268. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  7269. }
  7270. this.name = '';
  7271. this.array = array;
  7272. this.itemSize = itemSize;
  7273. this.count = array !== undefined ? array.length / itemSize : 0;
  7274. this.normalized = normalized === true;
  7275. this.dynamic = false;
  7276. this.updateRange = {
  7277. offset: 0,
  7278. count: -1
  7279. };
  7280. this.version = 0;
  7281. }
  7282. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  7283. set: function (value) {
  7284. if (value === true) this.version++;
  7285. }
  7286. });
  7287. Object.assign(BufferAttribute.prototype, {
  7288. isBufferAttribute: true,
  7289. onUploadCallback: function () {},
  7290. setDynamic: function (value) {
  7291. this.dynamic = value;
  7292. return this;
  7293. },
  7294. copy: function (source) {
  7295. this.name = source.name;
  7296. this.array = new source.array.constructor(source.array);
  7297. this.itemSize = source.itemSize;
  7298. this.count = source.count;
  7299. this.normalized = source.normalized;
  7300. this.dynamic = source.dynamic;
  7301. return this;
  7302. },
  7303. copyAt: function (index1, attribute, index2) {
  7304. index1 *= this.itemSize;
  7305. index2 *= attribute.itemSize;
  7306. for (var i = 0, l = this.itemSize; i < l; i++) {
  7307. this.array[index1 + i] = attribute.array[index2 + i];
  7308. }
  7309. return this;
  7310. },
  7311. copyArray: function (array) {
  7312. this.array.set(array);
  7313. return this;
  7314. },
  7315. copyColorsArray: function (colors) {
  7316. var array = this.array,
  7317. offset = 0;
  7318. for (var i = 0, l = colors.length; i < l; i++) {
  7319. var color = colors[i];
  7320. if (color === undefined) {
  7321. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  7322. color = new Color();
  7323. }
  7324. array[offset++] = color.r;
  7325. array[offset++] = color.g;
  7326. array[offset++] = color.b;
  7327. }
  7328. return this;
  7329. },
  7330. copyVector2sArray: function (vectors) {
  7331. var array = this.array,
  7332. offset = 0;
  7333. for (var i = 0, l = vectors.length; i < l; i++) {
  7334. var vector = vectors[i];
  7335. if (vector === undefined) {
  7336. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  7337. vector = new Vector2();
  7338. }
  7339. array[offset++] = vector.x;
  7340. array[offset++] = vector.y;
  7341. }
  7342. return this;
  7343. },
  7344. copyVector3sArray: function (vectors) {
  7345. var array = this.array,
  7346. offset = 0;
  7347. for (var i = 0, l = vectors.length; i < l; i++) {
  7348. var vector = vectors[i];
  7349. if (vector === undefined) {
  7350. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  7351. vector = new Vector3();
  7352. }
  7353. array[offset++] = vector.x;
  7354. array[offset++] = vector.y;
  7355. array[offset++] = vector.z;
  7356. }
  7357. return this;
  7358. },
  7359. copyVector4sArray: function (vectors) {
  7360. var array = this.array,
  7361. offset = 0;
  7362. for (var i = 0, l = vectors.length; i < l; i++) {
  7363. var vector = vectors[i];
  7364. if (vector === undefined) {
  7365. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  7366. vector = new Vector4();
  7367. }
  7368. array[offset++] = vector.x;
  7369. array[offset++] = vector.y;
  7370. array[offset++] = vector.z;
  7371. array[offset++] = vector.w;
  7372. }
  7373. return this;
  7374. },
  7375. set: function (value, offset) {
  7376. if (offset === undefined) offset = 0;
  7377. this.array.set(value, offset);
  7378. return this;
  7379. },
  7380. getX: function (index) {
  7381. return this.array[index * this.itemSize];
  7382. },
  7383. setX: function (index, x) {
  7384. this.array[index * this.itemSize] = x;
  7385. return this;
  7386. },
  7387. getY: function (index) {
  7388. return this.array[index * this.itemSize + 1];
  7389. },
  7390. setY: function (index, y) {
  7391. this.array[index * this.itemSize + 1] = y;
  7392. return this;
  7393. },
  7394. getZ: function (index) {
  7395. return this.array[index * this.itemSize + 2];
  7396. },
  7397. setZ: function (index, z) {
  7398. this.array[index * this.itemSize + 2] = z;
  7399. return this;
  7400. },
  7401. getW: function (index) {
  7402. return this.array[index * this.itemSize + 3];
  7403. },
  7404. setW: function (index, w) {
  7405. this.array[index * this.itemSize + 3] = w;
  7406. return this;
  7407. },
  7408. setXY: function (index, x, y) {
  7409. index *= this.itemSize;
  7410. this.array[index + 0] = x;
  7411. this.array[index + 1] = y;
  7412. return this;
  7413. },
  7414. setXYZ: function (index, x, y, z) {
  7415. index *= this.itemSize;
  7416. this.array[index + 0] = x;
  7417. this.array[index + 1] = y;
  7418. this.array[index + 2] = z;
  7419. return this;
  7420. },
  7421. setXYZW: function (index, x, y, z, w) {
  7422. index *= this.itemSize;
  7423. this.array[index + 0] = x;
  7424. this.array[index + 1] = y;
  7425. this.array[index + 2] = z;
  7426. this.array[index + 3] = w;
  7427. return this;
  7428. },
  7429. onUpload: function (callback) {
  7430. this.onUploadCallback = callback;
  7431. return this;
  7432. },
  7433. clone: function () {
  7434. return new this.constructor(this.array, this.itemSize).copy(this);
  7435. },
  7436. toJSON: function () {
  7437. return {
  7438. itemSize: this.itemSize,
  7439. type: this.array.constructor.name,
  7440. array: Array.prototype.slice.call(this.array),
  7441. normalized: this.normalized
  7442. };
  7443. }
  7444. }); //
  7445. function Int8BufferAttribute(array, itemSize, normalized) {
  7446. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  7447. }
  7448. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7449. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7450. function Uint8BufferAttribute(array, itemSize, normalized) {
  7451. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  7452. }
  7453. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7454. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7455. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  7456. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  7457. }
  7458. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7459. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7460. function Int16BufferAttribute(array, itemSize, normalized) {
  7461. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  7462. }
  7463. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7464. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7465. function Uint16BufferAttribute(array, itemSize, normalized) {
  7466. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  7467. }
  7468. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7469. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7470. function Int32BufferAttribute(array, itemSize, normalized) {
  7471. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  7472. }
  7473. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7474. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7475. function Uint32BufferAttribute(array, itemSize, normalized) {
  7476. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  7477. }
  7478. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7479. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7480. function Float32BufferAttribute(array, itemSize, normalized) {
  7481. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  7482. }
  7483. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7484. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7485. function Float64BufferAttribute(array, itemSize, normalized) {
  7486. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  7487. }
  7488. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7489. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7490. /**
  7491. * @author mrdoob / http://mrdoob.com/
  7492. */
  7493. function DirectGeometry() {
  7494. this.vertices = [];
  7495. this.normals = [];
  7496. this.colors = [];
  7497. this.uvs = [];
  7498. this.uvs2 = [];
  7499. this.groups = [];
  7500. this.morphTargets = {};
  7501. this.skinWeights = [];
  7502. this.skinIndices = []; // this.lineDistances = [];
  7503. this.boundingBox = null;
  7504. this.boundingSphere = null; // update flags
  7505. this.verticesNeedUpdate = false;
  7506. this.normalsNeedUpdate = false;
  7507. this.colorsNeedUpdate = false;
  7508. this.uvsNeedUpdate = false;
  7509. this.groupsNeedUpdate = false;
  7510. }
  7511. Object.assign(DirectGeometry.prototype, {
  7512. computeGroups: function (geometry) {
  7513. var group;
  7514. var groups = [];
  7515. var materialIndex = undefined;
  7516. var faces = geometry.faces;
  7517. for (var i = 0; i < faces.length; i++) {
  7518. var face = faces[i]; // materials
  7519. if (face.materialIndex !== materialIndex) {
  7520. materialIndex = face.materialIndex;
  7521. if (group !== undefined) {
  7522. group.count = i * 3 - group.start;
  7523. groups.push(group);
  7524. }
  7525. group = {
  7526. start: i * 3,
  7527. materialIndex: materialIndex
  7528. };
  7529. }
  7530. }
  7531. if (group !== undefined) {
  7532. group.count = i * 3 - group.start;
  7533. groups.push(group);
  7534. }
  7535. this.groups = groups;
  7536. },
  7537. fromGeometry: function (geometry) {
  7538. var faces = geometry.faces;
  7539. var vertices = geometry.vertices;
  7540. var faceVertexUvs = geometry.faceVertexUvs;
  7541. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  7542. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  7543. var morphTargets = geometry.morphTargets;
  7544. var morphTargetsLength = morphTargets.length;
  7545. var morphTargetsPosition;
  7546. if (morphTargetsLength > 0) {
  7547. morphTargetsPosition = [];
  7548. for (var i = 0; i < morphTargetsLength; i++) {
  7549. morphTargetsPosition[i] = {
  7550. name: morphTargets[i].name,
  7551. data: []
  7552. };
  7553. }
  7554. this.morphTargets.position = morphTargetsPosition;
  7555. }
  7556. var morphNormals = geometry.morphNormals;
  7557. var morphNormalsLength = morphNormals.length;
  7558. var morphTargetsNormal;
  7559. if (morphNormalsLength > 0) {
  7560. morphTargetsNormal = [];
  7561. for (var i = 0; i < morphNormalsLength; i++) {
  7562. morphTargetsNormal[i] = {
  7563. name: morphNormals[i].name,
  7564. data: []
  7565. };
  7566. }
  7567. this.morphTargets.normal = morphTargetsNormal;
  7568. } // skins
  7569. var skinIndices = geometry.skinIndices;
  7570. var skinWeights = geometry.skinWeights;
  7571. var hasSkinIndices = skinIndices.length === vertices.length;
  7572. var hasSkinWeights = skinWeights.length === vertices.length; //
  7573. if (vertices.length > 0 && faces.length === 0) {
  7574. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  7575. }
  7576. for (var i = 0; i < faces.length; i++) {
  7577. var face = faces[i];
  7578. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  7579. var vertexNormals = face.vertexNormals;
  7580. if (vertexNormals.length === 3) {
  7581. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  7582. } else {
  7583. var normal = face.normal;
  7584. this.normals.push(normal, normal, normal);
  7585. }
  7586. var vertexColors = face.vertexColors;
  7587. if (vertexColors.length === 3) {
  7588. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  7589. } else {
  7590. var color = face.color;
  7591. this.colors.push(color, color, color);
  7592. }
  7593. if (hasFaceVertexUv === true) {
  7594. var vertexUvs = faceVertexUvs[0][i];
  7595. if (vertexUvs !== undefined) {
  7596. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7597. } else {
  7598. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  7599. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  7600. }
  7601. }
  7602. if (hasFaceVertexUv2 === true) {
  7603. var vertexUvs = faceVertexUvs[1][i];
  7604. if (vertexUvs !== undefined) {
  7605. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7606. } else {
  7607. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  7608. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  7609. }
  7610. } // morphs
  7611. for (var j = 0; j < morphTargetsLength; j++) {
  7612. var morphTarget = morphTargets[j].vertices;
  7613. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  7614. }
  7615. for (var j = 0; j < morphNormalsLength; j++) {
  7616. var morphNormal = morphNormals[j].vertexNormals[i];
  7617. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  7618. } // skins
  7619. if (hasSkinIndices) {
  7620. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  7621. }
  7622. if (hasSkinWeights) {
  7623. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  7624. }
  7625. }
  7626. this.computeGroups(geometry);
  7627. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7628. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7629. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7630. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7631. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7632. if (geometry.boundingSphere !== null) {
  7633. this.boundingSphere = geometry.boundingSphere.clone();
  7634. }
  7635. if (geometry.boundingBox !== null) {
  7636. this.boundingBox = geometry.boundingBox.clone();
  7637. }
  7638. return this;
  7639. }
  7640. });
  7641. /**
  7642. * @author mrdoob / http://mrdoob.com/
  7643. */
  7644. function arrayMax(array) {
  7645. if (array.length === 0) return -Infinity;
  7646. var max = array[0];
  7647. for (var i = 1, l = array.length; i < l; ++i) {
  7648. if (array[i] > max) max = array[i];
  7649. }
  7650. return max;
  7651. }
  7652. /**
  7653. * @author alteredq / http://alteredqualia.com/
  7654. * @author mrdoob / http://mrdoob.com/
  7655. */
  7656. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  7657. var _m1$2 = new Matrix4();
  7658. var _obj = new Object3D();
  7659. var _offset = new Vector3();
  7660. var _box$1 = new Box3();
  7661. var _boxMorphTargets = new Box3();
  7662. var _vector$4 = new Vector3();
  7663. function BufferGeometry() {
  7664. Object.defineProperty(this, 'id', {
  7665. value: _bufferGeometryId += 2
  7666. });
  7667. this.uuid = _Math.generateUUID();
  7668. this.name = '';
  7669. this.type = 'BufferGeometry';
  7670. this.index = null;
  7671. this.attributes = {};
  7672. this.morphAttributes = {};
  7673. this.groups = [];
  7674. this.boundingBox = null;
  7675. this.boundingSphere = null;
  7676. this.drawRange = {
  7677. start: 0,
  7678. count: Infinity
  7679. };
  7680. this.userData = {};
  7681. }
  7682. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7683. constructor: BufferGeometry,
  7684. isBufferGeometry: true,
  7685. getIndex: function () {
  7686. return this.index;
  7687. },
  7688. setIndex: function (index) {
  7689. if (Array.isArray(index)) {
  7690. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  7691. } else {
  7692. this.index = index;
  7693. }
  7694. },
  7695. addAttribute: function (name, attribute) {
  7696. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  7697. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  7698. return this.addAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  7699. }
  7700. if (name === 'index') {
  7701. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  7702. this.setIndex(attribute);
  7703. return this;
  7704. }
  7705. return this.setAttribute(name, attribute);
  7706. },
  7707. getAttribute: function (name) {
  7708. return this.attributes[name];
  7709. },
  7710. setAttribute: function (name, attribute) {
  7711. this.attributes[name] = attribute;
  7712. return this;
  7713. },
  7714. removeAttribute: function (name) {
  7715. delete this.attributes[name];
  7716. return this;
  7717. },
  7718. addGroup: function (start, count, materialIndex) {
  7719. this.groups.push({
  7720. start: start,
  7721. count: count,
  7722. materialIndex: materialIndex !== undefined ? materialIndex : 0
  7723. });
  7724. },
  7725. clearGroups: function () {
  7726. this.groups = [];
  7727. },
  7728. setDrawRange: function (start, count) {
  7729. this.drawRange.start = start;
  7730. this.drawRange.count = count;
  7731. },
  7732. applyMatrix: function (matrix) {
  7733. var position = this.attributes.position;
  7734. if (position !== undefined) {
  7735. matrix.applyToBufferAttribute(position);
  7736. position.needsUpdate = true;
  7737. }
  7738. var normal = this.attributes.normal;
  7739. if (normal !== undefined) {
  7740. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7741. normalMatrix.applyToBufferAttribute(normal);
  7742. normal.needsUpdate = true;
  7743. }
  7744. var tangent = this.attributes.tangent;
  7745. if (tangent !== undefined) {
  7746. var normalMatrix = new Matrix3().getNormalMatrix(matrix); // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  7747. normalMatrix.applyToBufferAttribute(tangent);
  7748. tangent.needsUpdate = true;
  7749. }
  7750. if (this.boundingBox !== null) {
  7751. this.computeBoundingBox();
  7752. }
  7753. if (this.boundingSphere !== null) {
  7754. this.computeBoundingSphere();
  7755. }
  7756. return this;
  7757. },
  7758. rotateX: function (angle) {
  7759. // rotate geometry around world x-axis
  7760. _m1$2.makeRotationX(angle);
  7761. this.applyMatrix(_m1$2);
  7762. return this;
  7763. },
  7764. rotateY: function (angle) {
  7765. // rotate geometry around world y-axis
  7766. _m1$2.makeRotationY(angle);
  7767. this.applyMatrix(_m1$2);
  7768. return this;
  7769. },
  7770. rotateZ: function (angle) {
  7771. // rotate geometry around world z-axis
  7772. _m1$2.makeRotationZ(angle);
  7773. this.applyMatrix(_m1$2);
  7774. return this;
  7775. },
  7776. translate: function (x, y, z) {
  7777. // translate geometry
  7778. _m1$2.makeTranslation(x, y, z);
  7779. this.applyMatrix(_m1$2);
  7780. return this;
  7781. },
  7782. scale: function (x, y, z) {
  7783. // scale geometry
  7784. _m1$2.makeScale(x, y, z);
  7785. this.applyMatrix(_m1$2);
  7786. return this;
  7787. },
  7788. lookAt: function (vector) {
  7789. _obj.lookAt(vector);
  7790. _obj.updateMatrix();
  7791. this.applyMatrix(_obj.matrix);
  7792. return this;
  7793. },
  7794. center: function () {
  7795. this.computeBoundingBox();
  7796. this.boundingBox.getCenter(_offset).negate();
  7797. this.translate(_offset.x, _offset.y, _offset.z);
  7798. return this;
  7799. },
  7800. setFromObject: function (object) {
  7801. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  7802. var geometry = object.geometry;
  7803. if (object.isPoints || object.isLine) {
  7804. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  7805. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  7806. this.addAttribute('position', positions.copyVector3sArray(geometry.vertices));
  7807. this.addAttribute('color', colors.copyColorsArray(geometry.colors));
  7808. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  7809. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  7810. this.addAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  7811. }
  7812. if (geometry.boundingSphere !== null) {
  7813. this.boundingSphere = geometry.boundingSphere.clone();
  7814. }
  7815. if (geometry.boundingBox !== null) {
  7816. this.boundingBox = geometry.boundingBox.clone();
  7817. }
  7818. } else if (object.isMesh) {
  7819. if (geometry && geometry.isGeometry) {
  7820. this.fromGeometry(geometry);
  7821. }
  7822. }
  7823. return this;
  7824. },
  7825. setFromPoints: function (points) {
  7826. var position = [];
  7827. for (var i = 0, l = points.length; i < l; i++) {
  7828. var point = points[i];
  7829. position.push(point.x, point.y, point.z || 0);
  7830. }
  7831. this.addAttribute('position', new Float32BufferAttribute(position, 3));
  7832. return this;
  7833. },
  7834. updateFromObject: function (object) {
  7835. var geometry = object.geometry;
  7836. if (object.isMesh) {
  7837. var direct = geometry.__directGeometry;
  7838. if (geometry.elementsNeedUpdate === true) {
  7839. direct = undefined;
  7840. geometry.elementsNeedUpdate = false;
  7841. }
  7842. if (direct === undefined) {
  7843. return this.fromGeometry(geometry);
  7844. }
  7845. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7846. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7847. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7848. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7849. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7850. geometry.verticesNeedUpdate = false;
  7851. geometry.normalsNeedUpdate = false;
  7852. geometry.colorsNeedUpdate = false;
  7853. geometry.uvsNeedUpdate = false;
  7854. geometry.groupsNeedUpdate = false;
  7855. geometry = direct;
  7856. }
  7857. var attribute;
  7858. if (geometry.verticesNeedUpdate === true) {
  7859. attribute = this.attributes.position;
  7860. if (attribute !== undefined) {
  7861. attribute.copyVector3sArray(geometry.vertices);
  7862. attribute.needsUpdate = true;
  7863. }
  7864. geometry.verticesNeedUpdate = false;
  7865. }
  7866. if (geometry.normalsNeedUpdate === true) {
  7867. attribute = this.attributes.normal;
  7868. if (attribute !== undefined) {
  7869. attribute.copyVector3sArray(geometry.normals);
  7870. attribute.needsUpdate = true;
  7871. }
  7872. geometry.normalsNeedUpdate = false;
  7873. }
  7874. if (geometry.colorsNeedUpdate === true) {
  7875. attribute = this.attributes.color;
  7876. if (attribute !== undefined) {
  7877. attribute.copyColorsArray(geometry.colors);
  7878. attribute.needsUpdate = true;
  7879. }
  7880. geometry.colorsNeedUpdate = false;
  7881. }
  7882. if (geometry.uvsNeedUpdate) {
  7883. attribute = this.attributes.uv;
  7884. if (attribute !== undefined) {
  7885. attribute.copyVector2sArray(geometry.uvs);
  7886. attribute.needsUpdate = true;
  7887. }
  7888. geometry.uvsNeedUpdate = false;
  7889. }
  7890. if (geometry.lineDistancesNeedUpdate) {
  7891. attribute = this.attributes.lineDistance;
  7892. if (attribute !== undefined) {
  7893. attribute.copyArray(geometry.lineDistances);
  7894. attribute.needsUpdate = true;
  7895. }
  7896. geometry.lineDistancesNeedUpdate = false;
  7897. }
  7898. if (geometry.groupsNeedUpdate) {
  7899. geometry.computeGroups(object.geometry);
  7900. this.groups = geometry.groups;
  7901. geometry.groupsNeedUpdate = false;
  7902. }
  7903. return this;
  7904. },
  7905. fromGeometry: function (geometry) {
  7906. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  7907. return this.fromDirectGeometry(geometry.__directGeometry);
  7908. },
  7909. fromDirectGeometry: function (geometry) {
  7910. var positions = new Float32Array(geometry.vertices.length * 3);
  7911. this.addAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  7912. if (geometry.normals.length > 0) {
  7913. var normals = new Float32Array(geometry.normals.length * 3);
  7914. this.addAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  7915. }
  7916. if (geometry.colors.length > 0) {
  7917. var colors = new Float32Array(geometry.colors.length * 3);
  7918. this.addAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  7919. }
  7920. if (geometry.uvs.length > 0) {
  7921. var uvs = new Float32Array(geometry.uvs.length * 2);
  7922. this.addAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  7923. }
  7924. if (geometry.uvs2.length > 0) {
  7925. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  7926. this.addAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7927. } // groups
  7928. this.groups = geometry.groups; // morphs
  7929. for (var name in geometry.morphTargets) {
  7930. var array = [];
  7931. var morphTargets = geometry.morphTargets[name];
  7932. for (var i = 0, l = morphTargets.length; i < l; i++) {
  7933. var morphTarget = morphTargets[i];
  7934. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7935. attribute.name = morphTarget.name;
  7936. array.push(attribute.copyVector3sArray(morphTarget.data));
  7937. }
  7938. this.morphAttributes[name] = array;
  7939. } // skinning
  7940. if (geometry.skinIndices.length > 0) {
  7941. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7942. this.addAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7943. }
  7944. if (geometry.skinWeights.length > 0) {
  7945. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7946. this.addAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7947. } //
  7948. if (geometry.boundingSphere !== null) {
  7949. this.boundingSphere = geometry.boundingSphere.clone();
  7950. }
  7951. if (geometry.boundingBox !== null) {
  7952. this.boundingBox = geometry.boundingBox.clone();
  7953. }
  7954. return this;
  7955. },
  7956. computeBoundingBox: function () {
  7957. if (this.boundingBox === null) {
  7958. this.boundingBox = new Box3();
  7959. }
  7960. var position = this.attributes.position;
  7961. var morphAttributesPosition = this.morphAttributes.position;
  7962. if (position !== undefined) {
  7963. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7964. if (morphAttributesPosition) {
  7965. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7966. var morphAttribute = morphAttributesPosition[i];
  7967. _box$1.setFromBufferAttribute(morphAttribute);
  7968. this.boundingBox.expandByPoint(_box$1.min);
  7969. this.boundingBox.expandByPoint(_box$1.max);
  7970. }
  7971. }
  7972. } else {
  7973. this.boundingBox.makeEmpty();
  7974. }
  7975. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7976. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7977. }
  7978. },
  7979. computeBoundingSphere: function () {
  7980. if (this.boundingSphere === null) {
  7981. this.boundingSphere = new Sphere();
  7982. }
  7983. var position = this.attributes.position;
  7984. var morphAttributesPosition = this.morphAttributes.position;
  7985. if (position) {
  7986. // first, find the center of the bounding sphere
  7987. var center = this.boundingSphere.center;
  7988. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  7989. if (morphAttributesPosition) {
  7990. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7991. var morphAttribute = morphAttributesPosition[i];
  7992. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7993. _box$1.expandByPoint(_boxMorphTargets.min);
  7994. _box$1.expandByPoint(_boxMorphTargets.max);
  7995. }
  7996. }
  7997. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7998. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7999. var maxRadiusSq = 0;
  8000. for (var i = 0, il = position.count; i < il; i++) {
  8001. _vector$4.fromBufferAttribute(position, i);
  8002. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  8003. } // process morph attributes if present
  8004. if (morphAttributesPosition) {
  8005. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  8006. var morphAttribute = morphAttributesPosition[i];
  8007. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  8008. _vector$4.fromBufferAttribute(morphAttribute, j);
  8009. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  8010. }
  8011. }
  8012. }
  8013. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  8014. if (isNaN(this.boundingSphere.radius)) {
  8015. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  8016. }
  8017. }
  8018. },
  8019. computeFaceNormals: function () {// backwards compatibility
  8020. },
  8021. computeVertexNormals: function () {
  8022. var index = this.index;
  8023. var attributes = this.attributes;
  8024. if (attributes.position) {
  8025. var positions = attributes.position.array;
  8026. if (attributes.normal === undefined) {
  8027. this.addAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  8028. } else {
  8029. // reset existing normals to zero
  8030. var array = attributes.normal.array;
  8031. for (var i = 0, il = array.length; i < il; i++) {
  8032. array[i] = 0;
  8033. }
  8034. }
  8035. var normals = attributes.normal.array;
  8036. var vA, vB, vC;
  8037. var pA = new Vector3(),
  8038. pB = new Vector3(),
  8039. pC = new Vector3();
  8040. var cb = new Vector3(),
  8041. ab = new Vector3(); // indexed elements
  8042. if (index) {
  8043. var indices = index.array;
  8044. for (var i = 0, il = index.count; i < il; i += 3) {
  8045. vA = indices[i + 0] * 3;
  8046. vB = indices[i + 1] * 3;
  8047. vC = indices[i + 2] * 3;
  8048. pA.fromArray(positions, vA);
  8049. pB.fromArray(positions, vB);
  8050. pC.fromArray(positions, vC);
  8051. cb.subVectors(pC, pB);
  8052. ab.subVectors(pA, pB);
  8053. cb.cross(ab);
  8054. normals[vA] += cb.x;
  8055. normals[vA + 1] += cb.y;
  8056. normals[vA + 2] += cb.z;
  8057. normals[vB] += cb.x;
  8058. normals[vB + 1] += cb.y;
  8059. normals[vB + 2] += cb.z;
  8060. normals[vC] += cb.x;
  8061. normals[vC + 1] += cb.y;
  8062. normals[vC + 2] += cb.z;
  8063. }
  8064. } else {
  8065. // non-indexed elements (unconnected triangle soup)
  8066. for (var i = 0, il = positions.length; i < il; i += 9) {
  8067. pA.fromArray(positions, i);
  8068. pB.fromArray(positions, i + 3);
  8069. pC.fromArray(positions, i + 6);
  8070. cb.subVectors(pC, pB);
  8071. ab.subVectors(pA, pB);
  8072. cb.cross(ab);
  8073. normals[i] = cb.x;
  8074. normals[i + 1] = cb.y;
  8075. normals[i + 2] = cb.z;
  8076. normals[i + 3] = cb.x;
  8077. normals[i + 4] = cb.y;
  8078. normals[i + 5] = cb.z;
  8079. normals[i + 6] = cb.x;
  8080. normals[i + 7] = cb.y;
  8081. normals[i + 8] = cb.z;
  8082. }
  8083. }
  8084. this.normalizeNormals();
  8085. attributes.normal.needsUpdate = true;
  8086. }
  8087. },
  8088. merge: function (geometry, offset) {
  8089. if (!(geometry && geometry.isBufferGeometry)) {
  8090. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  8091. return;
  8092. }
  8093. if (offset === undefined) {
  8094. offset = 0;
  8095. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  8096. }
  8097. var attributes = this.attributes;
  8098. for (var key in attributes) {
  8099. if (geometry.attributes[key] === undefined) continue;
  8100. var attribute1 = attributes[key];
  8101. var attributeArray1 = attribute1.array;
  8102. var attribute2 = geometry.attributes[key];
  8103. var attributeArray2 = attribute2.array;
  8104. var attributeOffset = attribute2.itemSize * offset;
  8105. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  8106. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  8107. attributeArray1[j] = attributeArray2[i];
  8108. }
  8109. }
  8110. return this;
  8111. },
  8112. normalizeNormals: function () {
  8113. var normals = this.attributes.normal;
  8114. for (var i = 0, il = normals.count; i < il; i++) {
  8115. _vector$4.x = normals.getX(i);
  8116. _vector$4.y = normals.getY(i);
  8117. _vector$4.z = normals.getZ(i);
  8118. _vector$4.normalize();
  8119. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  8120. }
  8121. },
  8122. toNonIndexed: function () {
  8123. function convertBufferAttribute(attribute, indices) {
  8124. var array = attribute.array;
  8125. var itemSize = attribute.itemSize;
  8126. var array2 = new array.constructor(indices.length * itemSize);
  8127. var index = 0,
  8128. index2 = 0;
  8129. for (var i = 0, l = indices.length; i < l; i++) {
  8130. index = indices[i] * itemSize;
  8131. for (var j = 0; j < itemSize; j++) {
  8132. array2[index2++] = array[index++];
  8133. }
  8134. }
  8135. return new BufferAttribute(array2, itemSize);
  8136. } //
  8137. if (this.index === null) {
  8138. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  8139. return this;
  8140. }
  8141. var geometry2 = new BufferGeometry();
  8142. var indices = this.index.array;
  8143. var attributes = this.attributes; // attributes
  8144. for (var name in attributes) {
  8145. var attribute = attributes[name];
  8146. var newAttribute = convertBufferAttribute(attribute, indices);
  8147. geometry2.addAttribute(name, newAttribute);
  8148. } // morph attributes
  8149. var morphAttributes = this.morphAttributes;
  8150. for (name in morphAttributes) {
  8151. var morphArray = [];
  8152. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8153. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  8154. var attribute = morphAttribute[i];
  8155. var newAttribute = convertBufferAttribute(attribute, indices);
  8156. morphArray.push(newAttribute);
  8157. }
  8158. geometry2.morphAttributes[name] = morphArray;
  8159. } // groups
  8160. var groups = this.groups;
  8161. for (var i = 0, l = groups.length; i < l; i++) {
  8162. var group = groups[i];
  8163. geometry2.addGroup(group.start, group.count, group.materialIndex);
  8164. }
  8165. return geometry2;
  8166. },
  8167. toJSON: function () {
  8168. var data = {
  8169. metadata: {
  8170. version: 4.5,
  8171. type: 'BufferGeometry',
  8172. generator: 'BufferGeometry.toJSON'
  8173. }
  8174. }; // standard BufferGeometry serialization
  8175. data.uuid = this.uuid;
  8176. data.type = this.type;
  8177. if (this.name !== '') data.name = this.name;
  8178. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  8179. if (this.parameters !== undefined) {
  8180. var parameters = this.parameters;
  8181. for (var key in parameters) {
  8182. if (parameters[key] !== undefined) data[key] = parameters[key];
  8183. }
  8184. return data;
  8185. }
  8186. data.data = {
  8187. attributes: {}
  8188. };
  8189. var index = this.index;
  8190. if (index !== null) {
  8191. data.data.index = {
  8192. type: index.array.constructor.name,
  8193. array: Array.prototype.slice.call(index.array)
  8194. };
  8195. }
  8196. var attributes = this.attributes;
  8197. for (var key in attributes) {
  8198. var attribute = attributes[key];
  8199. var attributeData = attribute.toJSON();
  8200. if (attribute.name !== '') attributeData.name = attribute.name;
  8201. data.data.attributes[key] = attributeData;
  8202. }
  8203. var morphAttributes = {};
  8204. var hasMorphAttributes = false;
  8205. for (var key in this.morphAttributes) {
  8206. var attributeArray = this.morphAttributes[key];
  8207. var array = [];
  8208. for (var i = 0, il = attributeArray.length; i < il; i++) {
  8209. var attribute = attributeArray[i];
  8210. var attributeData = attribute.toJSON();
  8211. if (attribute.name !== '') attributeData.name = attribute.name;
  8212. array.push(attributeData);
  8213. }
  8214. if (array.length > 0) {
  8215. morphAttributes[key] = array;
  8216. hasMorphAttributes = true;
  8217. }
  8218. }
  8219. if (hasMorphAttributes) data.data.morphAttributes = morphAttributes;
  8220. var groups = this.groups;
  8221. if (groups.length > 0) {
  8222. data.data.groups = JSON.parse(JSON.stringify(groups));
  8223. }
  8224. var boundingSphere = this.boundingSphere;
  8225. if (boundingSphere !== null) {
  8226. data.data.boundingSphere = {
  8227. center: boundingSphere.center.toArray(),
  8228. radius: boundingSphere.radius
  8229. };
  8230. }
  8231. return data;
  8232. },
  8233. clone: function () {
  8234. /*
  8235. // Handle primitives
  8236. var parameters = this.parameters;
  8237. if ( parameters !== undefined ) {
  8238. var values = [];
  8239. for ( var key in parameters ) {
  8240. values.push( parameters[ key ] );
  8241. }
  8242. var geometry = Object.create( this.constructor.prototype );
  8243. this.constructor.apply( geometry, values );
  8244. return geometry;
  8245. }
  8246. return new this.constructor().copy( this );
  8247. */
  8248. return new BufferGeometry().copy(this);
  8249. },
  8250. copy: function (source) {
  8251. var name, i, l; // reset
  8252. this.index = null;
  8253. this.attributes = {};
  8254. this.morphAttributes = {};
  8255. this.groups = [];
  8256. this.boundingBox = null;
  8257. this.boundingSphere = null; // name
  8258. this.name = source.name; // index
  8259. var index = source.index;
  8260. if (index !== null) {
  8261. this.setIndex(index.clone());
  8262. } // attributes
  8263. var attributes = source.attributes;
  8264. for (name in attributes) {
  8265. var attribute = attributes[name];
  8266. this.addAttribute(name, attribute.clone());
  8267. } // morph attributes
  8268. var morphAttributes = source.morphAttributes;
  8269. for (name in morphAttributes) {
  8270. var array = [];
  8271. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8272. for (i = 0, l = morphAttribute.length; i < l; i++) {
  8273. array.push(morphAttribute[i].clone());
  8274. }
  8275. this.morphAttributes[name] = array;
  8276. } // groups
  8277. var groups = source.groups;
  8278. for (i = 0, l = groups.length; i < l; i++) {
  8279. var group = groups[i];
  8280. this.addGroup(group.start, group.count, group.materialIndex);
  8281. } // bounding box
  8282. var boundingBox = source.boundingBox;
  8283. if (boundingBox !== null) {
  8284. this.boundingBox = boundingBox.clone();
  8285. } // bounding sphere
  8286. var boundingSphere = source.boundingSphere;
  8287. if (boundingSphere !== null) {
  8288. this.boundingSphere = boundingSphere.clone();
  8289. } // draw range
  8290. this.drawRange.start = source.drawRange.start;
  8291. this.drawRange.count = source.drawRange.count; // user data
  8292. this.userData = source.userData;
  8293. return this;
  8294. },
  8295. dispose: function () {
  8296. this.dispatchEvent({
  8297. type: 'dispose'
  8298. });
  8299. }
  8300. });
  8301. /**
  8302. * @author mrdoob / http://mrdoob.com/
  8303. * @author alteredq / http://alteredqualia.com/
  8304. * @author mikael emtinger / http://gomo.se/
  8305. * @author jonobr1 / http://jonobr1.com/
  8306. */
  8307. var _inverseMatrix = new Matrix4();
  8308. var _ray = new Ray();
  8309. var _sphere = new Sphere();
  8310. var _vA = new Vector3();
  8311. var _vB = new Vector3();
  8312. var _vC = new Vector3();
  8313. var _tempA = new Vector3();
  8314. var _tempB = new Vector3();
  8315. var _tempC = new Vector3();
  8316. var _morphA = new Vector3();
  8317. var _morphB = new Vector3();
  8318. var _morphC = new Vector3();
  8319. var _uvA = new Vector2();
  8320. var _uvB = new Vector2();
  8321. var _uvC = new Vector2();
  8322. var _intersectionPoint = new Vector3();
  8323. var _intersectionPointWorld = new Vector3();
  8324. function Mesh(geometry, material) {
  8325. Object3D.call(this);
  8326. this.type = 'Mesh';
  8327. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8328. this.material = material !== undefined ? material : new MeshBasicMaterial({
  8329. color: Math.random() * 0xffffff
  8330. });
  8331. this.drawMode = TrianglesDrawMode;
  8332. this.updateMorphTargets();
  8333. }
  8334. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  8335. constructor: Mesh,
  8336. isMesh: true,
  8337. setDrawMode: function (value) {
  8338. this.drawMode = value;
  8339. },
  8340. copy: function (source) {
  8341. Object3D.prototype.copy.call(this, source);
  8342. this.drawMode = source.drawMode;
  8343. if (source.morphTargetInfluences !== undefined) {
  8344. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  8345. }
  8346. if (source.morphTargetDictionary !== undefined) {
  8347. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  8348. }
  8349. return this;
  8350. },
  8351. updateMorphTargets: function () {
  8352. var geometry = this.geometry;
  8353. var m, ml, name;
  8354. if (geometry.isBufferGeometry) {
  8355. var morphAttributes = geometry.morphAttributes;
  8356. var keys = Object.keys(morphAttributes);
  8357. if (keys.length > 0) {
  8358. var morphAttribute = morphAttributes[keys[0]];
  8359. if (morphAttribute !== undefined) {
  8360. this.morphTargetInfluences = [];
  8361. this.morphTargetDictionary = {};
  8362. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  8363. name = morphAttribute[m].name || String(m);
  8364. this.morphTargetInfluences.push(0);
  8365. this.morphTargetDictionary[name] = m;
  8366. }
  8367. }
  8368. }
  8369. } else {
  8370. var morphTargets = geometry.morphTargets;
  8371. if (morphTargets !== undefined && morphTargets.length > 0) {
  8372. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  8373. }
  8374. }
  8375. },
  8376. raycast: function (raycaster, intersects) {
  8377. var geometry = this.geometry;
  8378. var material = this.material;
  8379. var matrixWorld = this.matrixWorld;
  8380. if (material === undefined) return; // Checking boundingSphere distance to ray
  8381. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8382. _sphere.copy(geometry.boundingSphere);
  8383. _sphere.applyMatrix4(matrixWorld);
  8384. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  8385. _inverseMatrix.getInverse(matrixWorld);
  8386. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  8387. if (geometry.boundingBox !== null) {
  8388. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  8389. }
  8390. var intersection;
  8391. if (geometry.isBufferGeometry) {
  8392. var a, b, c;
  8393. var index = geometry.index;
  8394. var position = geometry.attributes.position;
  8395. var morphPosition = geometry.morphAttributes.position;
  8396. var uv = geometry.attributes.uv;
  8397. var uv2 = geometry.attributes.uv2;
  8398. var groups = geometry.groups;
  8399. var drawRange = geometry.drawRange;
  8400. var i, j, il, jl;
  8401. var group, groupMaterial;
  8402. var start, end;
  8403. if (index !== null) {
  8404. // indexed buffer geometry
  8405. if (Array.isArray(material)) {
  8406. for (i = 0, il = groups.length; i < il; i++) {
  8407. group = groups[i];
  8408. groupMaterial = material[group.materialIndex];
  8409. start = Math.max(group.start, drawRange.start);
  8410. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8411. for (j = start, jl = end; j < jl; j += 3) {
  8412. a = index.getX(j);
  8413. b = index.getX(j + 1);
  8414. c = index.getX(j + 2);
  8415. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8416. if (intersection) {
  8417. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  8418. intersection.face.materialIndex = group.materialIndex;
  8419. intersects.push(intersection);
  8420. }
  8421. }
  8422. }
  8423. } else {
  8424. start = Math.max(0, drawRange.start);
  8425. end = Math.min(index.count, drawRange.start + drawRange.count);
  8426. for (i = start, il = end; i < il; i += 3) {
  8427. a = index.getX(i);
  8428. b = index.getX(i + 1);
  8429. c = index.getX(i + 2);
  8430. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8431. if (intersection) {
  8432. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  8433. intersects.push(intersection);
  8434. }
  8435. }
  8436. }
  8437. } else if (position !== undefined) {
  8438. // non-indexed buffer geometry
  8439. if (Array.isArray(material)) {
  8440. for (i = 0, il = groups.length; i < il; i++) {
  8441. group = groups[i];
  8442. groupMaterial = material[group.materialIndex];
  8443. start = Math.max(group.start, drawRange.start);
  8444. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8445. for (j = start, jl = end; j < jl; j += 3) {
  8446. a = j;
  8447. b = j + 1;
  8448. c = j + 2;
  8449. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8450. if (intersection) {
  8451. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  8452. intersection.face.materialIndex = group.materialIndex;
  8453. intersects.push(intersection);
  8454. }
  8455. }
  8456. }
  8457. } else {
  8458. start = Math.max(0, drawRange.start);
  8459. end = Math.min(position.count, drawRange.start + drawRange.count);
  8460. for (i = start, il = end; i < il; i += 3) {
  8461. a = i;
  8462. b = i + 1;
  8463. c = i + 2;
  8464. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8465. if (intersection) {
  8466. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  8467. intersects.push(intersection);
  8468. }
  8469. }
  8470. }
  8471. }
  8472. } else if (geometry.isGeometry) {
  8473. var fvA, fvB, fvC;
  8474. var isMultiMaterial = Array.isArray(material);
  8475. var vertices = geometry.vertices;
  8476. var faces = geometry.faces;
  8477. var uvs;
  8478. var faceVertexUvs = geometry.faceVertexUvs[0];
  8479. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  8480. for (var f = 0, fl = faces.length; f < fl; f++) {
  8481. var face = faces[f];
  8482. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  8483. if (faceMaterial === undefined) continue;
  8484. fvA = vertices[face.a];
  8485. fvB = vertices[face.b];
  8486. fvC = vertices[face.c];
  8487. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  8488. if (intersection) {
  8489. if (uvs && uvs[f]) {
  8490. var uvs_f = uvs[f];
  8491. _uvA.copy(uvs_f[0]);
  8492. _uvB.copy(uvs_f[1]);
  8493. _uvC.copy(uvs_f[2]);
  8494. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  8495. }
  8496. intersection.face = face;
  8497. intersection.faceIndex = f;
  8498. intersects.push(intersection);
  8499. }
  8500. }
  8501. }
  8502. },
  8503. clone: function () {
  8504. return new this.constructor(this.geometry, this.material).copy(this);
  8505. }
  8506. });
  8507. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  8508. var intersect;
  8509. if (material.side === BackSide) {
  8510. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  8511. } else {
  8512. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  8513. }
  8514. if (intersect === null) return null;
  8515. _intersectionPointWorld.copy(point);
  8516. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  8517. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  8518. if (distance < raycaster.near || distance > raycaster.far) return null;
  8519. return {
  8520. distance: distance,
  8521. point: _intersectionPointWorld.clone(),
  8522. object: object
  8523. };
  8524. }
  8525. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, uv, uv2, a, b, c) {
  8526. _vA.fromBufferAttribute(position, a);
  8527. _vB.fromBufferAttribute(position, b);
  8528. _vC.fromBufferAttribute(position, c);
  8529. var morphInfluences = object.morphTargetInfluences;
  8530. if (material.morphTargets && morphPosition && morphInfluences) {
  8531. _morphA.set(0, 0, 0);
  8532. _morphB.set(0, 0, 0);
  8533. _morphC.set(0, 0, 0);
  8534. for (var i = 0, il = morphPosition.length; i < il; i++) {
  8535. var influence = morphInfluences[i];
  8536. var morphAttribute = morphPosition[i];
  8537. if (influence === 0) continue;
  8538. _tempA.fromBufferAttribute(morphAttribute, a);
  8539. _tempB.fromBufferAttribute(morphAttribute, b);
  8540. _tempC.fromBufferAttribute(morphAttribute, c);
  8541. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  8542. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  8543. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  8544. }
  8545. _vA.add(_morphA);
  8546. _vB.add(_morphB);
  8547. _vC.add(_morphC);
  8548. }
  8549. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  8550. if (intersection) {
  8551. if (uv) {
  8552. _uvA.fromBufferAttribute(uv, a);
  8553. _uvB.fromBufferAttribute(uv, b);
  8554. _uvC.fromBufferAttribute(uv, c);
  8555. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8556. }
  8557. if (uv2) {
  8558. _uvA.fromBufferAttribute(uv2, a);
  8559. _uvB.fromBufferAttribute(uv2, b);
  8560. _uvC.fromBufferAttribute(uv2, c);
  8561. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8562. }
  8563. var face = new Face3(a, b, c);
  8564. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  8565. intersection.face = face;
  8566. }
  8567. return intersection;
  8568. }
  8569. /**
  8570. * @author mrdoob / http://mrdoob.com/
  8571. * @author kile / http://kile.stravaganza.org/
  8572. * @author alteredq / http://alteredqualia.com/
  8573. * @author mikael emtinger / http://gomo.se/
  8574. * @author zz85 / http://www.lab4games.net/zz85/blog
  8575. * @author bhouston / http://clara.io
  8576. */
  8577. var _geometryId = 0; // Geometry uses even numbers as Id
  8578. var _m1$3 = new Matrix4();
  8579. var _obj$1 = new Object3D();
  8580. var _offset$1 = new Vector3();
  8581. function Geometry() {
  8582. Object.defineProperty(this, 'id', {
  8583. value: _geometryId += 2
  8584. });
  8585. this.uuid = _Math.generateUUID();
  8586. this.name = '';
  8587. this.type = 'Geometry';
  8588. this.vertices = [];
  8589. this.colors = [];
  8590. this.faces = [];
  8591. this.faceVertexUvs = [[]];
  8592. this.morphTargets = [];
  8593. this.morphNormals = [];
  8594. this.skinWeights = [];
  8595. this.skinIndices = [];
  8596. this.lineDistances = [];
  8597. this.boundingBox = null;
  8598. this.boundingSphere = null; // update flags
  8599. this.elementsNeedUpdate = false;
  8600. this.verticesNeedUpdate = false;
  8601. this.uvsNeedUpdate = false;
  8602. this.normalsNeedUpdate = false;
  8603. this.colorsNeedUpdate = false;
  8604. this.lineDistancesNeedUpdate = false;
  8605. this.groupsNeedUpdate = false;
  8606. }
  8607. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  8608. constructor: Geometry,
  8609. isGeometry: true,
  8610. applyMatrix: function (matrix) {
  8611. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8612. for (var i = 0, il = this.vertices.length; i < il; i++) {
  8613. var vertex = this.vertices[i];
  8614. vertex.applyMatrix4(matrix);
  8615. }
  8616. for (var i = 0, il = this.faces.length; i < il; i++) {
  8617. var face = this.faces[i];
  8618. face.normal.applyMatrix3(normalMatrix).normalize();
  8619. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  8620. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  8621. }
  8622. }
  8623. if (this.boundingBox !== null) {
  8624. this.computeBoundingBox();
  8625. }
  8626. if (this.boundingSphere !== null) {
  8627. this.computeBoundingSphere();
  8628. }
  8629. this.verticesNeedUpdate = true;
  8630. this.normalsNeedUpdate = true;
  8631. return this;
  8632. },
  8633. rotateX: function (angle) {
  8634. // rotate geometry around world x-axis
  8635. _m1$3.makeRotationX(angle);
  8636. this.applyMatrix(_m1$3);
  8637. return this;
  8638. },
  8639. rotateY: function (angle) {
  8640. // rotate geometry around world y-axis
  8641. _m1$3.makeRotationY(angle);
  8642. this.applyMatrix(_m1$3);
  8643. return this;
  8644. },
  8645. rotateZ: function (angle) {
  8646. // rotate geometry around world z-axis
  8647. _m1$3.makeRotationZ(angle);
  8648. this.applyMatrix(_m1$3);
  8649. return this;
  8650. },
  8651. translate: function (x, y, z) {
  8652. // translate geometry
  8653. _m1$3.makeTranslation(x, y, z);
  8654. this.applyMatrix(_m1$3);
  8655. return this;
  8656. },
  8657. scale: function (x, y, z) {
  8658. // scale geometry
  8659. _m1$3.makeScale(x, y, z);
  8660. this.applyMatrix(_m1$3);
  8661. return this;
  8662. },
  8663. lookAt: function (vector) {
  8664. _obj$1.lookAt(vector);
  8665. _obj$1.updateMatrix();
  8666. this.applyMatrix(_obj$1.matrix);
  8667. return this;
  8668. },
  8669. fromBufferGeometry: function (geometry) {
  8670. var scope = this;
  8671. var indices = geometry.index !== null ? geometry.index.array : undefined;
  8672. var attributes = geometry.attributes;
  8673. if (attributes.position === undefined) {
  8674. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  8675. return this;
  8676. }
  8677. var positions = attributes.position.array;
  8678. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  8679. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  8680. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  8681. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  8682. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  8683. for (var i = 0; i < positions.length; i += 3) {
  8684. scope.vertices.push(new Vector3().fromArray(positions, i));
  8685. if (colors !== undefined) {
  8686. scope.colors.push(new Color().fromArray(colors, i));
  8687. }
  8688. }
  8689. function addFace(a, b, c, materialIndex) {
  8690. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  8691. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  8692. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  8693. scope.faces.push(face);
  8694. if (uvs !== undefined) {
  8695. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  8696. }
  8697. if (uvs2 !== undefined) {
  8698. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  8699. }
  8700. }
  8701. var groups = geometry.groups;
  8702. if (groups.length > 0) {
  8703. for (var i = 0; i < groups.length; i++) {
  8704. var group = groups[i];
  8705. var start = group.start;
  8706. var count = group.count;
  8707. for (var j = start, jl = start + count; j < jl; j += 3) {
  8708. if (indices !== undefined) {
  8709. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  8710. } else {
  8711. addFace(j, j + 1, j + 2, group.materialIndex);
  8712. }
  8713. }
  8714. }
  8715. } else {
  8716. if (indices !== undefined) {
  8717. for (var i = 0; i < indices.length; i += 3) {
  8718. addFace(indices[i], indices[i + 1], indices[i + 2]);
  8719. }
  8720. } else {
  8721. for (var i = 0; i < positions.length / 3; i += 3) {
  8722. addFace(i, i + 1, i + 2);
  8723. }
  8724. }
  8725. }
  8726. this.computeFaceNormals();
  8727. if (geometry.boundingBox !== null) {
  8728. this.boundingBox = geometry.boundingBox.clone();
  8729. }
  8730. if (geometry.boundingSphere !== null) {
  8731. this.boundingSphere = geometry.boundingSphere.clone();
  8732. }
  8733. return this;
  8734. },
  8735. center: function () {
  8736. this.computeBoundingBox();
  8737. this.boundingBox.getCenter(_offset$1).negate();
  8738. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  8739. return this;
  8740. },
  8741. normalize: function () {
  8742. this.computeBoundingSphere();
  8743. var center = this.boundingSphere.center;
  8744. var radius = this.boundingSphere.radius;
  8745. var s = radius === 0 ? 1 : 1.0 / radius;
  8746. var matrix = new Matrix4();
  8747. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  8748. this.applyMatrix(matrix);
  8749. return this;
  8750. },
  8751. computeFaceNormals: function () {
  8752. var cb = new Vector3(),
  8753. ab = new Vector3();
  8754. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  8755. var face = this.faces[f];
  8756. var vA = this.vertices[face.a];
  8757. var vB = this.vertices[face.b];
  8758. var vC = this.vertices[face.c];
  8759. cb.subVectors(vC, vB);
  8760. ab.subVectors(vA, vB);
  8761. cb.cross(ab);
  8762. cb.normalize();
  8763. face.normal.copy(cb);
  8764. }
  8765. },
  8766. computeVertexNormals: function (areaWeighted) {
  8767. if (areaWeighted === undefined) areaWeighted = true;
  8768. var v, vl, f, fl, face, vertices;
  8769. vertices = new Array(this.vertices.length);
  8770. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8771. vertices[v] = new Vector3();
  8772. }
  8773. if (areaWeighted) {
  8774. // vertex normals weighted by triangle areas
  8775. // http://www.iquilezles.org/www/articles/normals/normals.htm
  8776. var vA, vB, vC;
  8777. var cb = new Vector3(),
  8778. ab = new Vector3();
  8779. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8780. face = this.faces[f];
  8781. vA = this.vertices[face.a];
  8782. vB = this.vertices[face.b];
  8783. vC = this.vertices[face.c];
  8784. cb.subVectors(vC, vB);
  8785. ab.subVectors(vA, vB);
  8786. cb.cross(ab);
  8787. vertices[face.a].add(cb);
  8788. vertices[face.b].add(cb);
  8789. vertices[face.c].add(cb);
  8790. }
  8791. } else {
  8792. this.computeFaceNormals();
  8793. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8794. face = this.faces[f];
  8795. vertices[face.a].add(face.normal);
  8796. vertices[face.b].add(face.normal);
  8797. vertices[face.c].add(face.normal);
  8798. }
  8799. }
  8800. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8801. vertices[v].normalize();
  8802. }
  8803. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8804. face = this.faces[f];
  8805. var vertexNormals = face.vertexNormals;
  8806. if (vertexNormals.length === 3) {
  8807. vertexNormals[0].copy(vertices[face.a]);
  8808. vertexNormals[1].copy(vertices[face.b]);
  8809. vertexNormals[2].copy(vertices[face.c]);
  8810. } else {
  8811. vertexNormals[0] = vertices[face.a].clone();
  8812. vertexNormals[1] = vertices[face.b].clone();
  8813. vertexNormals[2] = vertices[face.c].clone();
  8814. }
  8815. }
  8816. if (this.faces.length > 0) {
  8817. this.normalsNeedUpdate = true;
  8818. }
  8819. },
  8820. computeFlatVertexNormals: function () {
  8821. var f, fl, face;
  8822. this.computeFaceNormals();
  8823. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8824. face = this.faces[f];
  8825. var vertexNormals = face.vertexNormals;
  8826. if (vertexNormals.length === 3) {
  8827. vertexNormals[0].copy(face.normal);
  8828. vertexNormals[1].copy(face.normal);
  8829. vertexNormals[2].copy(face.normal);
  8830. } else {
  8831. vertexNormals[0] = face.normal.clone();
  8832. vertexNormals[1] = face.normal.clone();
  8833. vertexNormals[2] = face.normal.clone();
  8834. }
  8835. }
  8836. if (this.faces.length > 0) {
  8837. this.normalsNeedUpdate = true;
  8838. }
  8839. },
  8840. computeMorphNormals: function () {
  8841. var i, il, f, fl, face; // save original normals
  8842. // - create temp variables on first access
  8843. // otherwise just copy (for faster repeated calls)
  8844. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8845. face = this.faces[f];
  8846. if (!face.__originalFaceNormal) {
  8847. face.__originalFaceNormal = face.normal.clone();
  8848. } else {
  8849. face.__originalFaceNormal.copy(face.normal);
  8850. }
  8851. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  8852. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  8853. if (!face.__originalVertexNormals[i]) {
  8854. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  8855. } else {
  8856. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  8857. }
  8858. }
  8859. } // use temp geometry to compute face and vertex normals for each morph
  8860. var tmpGeo = new Geometry();
  8861. tmpGeo.faces = this.faces;
  8862. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  8863. // create on first access
  8864. if (!this.morphNormals[i]) {
  8865. this.morphNormals[i] = {};
  8866. this.morphNormals[i].faceNormals = [];
  8867. this.morphNormals[i].vertexNormals = [];
  8868. var dstNormalsFace = this.morphNormals[i].faceNormals;
  8869. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  8870. var faceNormal, vertexNormals;
  8871. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8872. faceNormal = new Vector3();
  8873. vertexNormals = {
  8874. a: new Vector3(),
  8875. b: new Vector3(),
  8876. c: new Vector3()
  8877. };
  8878. dstNormalsFace.push(faceNormal);
  8879. dstNormalsVertex.push(vertexNormals);
  8880. }
  8881. }
  8882. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  8883. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  8884. tmpGeo.computeFaceNormals();
  8885. tmpGeo.computeVertexNormals(); // store morph normals
  8886. var faceNormal, vertexNormals;
  8887. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8888. face = this.faces[f];
  8889. faceNormal = morphNormals.faceNormals[f];
  8890. vertexNormals = morphNormals.vertexNormals[f];
  8891. faceNormal.copy(face.normal);
  8892. vertexNormals.a.copy(face.vertexNormals[0]);
  8893. vertexNormals.b.copy(face.vertexNormals[1]);
  8894. vertexNormals.c.copy(face.vertexNormals[2]);
  8895. }
  8896. } // restore original normals
  8897. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8898. face = this.faces[f];
  8899. face.normal = face.__originalFaceNormal;
  8900. face.vertexNormals = face.__originalVertexNormals;
  8901. }
  8902. },
  8903. computeBoundingBox: function () {
  8904. if (this.boundingBox === null) {
  8905. this.boundingBox = new Box3();
  8906. }
  8907. this.boundingBox.setFromPoints(this.vertices);
  8908. },
  8909. computeBoundingSphere: function () {
  8910. if (this.boundingSphere === null) {
  8911. this.boundingSphere = new Sphere();
  8912. }
  8913. this.boundingSphere.setFromPoints(this.vertices);
  8914. },
  8915. merge: function (geometry, matrix, materialIndexOffset) {
  8916. if (!(geometry && geometry.isGeometry)) {
  8917. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  8918. return;
  8919. }
  8920. var normalMatrix,
  8921. vertexOffset = this.vertices.length,
  8922. vertices1 = this.vertices,
  8923. vertices2 = geometry.vertices,
  8924. faces1 = this.faces,
  8925. faces2 = geometry.faces,
  8926. colors1 = this.colors,
  8927. colors2 = geometry.colors;
  8928. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  8929. if (matrix !== undefined) {
  8930. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8931. } // vertices
  8932. for (var i = 0, il = vertices2.length; i < il; i++) {
  8933. var vertex = vertices2[i];
  8934. var vertexCopy = vertex.clone();
  8935. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  8936. vertices1.push(vertexCopy);
  8937. } // colors
  8938. for (var i = 0, il = colors2.length; i < il; i++) {
  8939. colors1.push(colors2[i].clone());
  8940. } // faces
  8941. for (i = 0, il = faces2.length; i < il; i++) {
  8942. var face = faces2[i],
  8943. faceCopy,
  8944. normal,
  8945. color,
  8946. faceVertexNormals = face.vertexNormals,
  8947. faceVertexColors = face.vertexColors;
  8948. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  8949. faceCopy.normal.copy(face.normal);
  8950. if (normalMatrix !== undefined) {
  8951. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  8952. }
  8953. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  8954. normal = faceVertexNormals[j].clone();
  8955. if (normalMatrix !== undefined) {
  8956. normal.applyMatrix3(normalMatrix).normalize();
  8957. }
  8958. faceCopy.vertexNormals.push(normal);
  8959. }
  8960. faceCopy.color.copy(face.color);
  8961. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  8962. color = faceVertexColors[j];
  8963. faceCopy.vertexColors.push(color.clone());
  8964. }
  8965. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8966. faces1.push(faceCopy);
  8967. } // uvs
  8968. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  8969. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  8970. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  8971. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  8972. var uvs2 = faceVertexUvs2[j],
  8973. uvsCopy = [];
  8974. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  8975. uvsCopy.push(uvs2[k].clone());
  8976. }
  8977. this.faceVertexUvs[i].push(uvsCopy);
  8978. }
  8979. }
  8980. },
  8981. mergeMesh: function (mesh) {
  8982. if (!(mesh && mesh.isMesh)) {
  8983. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  8984. return;
  8985. }
  8986. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  8987. this.merge(mesh.geometry, mesh.matrix);
  8988. },
  8989. /*
  8990. * Checks for duplicate vertices with hashmap.
  8991. * Duplicated vertices are removed
  8992. * and faces' vertices are updated.
  8993. */
  8994. mergeVertices: function () {
  8995. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8996. var unique = [],
  8997. changes = [];
  8998. var v, key;
  8999. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  9000. var precision = Math.pow(10, precisionPoints);
  9001. var i, il, face;
  9002. var indices, j, jl;
  9003. for (i = 0, il = this.vertices.length; i < il; i++) {
  9004. v = this.vertices[i];
  9005. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  9006. if (verticesMap[key] === undefined) {
  9007. verticesMap[key] = i;
  9008. unique.push(this.vertices[i]);
  9009. changes[i] = unique.length - 1;
  9010. } else {
  9011. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  9012. changes[i] = changes[verticesMap[key]];
  9013. }
  9014. } // if faces are completely degenerate after merging vertices, we
  9015. // have to remove them from the geometry.
  9016. var faceIndicesToRemove = [];
  9017. for (i = 0, il = this.faces.length; i < il; i++) {
  9018. face = this.faces[i];
  9019. face.a = changes[face.a];
  9020. face.b = changes[face.b];
  9021. face.c = changes[face.c];
  9022. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  9023. // we have to remove the face as nothing can be saved
  9024. for (var n = 0; n < 3; n++) {
  9025. if (indices[n] === indices[(n + 1) % 3]) {
  9026. faceIndicesToRemove.push(i);
  9027. break;
  9028. }
  9029. }
  9030. }
  9031. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  9032. var idx = faceIndicesToRemove[i];
  9033. this.faces.splice(idx, 1);
  9034. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  9035. this.faceVertexUvs[j].splice(idx, 1);
  9036. }
  9037. } // Use unique set of vertices
  9038. var diff = this.vertices.length - unique.length;
  9039. this.vertices = unique;
  9040. return diff;
  9041. },
  9042. setFromPoints: function (points) {
  9043. this.vertices = [];
  9044. for (var i = 0, l = points.length; i < l; i++) {
  9045. var point = points[i];
  9046. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  9047. }
  9048. return this;
  9049. },
  9050. sortFacesByMaterialIndex: function () {
  9051. var faces = this.faces;
  9052. var length = faces.length; // tag faces
  9053. for (var i = 0; i < length; i++) {
  9054. faces[i]._id = i;
  9055. } // sort faces
  9056. function materialIndexSort(a, b) {
  9057. return a.materialIndex - b.materialIndex;
  9058. }
  9059. faces.sort(materialIndexSort); // sort uvs
  9060. var uvs1 = this.faceVertexUvs[0];
  9061. var uvs2 = this.faceVertexUvs[1];
  9062. var newUvs1, newUvs2;
  9063. if (uvs1 && uvs1.length === length) newUvs1 = [];
  9064. if (uvs2 && uvs2.length === length) newUvs2 = [];
  9065. for (var i = 0; i < length; i++) {
  9066. var id = faces[i]._id;
  9067. if (newUvs1) newUvs1.push(uvs1[id]);
  9068. if (newUvs2) newUvs2.push(uvs2[id]);
  9069. }
  9070. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  9071. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  9072. },
  9073. toJSON: function () {
  9074. var data = {
  9075. metadata: {
  9076. version: 4.5,
  9077. type: 'Geometry',
  9078. generator: 'Geometry.toJSON'
  9079. }
  9080. }; // standard Geometry serialization
  9081. data.uuid = this.uuid;
  9082. data.type = this.type;
  9083. if (this.name !== '') data.name = this.name;
  9084. if (this.parameters !== undefined) {
  9085. var parameters = this.parameters;
  9086. for (var key in parameters) {
  9087. if (parameters[key] !== undefined) data[key] = parameters[key];
  9088. }
  9089. return data;
  9090. }
  9091. var vertices = [];
  9092. for (var i = 0; i < this.vertices.length; i++) {
  9093. var vertex = this.vertices[i];
  9094. vertices.push(vertex.x, vertex.y, vertex.z);
  9095. }
  9096. var faces = [];
  9097. var normals = [];
  9098. var normalsHash = {};
  9099. var colors = [];
  9100. var colorsHash = {};
  9101. var uvs = [];
  9102. var uvsHash = {};
  9103. for (var i = 0; i < this.faces.length; i++) {
  9104. var face = this.faces[i];
  9105. var hasMaterial = true;
  9106. var hasFaceUv = false; // deprecated
  9107. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  9108. var hasFaceNormal = face.normal.length() > 0;
  9109. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  9110. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  9111. var hasFaceVertexColor = face.vertexColors.length > 0;
  9112. var faceType = 0;
  9113. faceType = setBit(faceType, 0, 0); // isQuad
  9114. faceType = setBit(faceType, 1, hasMaterial);
  9115. faceType = setBit(faceType, 2, hasFaceUv);
  9116. faceType = setBit(faceType, 3, hasFaceVertexUv);
  9117. faceType = setBit(faceType, 4, hasFaceNormal);
  9118. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  9119. faceType = setBit(faceType, 6, hasFaceColor);
  9120. faceType = setBit(faceType, 7, hasFaceVertexColor);
  9121. faces.push(faceType);
  9122. faces.push(face.a, face.b, face.c);
  9123. faces.push(face.materialIndex);
  9124. if (hasFaceVertexUv) {
  9125. var faceVertexUvs = this.faceVertexUvs[0][i];
  9126. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  9127. }
  9128. if (hasFaceNormal) {
  9129. faces.push(getNormalIndex(face.normal));
  9130. }
  9131. if (hasFaceVertexNormal) {
  9132. var vertexNormals = face.vertexNormals;
  9133. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  9134. }
  9135. if (hasFaceColor) {
  9136. faces.push(getColorIndex(face.color));
  9137. }
  9138. if (hasFaceVertexColor) {
  9139. var vertexColors = face.vertexColors;
  9140. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  9141. }
  9142. }
  9143. function setBit(value, position, enabled) {
  9144. return enabled ? value | 1 << position : value & ~(1 << position);
  9145. }
  9146. function getNormalIndex(normal) {
  9147. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  9148. if (normalsHash[hash] !== undefined) {
  9149. return normalsHash[hash];
  9150. }
  9151. normalsHash[hash] = normals.length / 3;
  9152. normals.push(normal.x, normal.y, normal.z);
  9153. return normalsHash[hash];
  9154. }
  9155. function getColorIndex(color) {
  9156. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  9157. if (colorsHash[hash] !== undefined) {
  9158. return colorsHash[hash];
  9159. }
  9160. colorsHash[hash] = colors.length;
  9161. colors.push(color.getHex());
  9162. return colorsHash[hash];
  9163. }
  9164. function getUvIndex(uv) {
  9165. var hash = uv.x.toString() + uv.y.toString();
  9166. if (uvsHash[hash] !== undefined) {
  9167. return uvsHash[hash];
  9168. }
  9169. uvsHash[hash] = uvs.length / 2;
  9170. uvs.push(uv.x, uv.y);
  9171. return uvsHash[hash];
  9172. }
  9173. data.data = {};
  9174. data.data.vertices = vertices;
  9175. data.data.normals = normals;
  9176. if (colors.length > 0) data.data.colors = colors;
  9177. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  9178. data.data.faces = faces;
  9179. return data;
  9180. },
  9181. clone: function () {
  9182. /*
  9183. // Handle primitives
  9184. var parameters = this.parameters;
  9185. if ( parameters !== undefined ) {
  9186. var values = [];
  9187. for ( var key in parameters ) {
  9188. values.push( parameters[ key ] );
  9189. }
  9190. var geometry = Object.create( this.constructor.prototype );
  9191. this.constructor.apply( geometry, values );
  9192. return geometry;
  9193. }
  9194. return new this.constructor().copy( this );
  9195. */
  9196. return new Geometry().copy(this);
  9197. },
  9198. copy: function (source) {
  9199. var i, il, j, jl, k, kl; // reset
  9200. this.vertices = [];
  9201. this.colors = [];
  9202. this.faces = [];
  9203. this.faceVertexUvs = [[]];
  9204. this.morphTargets = [];
  9205. this.morphNormals = [];
  9206. this.skinWeights = [];
  9207. this.skinIndices = [];
  9208. this.lineDistances = [];
  9209. this.boundingBox = null;
  9210. this.boundingSphere = null; // name
  9211. this.name = source.name; // vertices
  9212. var vertices = source.vertices;
  9213. for (i = 0, il = vertices.length; i < il; i++) {
  9214. this.vertices.push(vertices[i].clone());
  9215. } // colors
  9216. var colors = source.colors;
  9217. for (i = 0, il = colors.length; i < il; i++) {
  9218. this.colors.push(colors[i].clone());
  9219. } // faces
  9220. var faces = source.faces;
  9221. for (i = 0, il = faces.length; i < il; i++) {
  9222. this.faces.push(faces[i].clone());
  9223. } // face vertex uvs
  9224. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  9225. var faceVertexUvs = source.faceVertexUvs[i];
  9226. if (this.faceVertexUvs[i] === undefined) {
  9227. this.faceVertexUvs[i] = [];
  9228. }
  9229. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  9230. var uvs = faceVertexUvs[j],
  9231. uvsCopy = [];
  9232. for (k = 0, kl = uvs.length; k < kl; k++) {
  9233. var uv = uvs[k];
  9234. uvsCopy.push(uv.clone());
  9235. }
  9236. this.faceVertexUvs[i].push(uvsCopy);
  9237. }
  9238. } // morph targets
  9239. var morphTargets = source.morphTargets;
  9240. for (i = 0, il = morphTargets.length; i < il; i++) {
  9241. var morphTarget = {};
  9242. morphTarget.name = morphTargets[i].name; // vertices
  9243. if (morphTargets[i].vertices !== undefined) {
  9244. morphTarget.vertices = [];
  9245. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  9246. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  9247. }
  9248. } // normals
  9249. if (morphTargets[i].normals !== undefined) {
  9250. morphTarget.normals = [];
  9251. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  9252. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  9253. }
  9254. }
  9255. this.morphTargets.push(morphTarget);
  9256. } // morph normals
  9257. var morphNormals = source.morphNormals;
  9258. for (i = 0, il = morphNormals.length; i < il; i++) {
  9259. var morphNormal = {}; // vertex normals
  9260. if (morphNormals[i].vertexNormals !== undefined) {
  9261. morphNormal.vertexNormals = [];
  9262. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  9263. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  9264. var destVertexNormal = {};
  9265. destVertexNormal.a = srcVertexNormal.a.clone();
  9266. destVertexNormal.b = srcVertexNormal.b.clone();
  9267. destVertexNormal.c = srcVertexNormal.c.clone();
  9268. morphNormal.vertexNormals.push(destVertexNormal);
  9269. }
  9270. } // face normals
  9271. if (morphNormals[i].faceNormals !== undefined) {
  9272. morphNormal.faceNormals = [];
  9273. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  9274. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  9275. }
  9276. }
  9277. this.morphNormals.push(morphNormal);
  9278. } // skin weights
  9279. var skinWeights = source.skinWeights;
  9280. for (i = 0, il = skinWeights.length; i < il; i++) {
  9281. this.skinWeights.push(skinWeights[i].clone());
  9282. } // skin indices
  9283. var skinIndices = source.skinIndices;
  9284. for (i = 0, il = skinIndices.length; i < il; i++) {
  9285. this.skinIndices.push(skinIndices[i].clone());
  9286. } // line distances
  9287. var lineDistances = source.lineDistances;
  9288. for (i = 0, il = lineDistances.length; i < il; i++) {
  9289. this.lineDistances.push(lineDistances[i]);
  9290. } // bounding box
  9291. var boundingBox = source.boundingBox;
  9292. if (boundingBox !== null) {
  9293. this.boundingBox = boundingBox.clone();
  9294. } // bounding sphere
  9295. var boundingSphere = source.boundingSphere;
  9296. if (boundingSphere !== null) {
  9297. this.boundingSphere = boundingSphere.clone();
  9298. } // update flags
  9299. this.elementsNeedUpdate = source.elementsNeedUpdate;
  9300. this.verticesNeedUpdate = source.verticesNeedUpdate;
  9301. this.uvsNeedUpdate = source.uvsNeedUpdate;
  9302. this.normalsNeedUpdate = source.normalsNeedUpdate;
  9303. this.colorsNeedUpdate = source.colorsNeedUpdate;
  9304. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  9305. this.groupsNeedUpdate = source.groupsNeedUpdate;
  9306. return this;
  9307. },
  9308. dispose: function () {
  9309. this.dispatchEvent({
  9310. type: 'dispose'
  9311. });
  9312. }
  9313. });
  9314. /**
  9315. * @author mrdoob / http://mrdoob.com/
  9316. * @author Mugen87 / https://github.com/Mugen87
  9317. */
  9318. // BoxGeometry
  9319. class BoxGeometry extends Geometry {
  9320. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9321. super();
  9322. this.type = 'BoxGeometry';
  9323. this.parameters = {
  9324. width: width,
  9325. height: height,
  9326. depth: depth,
  9327. widthSegments: widthSegments,
  9328. heightSegments: heightSegments,
  9329. depthSegments: depthSegments
  9330. };
  9331. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  9332. this.mergeVertices();
  9333. }
  9334. } // BoxBufferGeometry
  9335. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  9336. class BoxBufferGeometry extends BufferGeometry {
  9337. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9338. super();
  9339. this.type = 'BoxBufferGeometry';
  9340. this.parameters = {
  9341. width: width,
  9342. height: height,
  9343. depth: depth,
  9344. widthSegments: widthSegments,
  9345. heightSegments: heightSegments,
  9346. depthSegments: depthSegments
  9347. };
  9348. var scope = this;
  9349. width = width || 1;
  9350. height = height || 1;
  9351. depth = depth || 1; // segments
  9352. widthSegments = Math.floor(widthSegments) || 1;
  9353. heightSegments = Math.floor(heightSegments) || 1;
  9354. depthSegments = Math.floor(depthSegments) || 1; // buffers
  9355. var indices = [];
  9356. var vertices = [];
  9357. var normals = [];
  9358. var uvs = []; // helper variables
  9359. var numberOfVertices = 0;
  9360. var groupStart = 0; // build each side of the box geometry
  9361. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  9362. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  9363. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  9364. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  9365. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  9366. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  9367. // build geometry
  9368. this.setIndex(indices);
  9369. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  9370. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  9371. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9372. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  9373. var segmentWidth = width / gridX;
  9374. var segmentHeight = height / gridY;
  9375. var widthHalf = width / 2;
  9376. var heightHalf = height / 2;
  9377. var depthHalf = depth / 2;
  9378. var gridX1 = gridX + 1;
  9379. var gridY1 = gridY + 1;
  9380. var vertexCounter = 0;
  9381. var groupCount = 0;
  9382. var ix, iy;
  9383. var vector = new Vector3(); // generate vertices, normals and uvs
  9384. for (iy = 0; iy < gridY1; iy++) {
  9385. var y = iy * segmentHeight - heightHalf;
  9386. for (ix = 0; ix < gridX1; ix++) {
  9387. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  9388. vector[u] = x * udir;
  9389. vector[v] = y * vdir;
  9390. vector[w] = depthHalf; // now apply vector to vertex buffer
  9391. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  9392. vector[u] = 0;
  9393. vector[v] = 0;
  9394. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  9395. normals.push(vector.x, vector.y, vector.z); // uvs
  9396. uvs.push(ix / gridX);
  9397. uvs.push(1 - iy / gridY); // counters
  9398. vertexCounter += 1;
  9399. }
  9400. } // indices
  9401. // 1. you need three indices to draw a single face
  9402. // 2. a single segment consists of two faces
  9403. // 3. so we need to generate six (2*3) indices per segment
  9404. for (iy = 0; iy < gridY; iy++) {
  9405. for (ix = 0; ix < gridX; ix++) {
  9406. var a = numberOfVertices + ix + gridX1 * iy;
  9407. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  9408. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  9409. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  9410. indices.push(a, b, d);
  9411. indices.push(b, c, d); // increase counter
  9412. groupCount += 6;
  9413. }
  9414. } // add a group to the geometry. this will ensure multi material support
  9415. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  9416. groupStart += groupCount; // update total number of vertices
  9417. numberOfVertices += vertexCounter;
  9418. }
  9419. }
  9420. }
  9421. /**
  9422. * Uniform Utilities
  9423. */
  9424. exports.BoxBufferGeometry = BoxBufferGeometry;
  9425. function cloneUniforms(src) {
  9426. var dst = {};
  9427. for (var u in src) {
  9428. dst[u] = {};
  9429. for (var p in src[u]) {
  9430. var property = src[u][p];
  9431. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  9432. dst[u][p] = property.clone();
  9433. } else if (Array.isArray(property)) {
  9434. dst[u][p] = property.slice();
  9435. } else {
  9436. dst[u][p] = property;
  9437. }
  9438. }
  9439. }
  9440. return dst;
  9441. }
  9442. function mergeUniforms(uniforms) {
  9443. var merged = {};
  9444. for (var u = 0; u < uniforms.length; u++) {
  9445. var tmp = cloneUniforms(uniforms[u]);
  9446. for (var p in tmp) {
  9447. merged[p] = tmp[p];
  9448. }
  9449. }
  9450. return merged;
  9451. } // Legacy
  9452. var UniformsUtils = {
  9453. clone: cloneUniforms,
  9454. merge: mergeUniforms
  9455. };
  9456. exports.UniformsUtils = UniformsUtils;
  9457. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  9458. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  9459. /**
  9460. * @author alteredq / http://alteredqualia.com/
  9461. *
  9462. * parameters = {
  9463. * defines: { "label" : "value" },
  9464. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  9465. *
  9466. * fragmentShader: <string>,
  9467. * vertexShader: <string>,
  9468. *
  9469. * wireframe: <boolean>,
  9470. * wireframeLinewidth: <float>,
  9471. *
  9472. * lights: <bool>,
  9473. *
  9474. * skinning: <bool>,
  9475. * morphTargets: <bool>,
  9476. * morphNormals: <bool>
  9477. * }
  9478. */
  9479. function ShaderMaterial(parameters) {
  9480. Material.call(this);
  9481. this.type = 'ShaderMaterial';
  9482. this.defines = {};
  9483. this.uniforms = {};
  9484. this.vertexShader = default_vertex;
  9485. this.fragmentShader = default_fragment;
  9486. this.linewidth = 1;
  9487. this.wireframe = false;
  9488. this.wireframeLinewidth = 1;
  9489. this.fog = false; // set to use scene fog
  9490. this.lights = false; // set to use scene lights
  9491. this.clipping = false; // set to use user-defined clipping planes
  9492. this.skinning = false; // set to use skinning attribute streams
  9493. this.morphTargets = false; // set to use morph targets
  9494. this.morphNormals = false; // set to use morph normals
  9495. this.extensions = {
  9496. derivatives: false,
  9497. // set to use derivatives
  9498. fragDepth: false,
  9499. // set to use fragment depth values
  9500. drawBuffers: false,
  9501. // set to use draw buffers
  9502. shaderTextureLOD: false // set to use shader texture LOD
  9503. }; // When rendered geometry doesn't include these attributes but the material does,
  9504. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9505. this.defaultAttributeValues = {
  9506. 'color': [1, 1, 1],
  9507. 'uv': [0, 0],
  9508. 'uv2': [0, 0]
  9509. };
  9510. this.index0AttributeName = undefined;
  9511. this.uniformsNeedUpdate = false;
  9512. if (parameters !== undefined) {
  9513. if (parameters.attributes !== undefined) {
  9514. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  9515. }
  9516. this.setValues(parameters);
  9517. }
  9518. }
  9519. ShaderMaterial.prototype = Object.create(Material.prototype);
  9520. ShaderMaterial.prototype.constructor = ShaderMaterial;
  9521. ShaderMaterial.prototype.isShaderMaterial = true;
  9522. ShaderMaterial.prototype.copy = function (source) {
  9523. Material.prototype.copy.call(this, source);
  9524. this.fragmentShader = source.fragmentShader;
  9525. this.vertexShader = source.vertexShader;
  9526. this.uniforms = cloneUniforms(source.uniforms);
  9527. this.defines = Object.assign({}, source.defines);
  9528. this.wireframe = source.wireframe;
  9529. this.wireframeLinewidth = source.wireframeLinewidth;
  9530. this.lights = source.lights;
  9531. this.clipping = source.clipping;
  9532. this.skinning = source.skinning;
  9533. this.morphTargets = source.morphTargets;
  9534. this.morphNormals = source.morphNormals;
  9535. this.extensions = source.extensions;
  9536. return this;
  9537. };
  9538. ShaderMaterial.prototype.toJSON = function (meta) {
  9539. var data = Material.prototype.toJSON.call(this, meta);
  9540. data.uniforms = {};
  9541. for (var name in this.uniforms) {
  9542. var uniform = this.uniforms[name];
  9543. var value = uniform.value;
  9544. if (value && value.isTexture) {
  9545. data.uniforms[name] = {
  9546. type: 't',
  9547. value: value.toJSON(meta).uuid
  9548. };
  9549. } else if (value && value.isColor) {
  9550. data.uniforms[name] = {
  9551. type: 'c',
  9552. value: value.getHex()
  9553. };
  9554. } else if (value && value.isVector2) {
  9555. data.uniforms[name] = {
  9556. type: 'v2',
  9557. value: value.toArray()
  9558. };
  9559. } else if (value && value.isVector3) {
  9560. data.uniforms[name] = {
  9561. type: 'v3',
  9562. value: value.toArray()
  9563. };
  9564. } else if (value && value.isVector4) {
  9565. data.uniforms[name] = {
  9566. type: 'v4',
  9567. value: value.toArray()
  9568. };
  9569. } else if (value && value.isMatrix3) {
  9570. data.uniforms[name] = {
  9571. type: 'm3',
  9572. value: value.toArray()
  9573. };
  9574. } else if (value && value.isMatrix4) {
  9575. data.uniforms[name] = {
  9576. type: 'm4',
  9577. value: value.toArray()
  9578. };
  9579. } else {
  9580. data.uniforms[name] = {
  9581. value: value
  9582. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  9583. }
  9584. }
  9585. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  9586. data.vertexShader = this.vertexShader;
  9587. data.fragmentShader = this.fragmentShader;
  9588. var extensions = {};
  9589. for (var key in this.extensions) {
  9590. if (this.extensions[key] === true) extensions[key] = true;
  9591. }
  9592. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  9593. return data;
  9594. };
  9595. /**
  9596. * @author mrdoob / http://mrdoob.com/
  9597. * @author mikael emtinger / http://gomo.se/
  9598. * @author WestLangley / http://github.com/WestLangley
  9599. */
  9600. function Camera() {
  9601. Object3D.call(this);
  9602. this.type = 'Camera';
  9603. this.matrixWorldInverse = new Matrix4();
  9604. this.projectionMatrix = new Matrix4();
  9605. this.projectionMatrixInverse = new Matrix4();
  9606. }
  9607. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  9608. constructor: Camera,
  9609. isCamera: true,
  9610. copy: function (source, recursive) {
  9611. Object3D.prototype.copy.call(this, source, recursive);
  9612. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  9613. this.projectionMatrix.copy(source.projectionMatrix);
  9614. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  9615. return this;
  9616. },
  9617. getWorldDirection: function (target) {
  9618. if (target === undefined) {
  9619. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  9620. target = new Vector3();
  9621. }
  9622. this.updateMatrixWorld(true);
  9623. var e = this.matrixWorld.elements;
  9624. return target.set(-e[8], -e[9], -e[10]).normalize();
  9625. },
  9626. updateMatrixWorld: function (force) {
  9627. Object3D.prototype.updateMatrixWorld.call(this, force);
  9628. this.matrixWorldInverse.getInverse(this.matrixWorld);
  9629. },
  9630. clone: function () {
  9631. return new this.constructor().copy(this);
  9632. }
  9633. });
  9634. /**
  9635. * @author mrdoob / http://mrdoob.com/
  9636. * @author greggman / http://games.greggman.com/
  9637. * @author zz85 / http://www.lab4games.net/zz85/blog
  9638. * @author tschw
  9639. */
  9640. function PerspectiveCamera(fov, aspect, near, far) {
  9641. Camera.call(this);
  9642. this.type = 'PerspectiveCamera';
  9643. this.fov = fov !== undefined ? fov : 50;
  9644. this.zoom = 1;
  9645. this.near = near !== undefined ? near : 0.1;
  9646. this.far = far !== undefined ? far : 2000;
  9647. this.focus = 10;
  9648. this.aspect = aspect !== undefined ? aspect : 1;
  9649. this.view = null;
  9650. this.filmGauge = 35; // width of the film (default in millimeters)
  9651. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9652. this.updateProjectionMatrix();
  9653. }
  9654. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  9655. constructor: PerspectiveCamera,
  9656. isPerspectiveCamera: true,
  9657. copy: function (source, recursive) {
  9658. Camera.prototype.copy.call(this, source, recursive);
  9659. this.fov = source.fov;
  9660. this.zoom = source.zoom;
  9661. this.near = source.near;
  9662. this.far = source.far;
  9663. this.focus = source.focus;
  9664. this.aspect = source.aspect;
  9665. this.view = source.view === null ? null : Object.assign({}, source.view);
  9666. this.filmGauge = source.filmGauge;
  9667. this.filmOffset = source.filmOffset;
  9668. return this;
  9669. },
  9670. /**
  9671. * Sets the FOV by focal length in respect to the current .filmGauge.
  9672. *
  9673. * The default film gauge is 35, so that the focal length can be specified for
  9674. * a 35mm (full frame) camera.
  9675. *
  9676. * Values for focal length and film gauge must have the same unit.
  9677. */
  9678. setFocalLength: function (focalLength) {
  9679. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9680. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9681. this.fov = _Math.RAD2DEG * 2 * Math.atan(vExtentSlope);
  9682. this.updateProjectionMatrix();
  9683. },
  9684. /**
  9685. * Calculates the focal length from the current .fov and .filmGauge.
  9686. */
  9687. getFocalLength: function () {
  9688. var vExtentSlope = Math.tan(_Math.DEG2RAD * 0.5 * this.fov);
  9689. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9690. },
  9691. getEffectiveFOV: function () {
  9692. return _Math.RAD2DEG * 2 * Math.atan(Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom);
  9693. },
  9694. getFilmWidth: function () {
  9695. // film not completely covered in portrait format (aspect < 1)
  9696. return this.filmGauge * Math.min(this.aspect, 1);
  9697. },
  9698. getFilmHeight: function () {
  9699. // film not completely covered in landscape format (aspect > 1)
  9700. return this.filmGauge / Math.max(this.aspect, 1);
  9701. },
  9702. /**
  9703. * Sets an offset in a larger frustum. This is useful for multi-window or
  9704. * multi-monitor/multi-machine setups.
  9705. *
  9706. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9707. * the monitors are in grid like this
  9708. *
  9709. * +---+---+---+
  9710. * | A | B | C |
  9711. * +---+---+---+
  9712. * | D | E | F |
  9713. * +---+---+---+
  9714. *
  9715. * then for each monitor you would call it like this
  9716. *
  9717. * var w = 1920;
  9718. * var h = 1080;
  9719. * var fullWidth = w * 3;
  9720. * var fullHeight = h * 2;
  9721. *
  9722. * --A--
  9723. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9724. * --B--
  9725. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9726. * --C--
  9727. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9728. * --D--
  9729. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9730. * --E--
  9731. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9732. * --F--
  9733. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9734. *
  9735. * Note there is no reason monitors have to be the same size or in a grid.
  9736. */
  9737. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  9738. this.aspect = fullWidth / fullHeight;
  9739. if (this.view === null) {
  9740. this.view = {
  9741. enabled: true,
  9742. fullWidth: 1,
  9743. fullHeight: 1,
  9744. offsetX: 0,
  9745. offsetY: 0,
  9746. width: 1,
  9747. height: 1
  9748. };
  9749. }
  9750. this.view.enabled = true;
  9751. this.view.fullWidth = fullWidth;
  9752. this.view.fullHeight = fullHeight;
  9753. this.view.offsetX = x;
  9754. this.view.offsetY = y;
  9755. this.view.width = width;
  9756. this.view.height = height;
  9757. this.updateProjectionMatrix();
  9758. },
  9759. clearViewOffset: function () {
  9760. if (this.view !== null) {
  9761. this.view.enabled = false;
  9762. }
  9763. this.updateProjectionMatrix();
  9764. },
  9765. updateProjectionMatrix: function () {
  9766. var near = this.near,
  9767. top = near * Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom,
  9768. height = 2 * top,
  9769. width = this.aspect * height,
  9770. left = -0.5 * width,
  9771. view = this.view;
  9772. if (this.view !== null && this.view.enabled) {
  9773. var fullWidth = view.fullWidth,
  9774. fullHeight = view.fullHeight;
  9775. left += view.offsetX * width / fullWidth;
  9776. top -= view.offsetY * height / fullHeight;
  9777. width *= view.width / fullWidth;
  9778. height *= view.height / fullHeight;
  9779. }
  9780. var skew = this.filmOffset;
  9781. if (skew !== 0) left += near * skew / this.getFilmWidth();
  9782. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  9783. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  9784. },
  9785. toJSON: function (meta) {
  9786. var data = Object3D.prototype.toJSON.call(this, meta);
  9787. data.object.fov = this.fov;
  9788. data.object.zoom = this.zoom;
  9789. data.object.near = this.near;
  9790. data.object.far = this.far;
  9791. data.object.focus = this.focus;
  9792. data.object.aspect = this.aspect;
  9793. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9794. data.object.filmGauge = this.filmGauge;
  9795. data.object.filmOffset = this.filmOffset;
  9796. return data;
  9797. }
  9798. });
  9799. /**
  9800. * Camera for rendering cube maps
  9801. * - renders scene into axis-aligned cube
  9802. *
  9803. * @author alteredq / http://alteredqualia.com/
  9804. */
  9805. var fov = 90,
  9806. aspect = 1;
  9807. function CubeCamera(near, far, cubeResolution, options) {
  9808. Object3D.call(this);
  9809. this.type = 'CubeCamera';
  9810. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  9811. cameraPX.up.set(0, -1, 0);
  9812. cameraPX.lookAt(new Vector3(1, 0, 0));
  9813. this.add(cameraPX);
  9814. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  9815. cameraNX.up.set(0, -1, 0);
  9816. cameraNX.lookAt(new Vector3(-1, 0, 0));
  9817. this.add(cameraNX);
  9818. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  9819. cameraPY.up.set(0, 0, 1);
  9820. cameraPY.lookAt(new Vector3(0, 1, 0));
  9821. this.add(cameraPY);
  9822. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  9823. cameraNY.up.set(0, 0, -1);
  9824. cameraNY.lookAt(new Vector3(0, -1, 0));
  9825. this.add(cameraNY);
  9826. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  9827. cameraPZ.up.set(0, -1, 0);
  9828. cameraPZ.lookAt(new Vector3(0, 0, 1));
  9829. this.add(cameraPZ);
  9830. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  9831. cameraNZ.up.set(0, -1, 0);
  9832. cameraNZ.lookAt(new Vector3(0, 0, -1));
  9833. this.add(cameraNZ);
  9834. options = options || {
  9835. format: RGBFormat,
  9836. magFilter: LinearFilter,
  9837. minFilter: LinearFilter
  9838. };
  9839. this.renderTarget = new WebGLRenderTargetCube(cubeResolution, cubeResolution, options);
  9840. this.renderTarget.texture.name = "CubeCamera";
  9841. this.update = function (renderer, scene) {
  9842. if (this.parent === null) this.updateMatrixWorld();
  9843. var currentRenderTarget = renderer.getRenderTarget();
  9844. var renderTarget = this.renderTarget;
  9845. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9846. renderTarget.texture.generateMipmaps = false;
  9847. renderer.setRenderTarget(renderTarget, 0);
  9848. renderer.render(scene, cameraPX);
  9849. renderer.setRenderTarget(renderTarget, 1);
  9850. renderer.render(scene, cameraNX);
  9851. renderer.setRenderTarget(renderTarget, 2);
  9852. renderer.render(scene, cameraPY);
  9853. renderer.setRenderTarget(renderTarget, 3);
  9854. renderer.render(scene, cameraNY);
  9855. renderer.setRenderTarget(renderTarget, 4);
  9856. renderer.render(scene, cameraPZ);
  9857. renderTarget.texture.generateMipmaps = generateMipmaps;
  9858. renderer.setRenderTarget(renderTarget, 5);
  9859. renderer.render(scene, cameraNZ);
  9860. renderer.setRenderTarget(currentRenderTarget);
  9861. };
  9862. this.clear = function (renderer, color, depth, stencil) {
  9863. var currentRenderTarget = renderer.getRenderTarget();
  9864. var renderTarget = this.renderTarget;
  9865. for (var i = 0; i < 6; i++) {
  9866. renderer.setRenderTarget(renderTarget, i);
  9867. renderer.clear(color, depth, stencil);
  9868. }
  9869. renderer.setRenderTarget(currentRenderTarget);
  9870. };
  9871. }
  9872. CubeCamera.prototype = Object.create(Object3D.prototype);
  9873. CubeCamera.prototype.constructor = CubeCamera;
  9874. /**
  9875. * @author alteredq / http://alteredqualia.com
  9876. * @author WestLangley / http://github.com/WestLangley
  9877. */
  9878. function WebGLRenderTargetCube(width, height, options) {
  9879. WebGLRenderTarget.call(this, width, height, options);
  9880. }
  9881. WebGLRenderTargetCube.prototype = Object.create(WebGLRenderTarget.prototype);
  9882. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  9883. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  9884. WebGLRenderTargetCube.prototype.fromEquirectangularTexture = function (renderer, texture) {
  9885. this.texture.type = texture.type;
  9886. this.texture.format = texture.format;
  9887. this.texture.encoding = texture.encoding;
  9888. var scene = new Scene();
  9889. var shader = {
  9890. uniforms: {
  9891. tEquirect: {
  9892. value: null
  9893. }
  9894. },
  9895. 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'),
  9896. 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')
  9897. };
  9898. var material = new ShaderMaterial({
  9899. type: 'CubemapFromEquirect',
  9900. uniforms: cloneUniforms(shader.uniforms),
  9901. vertexShader: shader.vertexShader,
  9902. fragmentShader: shader.fragmentShader,
  9903. side: BackSide,
  9904. blending: NoBlending
  9905. });
  9906. material.uniforms.tEquirect.value = texture;
  9907. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  9908. scene.add(mesh);
  9909. var camera = new CubeCamera(1, 10, 1);
  9910. camera.renderTarget = this;
  9911. camera.renderTarget.texture.name = 'CubeCameraTexture';
  9912. camera.update(renderer, scene);
  9913. mesh.geometry.dispose();
  9914. mesh.material.dispose();
  9915. return this;
  9916. };
  9917. /**
  9918. * @author alteredq / http://alteredqualia.com/
  9919. */
  9920. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  9921. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  9922. this.image = {
  9923. data: data || null,
  9924. width: width || 1,
  9925. height: height || 1
  9926. };
  9927. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  9928. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  9929. this.generateMipmaps = false;
  9930. this.flipY = false;
  9931. this.unpackAlignment = 1;
  9932. this.needsUpdate = true;
  9933. }
  9934. DataTexture.prototype = Object.create(Texture.prototype);
  9935. DataTexture.prototype.constructor = DataTexture;
  9936. DataTexture.prototype.isDataTexture = true;
  9937. /**
  9938. * @author bhouston / http://clara.io
  9939. */
  9940. var _vector1 = new Vector3();
  9941. var _vector2 = new Vector3();
  9942. var _normalMatrix = new Matrix3();
  9943. function Plane(normal, constant) {
  9944. // normal is assumed to be normalized
  9945. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  9946. this.constant = constant !== undefined ? constant : 0;
  9947. }
  9948. Object.assign(Plane.prototype, {
  9949. isPlane: true,
  9950. set: function (normal, constant) {
  9951. this.normal.copy(normal);
  9952. this.constant = constant;
  9953. return this;
  9954. },
  9955. setComponents: function (x, y, z, w) {
  9956. this.normal.set(x, y, z);
  9957. this.constant = w;
  9958. return this;
  9959. },
  9960. setFromNormalAndCoplanarPoint: function (normal, point) {
  9961. this.normal.copy(normal);
  9962. this.constant = -point.dot(this.normal);
  9963. return this;
  9964. },
  9965. setFromCoplanarPoints: function (a, b, c) {
  9966. 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)?
  9967. this.setFromNormalAndCoplanarPoint(normal, a);
  9968. return this;
  9969. },
  9970. clone: function () {
  9971. return new this.constructor().copy(this);
  9972. },
  9973. copy: function (plane) {
  9974. this.normal.copy(plane.normal);
  9975. this.constant = plane.constant;
  9976. return this;
  9977. },
  9978. normalize: function () {
  9979. // Note: will lead to a divide by zero if the plane is invalid.
  9980. var inverseNormalLength = 1.0 / this.normal.length();
  9981. this.normal.multiplyScalar(inverseNormalLength);
  9982. this.constant *= inverseNormalLength;
  9983. return this;
  9984. },
  9985. negate: function () {
  9986. this.constant *= -1;
  9987. this.normal.negate();
  9988. return this;
  9989. },
  9990. distanceToPoint: function (point) {
  9991. return this.normal.dot(point) + this.constant;
  9992. },
  9993. distanceToSphere: function (sphere) {
  9994. return this.distanceToPoint(sphere.center) - sphere.radius;
  9995. },
  9996. projectPoint: function (point, target) {
  9997. if (target === undefined) {
  9998. console.warn('THREE.Plane: .projectPoint() target is now required');
  9999. target = new Vector3();
  10000. }
  10001. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  10002. },
  10003. intersectLine: function (line, target) {
  10004. if (target === undefined) {
  10005. console.warn('THREE.Plane: .intersectLine() target is now required');
  10006. target = new Vector3();
  10007. }
  10008. var direction = line.delta(_vector1);
  10009. var denominator = this.normal.dot(direction);
  10010. if (denominator === 0) {
  10011. // line is coplanar, return origin
  10012. if (this.distanceToPoint(line.start) === 0) {
  10013. return target.copy(line.start);
  10014. } // Unsure if this is the correct method to handle this case.
  10015. return undefined;
  10016. }
  10017. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  10018. if (t < 0 || t > 1) {
  10019. return undefined;
  10020. }
  10021. return target.copy(direction).multiplyScalar(t).add(line.start);
  10022. },
  10023. intersectsLine: function (line) {
  10024. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  10025. var startSign = this.distanceToPoint(line.start);
  10026. var endSign = this.distanceToPoint(line.end);
  10027. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  10028. },
  10029. intersectsBox: function (box) {
  10030. return box.intersectsPlane(this);
  10031. },
  10032. intersectsSphere: function (sphere) {
  10033. return sphere.intersectsPlane(this);
  10034. },
  10035. coplanarPoint: function (target) {
  10036. if (target === undefined) {
  10037. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  10038. target = new Vector3();
  10039. }
  10040. return target.copy(this.normal).multiplyScalar(-this.constant);
  10041. },
  10042. applyMatrix4: function (matrix, optionalNormalMatrix) {
  10043. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  10044. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  10045. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  10046. this.constant = -referencePoint.dot(normal);
  10047. return this;
  10048. },
  10049. translate: function (offset) {
  10050. this.constant -= offset.dot(this.normal);
  10051. return this;
  10052. },
  10053. equals: function (plane) {
  10054. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  10055. }
  10056. });
  10057. /**
  10058. * @author mrdoob / http://mrdoob.com/
  10059. * @author alteredq / http://alteredqualia.com/
  10060. * @author bhouston / http://clara.io
  10061. */
  10062. var _sphere$1 = new Sphere();
  10063. var _vector$5 = new Vector3();
  10064. function Frustum(p0, p1, p2, p3, p4, p5) {
  10065. 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()];
  10066. }
  10067. Object.assign(Frustum.prototype, {
  10068. set: function (p0, p1, p2, p3, p4, p5) {
  10069. var planes = this.planes;
  10070. planes[0].copy(p0);
  10071. planes[1].copy(p1);
  10072. planes[2].copy(p2);
  10073. planes[3].copy(p3);
  10074. planes[4].copy(p4);
  10075. planes[5].copy(p5);
  10076. return this;
  10077. },
  10078. clone: function () {
  10079. return new this.constructor().copy(this);
  10080. },
  10081. copy: function (frustum) {
  10082. var planes = this.planes;
  10083. for (var i = 0; i < 6; i++) {
  10084. planes[i].copy(frustum.planes[i]);
  10085. }
  10086. return this;
  10087. },
  10088. setFromMatrix: function (m) {
  10089. var planes = this.planes;
  10090. var me = m.elements;
  10091. var me0 = me[0],
  10092. me1 = me[1],
  10093. me2 = me[2],
  10094. me3 = me[3];
  10095. var me4 = me[4],
  10096. me5 = me[5],
  10097. me6 = me[6],
  10098. me7 = me[7];
  10099. var me8 = me[8],
  10100. me9 = me[9],
  10101. me10 = me[10],
  10102. me11 = me[11];
  10103. var me12 = me[12],
  10104. me13 = me[13],
  10105. me14 = me[14],
  10106. me15 = me[15];
  10107. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  10108. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  10109. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  10110. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  10111. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  10112. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  10113. return this;
  10114. },
  10115. intersectsObject: function (object) {
  10116. var geometry = object.geometry;
  10117. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  10118. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  10119. return this.intersectsSphere(_sphere$1);
  10120. },
  10121. intersectsSprite: function (sprite) {
  10122. _sphere$1.center.set(0, 0, 0);
  10123. _sphere$1.radius = 0.7071067811865476;
  10124. _sphere$1.applyMatrix4(sprite.matrixWorld);
  10125. return this.intersectsSphere(_sphere$1);
  10126. },
  10127. intersectsSphere: function (sphere) {
  10128. var planes = this.planes;
  10129. var center = sphere.center;
  10130. var negRadius = -sphere.radius;
  10131. for (var i = 0; i < 6; i++) {
  10132. var distance = planes[i].distanceToPoint(center);
  10133. if (distance < negRadius) {
  10134. return false;
  10135. }
  10136. }
  10137. return true;
  10138. },
  10139. intersectsBox: function (box) {
  10140. var planes = this.planes;
  10141. for (var i = 0; i < 6; i++) {
  10142. var plane = planes[i]; // corner at max distance
  10143. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10144. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10145. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10146. if (plane.distanceToPoint(_vector$5) < 0) {
  10147. return false;
  10148. }
  10149. }
  10150. return true;
  10151. },
  10152. containsPoint: function (point) {
  10153. var planes = this.planes;
  10154. for (var i = 0; i < 6; i++) {
  10155. if (planes[i].distanceToPoint(point) < 0) {
  10156. return false;
  10157. }
  10158. }
  10159. return true;
  10160. }
  10161. });
  10162. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  10163. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  10164. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  10165. 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";
  10166. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  10167. var begin_vertex = "vec3 transformed = vec3( position );";
  10168. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  10169. 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";
  10170. 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";
  10171. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  10172. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  10173. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  10174. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  10175. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  10176. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10177. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10178. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  10179. 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}";
  10180. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV( sampler2D envMap, vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif";
  10181. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\ttransformedNormal = mat3( instanceMatrix ) * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = normalMatrix * objectTangent;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  10182. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  10183. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  10184. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  10185. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  10186. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  10187. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  10188. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  10189. 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";
  10190. 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";
  10191. 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";
  10192. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  10193. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  10194. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  10195. 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";
  10196. 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";
  10197. var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif";
  10198. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  10199. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  10200. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif";
  10201. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  10202. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryReflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  10203. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  10204. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  10205. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = saturate( clearcoat );\tmaterial.clearcoatRoughness = clamp( clearcoatRoughness, 0.04, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  10206. 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}";
  10207. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( pointLight.shadow, directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( spotLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( directionalLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  10208. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  10209. 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";
  10210. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 1.0 ? log2( vFragDepth ) * logDepthBufFC * 0.5 : gl_FragCoord.z;\n#endif";
  10211. 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";
  10212. 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";
  10213. 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";
  10214. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  10215. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  10216. var map_particle_fragment = "#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif";
  10217. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  10218. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  10219. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  10220. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif";
  10221. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  10222. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  10223. var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  10224. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, normalScale, normalMap );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  10225. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 normalScale, in sampler2D normalMap ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy *= normalScale;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tbool frontFacing = dot( cross( S, T ), N ) > 0.0;\n\t\t\tmapN.xy *= ( float( frontFacing ) * 2.0 - 1.0 );\n\t\t#else\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  10226. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  10227. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = clearcoatNormalScale * mapN.xy;\n\t\tclearcoatNormal = normalize( vTBN * mapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatNormalScale, clearcoatNormalMap );\n\t#endif\n#endif";
  10228. var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  10229. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 encodeHalfRGBA ( vec2 v ) {\n\tvec4 encoded = vec4( 0.0 );\n\tconst vec2 offset = vec2( 1.0 / 255.0, 0.0 );\n\tencoded.xy = vec2( v.x, fract( v.x * 255.0 ) );\n\tencoded.xy = encoded.xy - ( encoded.yy * offset );\n\tencoded.zw = vec2( v.y, fract( v.y * 255.0 ) );\n\tencoded.zw = encoded.zw - ( encoded.ww * offset );\n\treturn encoded;\n}\nvec2 decodeHalfRGBA( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  10230. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  10231. 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;";
  10232. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  10233. 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";
  10234. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  10235. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  10236. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn decodeHalfRGBA( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = ( floor( uv * size - 0.5 ) + 0.5 ) * texelSize;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  10237. 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";
  10238. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif";
  10239. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= all( bvec2( directionalLight.shadow, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= all( bvec2( spotLight.shadow, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= all( bvec2( pointLight.shadow, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  10240. 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";
  10241. 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";
  10242. 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";
  10243. 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";
  10244. 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";
  10245. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  10246. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  10247. 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}";
  10248. var uv_pars_fragment = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif";
  10249. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  10250. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  10251. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  10252. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  10253. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  10254. 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";
  10255. 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}";
  10256. 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}";
  10257. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  10258. 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}";
  10259. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}";
  10260. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}";
  10261. 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}";
  10262. 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}";
  10263. 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}";
  10264. 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}";
  10265. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10266. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  10267. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10268. 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}";
  10269. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  10270. 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}";
  10271. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10272. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  10273. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  10274. 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}";
  10275. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  10276. 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}";
  10277. 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}";
  10278. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  10279. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10280. 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}";
  10281. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <fog_fragment>\n}";
  10282. 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}";
  10283. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  10284. 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}";
  10285. var ShaderChunk = {
  10286. alphamap_fragment: alphamap_fragment,
  10287. alphamap_pars_fragment: alphamap_pars_fragment,
  10288. alphatest_fragment: alphatest_fragment,
  10289. aomap_fragment: aomap_fragment,
  10290. aomap_pars_fragment: aomap_pars_fragment,
  10291. begin_vertex: begin_vertex,
  10292. beginnormal_vertex: beginnormal_vertex,
  10293. bsdfs: bsdfs,
  10294. bumpmap_pars_fragment: bumpmap_pars_fragment,
  10295. clipping_planes_fragment: clipping_planes_fragment,
  10296. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  10297. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  10298. clipping_planes_vertex: clipping_planes_vertex,
  10299. color_fragment: color_fragment,
  10300. color_pars_fragment: color_pars_fragment,
  10301. color_pars_vertex: color_pars_vertex,
  10302. color_vertex: color_vertex,
  10303. common: common,
  10304. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  10305. defaultnormal_vertex: defaultnormal_vertex,
  10306. displacementmap_pars_vertex: displacementmap_pars_vertex,
  10307. displacementmap_vertex: displacementmap_vertex,
  10308. emissivemap_fragment: emissivemap_fragment,
  10309. emissivemap_pars_fragment: emissivemap_pars_fragment,
  10310. encodings_fragment: encodings_fragment,
  10311. encodings_pars_fragment: encodings_pars_fragment,
  10312. envmap_fragment: envmap_fragment,
  10313. envmap_common_pars_fragment: envmap_common_pars_fragment,
  10314. envmap_pars_fragment: envmap_pars_fragment,
  10315. envmap_pars_vertex: envmap_pars_vertex,
  10316. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  10317. envmap_vertex: envmap_vertex,
  10318. fog_vertex: fog_vertex,
  10319. fog_pars_vertex: fog_pars_vertex,
  10320. fog_fragment: fog_fragment,
  10321. fog_pars_fragment: fog_pars_fragment,
  10322. gradientmap_pars_fragment: gradientmap_pars_fragment,
  10323. lightmap_fragment: lightmap_fragment,
  10324. lightmap_pars_fragment: lightmap_pars_fragment,
  10325. lights_lambert_vertex: lights_lambert_vertex,
  10326. lights_pars_begin: lights_pars_begin,
  10327. lights_phong_fragment: lights_phong_fragment,
  10328. lights_phong_pars_fragment: lights_phong_pars_fragment,
  10329. lights_physical_fragment: lights_physical_fragment,
  10330. lights_physical_pars_fragment: lights_physical_pars_fragment,
  10331. lights_fragment_begin: lights_fragment_begin,
  10332. lights_fragment_maps: lights_fragment_maps,
  10333. lights_fragment_end: lights_fragment_end,
  10334. logdepthbuf_fragment: logdepthbuf_fragment,
  10335. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  10336. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  10337. logdepthbuf_vertex: logdepthbuf_vertex,
  10338. map_fragment: map_fragment,
  10339. map_pars_fragment: map_pars_fragment,
  10340. map_particle_fragment: map_particle_fragment,
  10341. map_particle_pars_fragment: map_particle_pars_fragment,
  10342. metalnessmap_fragment: metalnessmap_fragment,
  10343. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  10344. morphnormal_vertex: morphnormal_vertex,
  10345. morphtarget_pars_vertex: morphtarget_pars_vertex,
  10346. morphtarget_vertex: morphtarget_vertex,
  10347. normal_fragment_begin: normal_fragment_begin,
  10348. normal_fragment_maps: normal_fragment_maps,
  10349. normalmap_pars_fragment: normalmap_pars_fragment,
  10350. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  10351. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  10352. clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,
  10353. packing: packing,
  10354. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  10355. project_vertex: project_vertex,
  10356. dithering_fragment: dithering_fragment,
  10357. dithering_pars_fragment: dithering_pars_fragment,
  10358. roughnessmap_fragment: roughnessmap_fragment,
  10359. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  10360. shadowmap_pars_fragment: shadowmap_pars_fragment,
  10361. shadowmap_pars_vertex: shadowmap_pars_vertex,
  10362. shadowmap_vertex: shadowmap_vertex,
  10363. shadowmask_pars_fragment: shadowmask_pars_fragment,
  10364. skinbase_vertex: skinbase_vertex,
  10365. skinning_pars_vertex: skinning_pars_vertex,
  10366. skinning_vertex: skinning_vertex,
  10367. skinnormal_vertex: skinnormal_vertex,
  10368. specularmap_fragment: specularmap_fragment,
  10369. specularmap_pars_fragment: specularmap_pars_fragment,
  10370. tonemapping_fragment: tonemapping_fragment,
  10371. tonemapping_pars_fragment: tonemapping_pars_fragment,
  10372. uv_pars_fragment: uv_pars_fragment,
  10373. uv_pars_vertex: uv_pars_vertex,
  10374. uv_vertex: uv_vertex,
  10375. uv2_pars_fragment: uv2_pars_fragment,
  10376. uv2_pars_vertex: uv2_pars_vertex,
  10377. uv2_vertex: uv2_vertex,
  10378. worldpos_vertex: worldpos_vertex,
  10379. background_frag: background_frag,
  10380. background_vert: background_vert,
  10381. cube_frag: cube_frag,
  10382. cube_vert: cube_vert,
  10383. depth_frag: depth_frag,
  10384. depth_vert: depth_vert,
  10385. distanceRGBA_frag: distanceRGBA_frag,
  10386. distanceRGBA_vert: distanceRGBA_vert,
  10387. equirect_frag: equirect_frag,
  10388. equirect_vert: equirect_vert,
  10389. linedashed_frag: linedashed_frag,
  10390. linedashed_vert: linedashed_vert,
  10391. meshbasic_frag: meshbasic_frag,
  10392. meshbasic_vert: meshbasic_vert,
  10393. meshlambert_frag: meshlambert_frag,
  10394. meshlambert_vert: meshlambert_vert,
  10395. meshmatcap_frag: meshmatcap_frag,
  10396. meshmatcap_vert: meshmatcap_vert,
  10397. meshphong_frag: meshphong_frag,
  10398. meshphong_vert: meshphong_vert,
  10399. meshphysical_frag: meshphysical_frag,
  10400. meshphysical_vert: meshphysical_vert,
  10401. normal_frag: normal_frag,
  10402. normal_vert: normal_vert,
  10403. points_frag: points_frag,
  10404. points_vert: points_vert,
  10405. shadow_frag: shadow_frag,
  10406. shadow_vert: shadow_vert,
  10407. sprite_frag: sprite_frag,
  10408. sprite_vert: sprite_vert
  10409. };
  10410. /**
  10411. * Uniforms library for shared webgl shaders
  10412. */
  10413. exports.ShaderChunk = ShaderChunk;
  10414. var UniformsLib = {
  10415. common: {
  10416. diffuse: {
  10417. value: new Color(0xeeeeee)
  10418. },
  10419. opacity: {
  10420. value: 1.0
  10421. },
  10422. map: {
  10423. value: null
  10424. },
  10425. uvTransform: {
  10426. value: new Matrix3()
  10427. },
  10428. alphaMap: {
  10429. value: null
  10430. }
  10431. },
  10432. specularmap: {
  10433. specularMap: {
  10434. value: null
  10435. }
  10436. },
  10437. envmap: {
  10438. envMap: {
  10439. value: null
  10440. },
  10441. flipEnvMap: {
  10442. value: -1
  10443. },
  10444. reflectivity: {
  10445. value: 1.0
  10446. },
  10447. refractionRatio: {
  10448. value: 0.98
  10449. },
  10450. maxMipLevel: {
  10451. value: 0
  10452. }
  10453. },
  10454. aomap: {
  10455. aoMap: {
  10456. value: null
  10457. },
  10458. aoMapIntensity: {
  10459. value: 1
  10460. }
  10461. },
  10462. lightmap: {
  10463. lightMap: {
  10464. value: null
  10465. },
  10466. lightMapIntensity: {
  10467. value: 1
  10468. }
  10469. },
  10470. emissivemap: {
  10471. emissiveMap: {
  10472. value: null
  10473. }
  10474. },
  10475. bumpmap: {
  10476. bumpMap: {
  10477. value: null
  10478. },
  10479. bumpScale: {
  10480. value: 1
  10481. }
  10482. },
  10483. normalmap: {
  10484. normalMap: {
  10485. value: null
  10486. },
  10487. normalScale: {
  10488. value: new Vector2(1, 1)
  10489. }
  10490. },
  10491. displacementmap: {
  10492. displacementMap: {
  10493. value: null
  10494. },
  10495. displacementScale: {
  10496. value: 1
  10497. },
  10498. displacementBias: {
  10499. value: 0
  10500. }
  10501. },
  10502. roughnessmap: {
  10503. roughnessMap: {
  10504. value: null
  10505. }
  10506. },
  10507. metalnessmap: {
  10508. metalnessMap: {
  10509. value: null
  10510. }
  10511. },
  10512. gradientmap: {
  10513. gradientMap: {
  10514. value: null
  10515. }
  10516. },
  10517. fog: {
  10518. fogDensity: {
  10519. value: 0.00025
  10520. },
  10521. fogNear: {
  10522. value: 1
  10523. },
  10524. fogFar: {
  10525. value: 2000
  10526. },
  10527. fogColor: {
  10528. value: new Color(0xffffff)
  10529. }
  10530. },
  10531. lights: {
  10532. ambientLightColor: {
  10533. value: []
  10534. },
  10535. lightProbe: {
  10536. value: []
  10537. },
  10538. directionalLights: {
  10539. value: [],
  10540. properties: {
  10541. direction: {},
  10542. color: {},
  10543. shadow: {},
  10544. shadowBias: {},
  10545. shadowRadius: {},
  10546. shadowMapSize: {}
  10547. }
  10548. },
  10549. directionalShadowMap: {
  10550. value: []
  10551. },
  10552. directionalShadowMatrix: {
  10553. value: []
  10554. },
  10555. spotLights: {
  10556. value: [],
  10557. properties: {
  10558. color: {},
  10559. position: {},
  10560. direction: {},
  10561. distance: {},
  10562. coneCos: {},
  10563. penumbraCos: {},
  10564. decay: {},
  10565. shadow: {},
  10566. shadowBias: {},
  10567. shadowRadius: {},
  10568. shadowMapSize: {}
  10569. }
  10570. },
  10571. spotShadowMap: {
  10572. value: []
  10573. },
  10574. spotShadowMatrix: {
  10575. value: []
  10576. },
  10577. pointLights: {
  10578. value: [],
  10579. properties: {
  10580. color: {},
  10581. position: {},
  10582. decay: {},
  10583. distance: {},
  10584. shadow: {},
  10585. shadowBias: {},
  10586. shadowRadius: {},
  10587. shadowMapSize: {},
  10588. shadowCameraNear: {},
  10589. shadowCameraFar: {}
  10590. }
  10591. },
  10592. pointShadowMap: {
  10593. value: []
  10594. },
  10595. pointShadowMatrix: {
  10596. value: []
  10597. },
  10598. hemisphereLights: {
  10599. value: [],
  10600. properties: {
  10601. direction: {},
  10602. skyColor: {},
  10603. groundColor: {}
  10604. }
  10605. },
  10606. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  10607. rectAreaLights: {
  10608. value: [],
  10609. properties: {
  10610. color: {},
  10611. position: {},
  10612. width: {},
  10613. height: {}
  10614. }
  10615. }
  10616. },
  10617. points: {
  10618. diffuse: {
  10619. value: new Color(0xeeeeee)
  10620. },
  10621. opacity: {
  10622. value: 1.0
  10623. },
  10624. size: {
  10625. value: 1.0
  10626. },
  10627. scale: {
  10628. value: 1.0
  10629. },
  10630. map: {
  10631. value: null
  10632. },
  10633. uvTransform: {
  10634. value: new Matrix3()
  10635. }
  10636. },
  10637. sprite: {
  10638. diffuse: {
  10639. value: new Color(0xeeeeee)
  10640. },
  10641. opacity: {
  10642. value: 1.0
  10643. },
  10644. center: {
  10645. value: new Vector2(0.5, 0.5)
  10646. },
  10647. rotation: {
  10648. value: 0.0
  10649. },
  10650. map: {
  10651. value: null
  10652. },
  10653. uvTransform: {
  10654. value: new Matrix3()
  10655. }
  10656. }
  10657. };
  10658. /**
  10659. * @author alteredq / http://alteredqualia.com/
  10660. * @author mrdoob / http://mrdoob.com/
  10661. * @author mikael emtinger / http://gomo.se/
  10662. */
  10663. exports.UniformsLib = UniformsLib;
  10664. var ShaderLib = {
  10665. basic: {
  10666. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  10667. vertexShader: ShaderChunk.meshbasic_vert,
  10668. fragmentShader: ShaderChunk.meshbasic_frag
  10669. },
  10670. lambert: {
  10671. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  10672. emissive: {
  10673. value: new Color(0x000000)
  10674. }
  10675. }]),
  10676. vertexShader: ShaderChunk.meshlambert_vert,
  10677. fragmentShader: ShaderChunk.meshlambert_frag
  10678. },
  10679. phong: {
  10680. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  10681. emissive: {
  10682. value: new Color(0x000000)
  10683. },
  10684. specular: {
  10685. value: new Color(0x111111)
  10686. },
  10687. shininess: {
  10688. value: 30
  10689. }
  10690. }]),
  10691. vertexShader: ShaderChunk.meshphong_vert,
  10692. fragmentShader: ShaderChunk.meshphong_frag
  10693. },
  10694. standard: {
  10695. 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, {
  10696. emissive: {
  10697. value: new Color(0x000000)
  10698. },
  10699. roughness: {
  10700. value: 0.5
  10701. },
  10702. metalness: {
  10703. value: 0.5
  10704. },
  10705. envMapIntensity: {
  10706. value: 1
  10707. } // temporary
  10708. }]),
  10709. vertexShader: ShaderChunk.meshphysical_vert,
  10710. fragmentShader: ShaderChunk.meshphysical_frag
  10711. },
  10712. matcap: {
  10713. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  10714. matcap: {
  10715. value: null
  10716. }
  10717. }]),
  10718. vertexShader: ShaderChunk.meshmatcap_vert,
  10719. fragmentShader: ShaderChunk.meshmatcap_frag
  10720. },
  10721. points: {
  10722. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  10723. vertexShader: ShaderChunk.points_vert,
  10724. fragmentShader: ShaderChunk.points_frag
  10725. },
  10726. dashed: {
  10727. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  10728. scale: {
  10729. value: 1
  10730. },
  10731. dashSize: {
  10732. value: 1
  10733. },
  10734. totalSize: {
  10735. value: 2
  10736. }
  10737. }]),
  10738. vertexShader: ShaderChunk.linedashed_vert,
  10739. fragmentShader: ShaderChunk.linedashed_frag
  10740. },
  10741. depth: {
  10742. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  10743. vertexShader: ShaderChunk.depth_vert,
  10744. fragmentShader: ShaderChunk.depth_frag
  10745. },
  10746. normal: {
  10747. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  10748. opacity: {
  10749. value: 1.0
  10750. }
  10751. }]),
  10752. vertexShader: ShaderChunk.normal_vert,
  10753. fragmentShader: ShaderChunk.normal_frag
  10754. },
  10755. sprite: {
  10756. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  10757. vertexShader: ShaderChunk.sprite_vert,
  10758. fragmentShader: ShaderChunk.sprite_frag
  10759. },
  10760. background: {
  10761. uniforms: {
  10762. uvTransform: {
  10763. value: new Matrix3()
  10764. },
  10765. t2D: {
  10766. value: null
  10767. }
  10768. },
  10769. vertexShader: ShaderChunk.background_vert,
  10770. fragmentShader: ShaderChunk.background_frag
  10771. },
  10772. /* -------------------------------------------------------------------------
  10773. // Cube map shader
  10774. ------------------------------------------------------------------------- */
  10775. cube: {
  10776. uniforms: {
  10777. tCube: {
  10778. value: null
  10779. },
  10780. tFlip: {
  10781. value: -1
  10782. },
  10783. opacity: {
  10784. value: 1.0
  10785. }
  10786. },
  10787. vertexShader: ShaderChunk.cube_vert,
  10788. fragmentShader: ShaderChunk.cube_frag
  10789. },
  10790. equirect: {
  10791. uniforms: {
  10792. tEquirect: {
  10793. value: null
  10794. }
  10795. },
  10796. vertexShader: ShaderChunk.equirect_vert,
  10797. fragmentShader: ShaderChunk.equirect_frag
  10798. },
  10799. distanceRGBA: {
  10800. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  10801. referencePosition: {
  10802. value: new Vector3()
  10803. },
  10804. nearDistance: {
  10805. value: 1
  10806. },
  10807. farDistance: {
  10808. value: 1000
  10809. }
  10810. }]),
  10811. vertexShader: ShaderChunk.distanceRGBA_vert,
  10812. fragmentShader: ShaderChunk.distanceRGBA_frag
  10813. },
  10814. shadow: {
  10815. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  10816. color: {
  10817. value: new Color(0x00000)
  10818. },
  10819. opacity: {
  10820. value: 1.0
  10821. }
  10822. }]),
  10823. vertexShader: ShaderChunk.shadow_vert,
  10824. fragmentShader: ShaderChunk.shadow_frag
  10825. }
  10826. };
  10827. exports.ShaderLib = ShaderLib;
  10828. ShaderLib.physical = {
  10829. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  10830. transparency: {
  10831. value: 0
  10832. },
  10833. clearcoat: {
  10834. value: 0
  10835. },
  10836. clearcoatRoughness: {
  10837. value: 0
  10838. },
  10839. sheen: {
  10840. value: new Color(0x000000)
  10841. },
  10842. clearcoatNormalScale: {
  10843. value: new Vector2(1, 1)
  10844. },
  10845. clearcoatNormalMap: {
  10846. value: null
  10847. }
  10848. }]),
  10849. vertexShader: ShaderChunk.meshphysical_vert,
  10850. fragmentShader: ShaderChunk.meshphysical_frag
  10851. };
  10852. /**
  10853. * @author mrdoob / http://mrdoob.com/
  10854. */
  10855. function WebGLAnimation() {
  10856. var context = null;
  10857. var isAnimating = false;
  10858. var animationLoop = null;
  10859. function onAnimationFrame(time, frame) {
  10860. if (isAnimating === false) return;
  10861. animationLoop(time, frame);
  10862. context.requestAnimationFrame(onAnimationFrame);
  10863. }
  10864. return {
  10865. start: function () {
  10866. if (isAnimating === true) return;
  10867. if (animationLoop === null) return;
  10868. context.requestAnimationFrame(onAnimationFrame);
  10869. isAnimating = true;
  10870. },
  10871. stop: function () {
  10872. isAnimating = false;
  10873. },
  10874. setAnimationLoop: function (callback) {
  10875. animationLoop = callback;
  10876. },
  10877. setContext: function (value) {
  10878. context = value;
  10879. }
  10880. };
  10881. }
  10882. /**
  10883. * @author mrdoob / http://mrdoob.com/
  10884. */
  10885. function WebGLAttributes(gl) {
  10886. var buffers = new WeakMap();
  10887. function createBuffer(attribute, bufferType) {
  10888. var array = attribute.array;
  10889. var usage = attribute.dynamic ? 35048 : 35044;
  10890. var buffer = gl.createBuffer();
  10891. gl.bindBuffer(bufferType, buffer);
  10892. gl.bufferData(bufferType, array, usage);
  10893. attribute.onUploadCallback();
  10894. var type = 5126;
  10895. if (array instanceof Float32Array) {
  10896. type = 5126;
  10897. } else if (array instanceof Float64Array) {
  10898. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  10899. } else if (array instanceof Uint16Array) {
  10900. type = 5123;
  10901. } else if (array instanceof Int16Array) {
  10902. type = 5122;
  10903. } else if (array instanceof Uint32Array) {
  10904. type = 5125;
  10905. } else if (array instanceof Int32Array) {
  10906. type = 5124;
  10907. } else if (array instanceof Int8Array) {
  10908. type = 5120;
  10909. } else if (array instanceof Uint8Array) {
  10910. type = 5121;
  10911. }
  10912. return {
  10913. buffer: buffer,
  10914. type: type,
  10915. bytesPerElement: array.BYTES_PER_ELEMENT,
  10916. version: attribute.version
  10917. };
  10918. }
  10919. function updateBuffer(buffer, attribute, bufferType) {
  10920. var array = attribute.array;
  10921. var updateRange = attribute.updateRange;
  10922. gl.bindBuffer(bufferType, buffer);
  10923. if (attribute.dynamic === false) {
  10924. gl.bufferData(bufferType, array, 35044);
  10925. } else if (updateRange.count === -1) {
  10926. // Not using update ranges
  10927. gl.bufferSubData(bufferType, 0, array);
  10928. } else if (updateRange.count === 0) {
  10929. console.error('THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.');
  10930. } else {
  10931. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  10932. updateRange.count = -1; // reset range
  10933. }
  10934. } //
  10935. function get(attribute) {
  10936. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10937. return buffers.get(attribute);
  10938. }
  10939. function remove(attribute) {
  10940. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10941. var data = buffers.get(attribute);
  10942. if (data) {
  10943. gl.deleteBuffer(data.buffer);
  10944. buffers.delete(attribute);
  10945. }
  10946. }
  10947. function update(attribute, bufferType) {
  10948. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10949. var data = buffers.get(attribute);
  10950. if (data === undefined) {
  10951. buffers.set(attribute, createBuffer(attribute, bufferType));
  10952. } else if (data.version < attribute.version) {
  10953. updateBuffer(data.buffer, attribute, bufferType);
  10954. data.version = attribute.version;
  10955. }
  10956. }
  10957. return {
  10958. get: get,
  10959. remove: remove,
  10960. update: update
  10961. };
  10962. }
  10963. /**
  10964. * @author mrdoob / http://mrdoob.com/
  10965. * @author Mugen87 / https://github.com/Mugen87
  10966. */
  10967. // PlaneGeometry
  10968. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  10969. Geometry.call(this);
  10970. this.type = 'PlaneGeometry';
  10971. this.parameters = {
  10972. width: width,
  10973. height: height,
  10974. widthSegments: widthSegments,
  10975. heightSegments: heightSegments
  10976. };
  10977. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  10978. this.mergeVertices();
  10979. }
  10980. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  10981. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  10982. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  10983. BufferGeometry.call(this);
  10984. this.type = 'PlaneBufferGeometry';
  10985. this.parameters = {
  10986. width: width,
  10987. height: height,
  10988. widthSegments: widthSegments,
  10989. heightSegments: heightSegments
  10990. };
  10991. width = width || 1;
  10992. height = height || 1;
  10993. var width_half = width / 2;
  10994. var height_half = height / 2;
  10995. var gridX = Math.floor(widthSegments) || 1;
  10996. var gridY = Math.floor(heightSegments) || 1;
  10997. var gridX1 = gridX + 1;
  10998. var gridY1 = gridY + 1;
  10999. var segment_width = width / gridX;
  11000. var segment_height = height / gridY;
  11001. var ix, iy; // buffers
  11002. var indices = [];
  11003. var vertices = [];
  11004. var normals = [];
  11005. var uvs = []; // generate vertices, normals and uvs
  11006. for (iy = 0; iy < gridY1; iy++) {
  11007. var y = iy * segment_height - height_half;
  11008. for (ix = 0; ix < gridX1; ix++) {
  11009. var x = ix * segment_width - width_half;
  11010. vertices.push(x, -y, 0);
  11011. normals.push(0, 0, 1);
  11012. uvs.push(ix / gridX);
  11013. uvs.push(1 - iy / gridY);
  11014. }
  11015. } // indices
  11016. for (iy = 0; iy < gridY; iy++) {
  11017. for (ix = 0; ix < gridX; ix++) {
  11018. var a = ix + gridX1 * iy;
  11019. var b = ix + gridX1 * (iy + 1);
  11020. var c = ix + 1 + gridX1 * (iy + 1);
  11021. var d = ix + 1 + gridX1 * iy; // faces
  11022. indices.push(a, b, d);
  11023. indices.push(b, c, d);
  11024. }
  11025. } // build geometry
  11026. this.setIndex(indices);
  11027. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  11028. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  11029. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  11030. }
  11031. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  11032. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11033. /**
  11034. * @author mrdoob / http://mrdoob.com/
  11035. */
  11036. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  11037. var clearColor = new Color(0x000000);
  11038. var clearAlpha = 0;
  11039. var planeMesh;
  11040. var boxMesh; // Store the current background texture and its `version`
  11041. // so we can recompile the material accordingly.
  11042. var currentBackground = null;
  11043. var currentBackgroundVersion = 0;
  11044. function render(renderList, scene, camera, forceClear) {
  11045. var background = scene.background; // Ignore background in AR
  11046. // TODO: Reconsider this.
  11047. var vr = renderer.vr;
  11048. var session = vr.getSession && vr.getSession();
  11049. if (session && session.environmentBlendMode === 'additive') {
  11050. background = null;
  11051. }
  11052. if (background === null) {
  11053. setClear(clearColor, clearAlpha);
  11054. currentBackground = null;
  11055. currentBackgroundVersion = 0;
  11056. } else if (background && background.isColor) {
  11057. setClear(background, 1);
  11058. forceClear = true;
  11059. currentBackground = null;
  11060. currentBackgroundVersion = 0;
  11061. }
  11062. if (renderer.autoClear || forceClear) {
  11063. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  11064. }
  11065. if (background && (background.isCubeTexture || background.isWebGLRenderTargetCube)) {
  11066. if (boxMesh === undefined) {
  11067. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  11068. type: 'BackgroundCubeMaterial',
  11069. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  11070. vertexShader: ShaderLib.cube.vertexShader,
  11071. fragmentShader: ShaderLib.cube.fragmentShader,
  11072. side: BackSide,
  11073. depthTest: false,
  11074. depthWrite: false,
  11075. fog: false
  11076. }));
  11077. boxMesh.geometry.removeAttribute('normal');
  11078. boxMesh.geometry.removeAttribute('uv');
  11079. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  11080. this.matrixWorld.copyPosition(camera.matrixWorld);
  11081. }; // enable code injection for non-built-in material
  11082. Object.defineProperty(boxMesh.material, 'map', {
  11083. get: function () {
  11084. return this.uniforms.tCube.value;
  11085. }
  11086. });
  11087. objects.update(boxMesh);
  11088. }
  11089. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  11090. boxMesh.material.uniforms.tCube.value = texture;
  11091. boxMesh.material.uniforms.tFlip.value = background.isWebGLRenderTargetCube ? 1 : -1;
  11092. if (currentBackground !== background || currentBackgroundVersion !== texture.version) {
  11093. boxMesh.material.needsUpdate = true;
  11094. currentBackground = background;
  11095. currentBackgroundVersion = texture.version;
  11096. } // push to the pre-sorted opaque render list
  11097. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  11098. } else if (background && background.isTexture) {
  11099. if (planeMesh === undefined) {
  11100. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  11101. type: 'BackgroundMaterial',
  11102. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  11103. vertexShader: ShaderLib.background.vertexShader,
  11104. fragmentShader: ShaderLib.background.fragmentShader,
  11105. side: FrontSide,
  11106. depthTest: false,
  11107. depthWrite: false,
  11108. fog: false
  11109. }));
  11110. planeMesh.geometry.removeAttribute('normal'); // enable code injection for non-built-in material
  11111. Object.defineProperty(planeMesh.material, 'map', {
  11112. get: function () {
  11113. return this.uniforms.t2D.value;
  11114. }
  11115. });
  11116. objects.update(planeMesh);
  11117. }
  11118. planeMesh.material.uniforms.t2D.value = background;
  11119. if (background.matrixAutoUpdate === true) {
  11120. background.updateMatrix();
  11121. }
  11122. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  11123. if (currentBackground !== background || currentBackgroundVersion !== background.version) {
  11124. planeMesh.material.needsUpdate = true;
  11125. currentBackground = background;
  11126. currentBackgroundVersion = background.version;
  11127. } // push to the pre-sorted opaque render list
  11128. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  11129. }
  11130. }
  11131. function setClear(color, alpha) {
  11132. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  11133. }
  11134. return {
  11135. getClearColor: function () {
  11136. return clearColor;
  11137. },
  11138. setClearColor: function (color, alpha) {
  11139. clearColor.set(color);
  11140. clearAlpha = alpha !== undefined ? alpha : 1;
  11141. setClear(clearColor, clearAlpha);
  11142. },
  11143. getClearAlpha: function () {
  11144. return clearAlpha;
  11145. },
  11146. setClearAlpha: function (alpha) {
  11147. clearAlpha = alpha;
  11148. setClear(clearColor, clearAlpha);
  11149. },
  11150. render: render
  11151. };
  11152. }
  11153. /**
  11154. * @author mrdoob / http://mrdoob.com/
  11155. */
  11156. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  11157. var mode;
  11158. function setMode(value) {
  11159. mode = value;
  11160. }
  11161. function render(start, count) {
  11162. gl.drawArrays(mode, start, count);
  11163. info.update(count, mode);
  11164. }
  11165. function renderInstances(geometry, start, count, primcount) {
  11166. if (primcount === 0) return;
  11167. var extension, methodName;
  11168. if (capabilities.isWebGL2) {
  11169. extension = gl;
  11170. methodName = 'drawArraysInstanced';
  11171. } else {
  11172. extension = extensions.get('ANGLE_instanced_arrays');
  11173. methodName = 'drawArraysInstancedANGLE';
  11174. if (extension === null) {
  11175. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11176. return;
  11177. }
  11178. }
  11179. extension[methodName](mode, start, count, primcount);
  11180. info.update(count, mode, primcount);
  11181. } //
  11182. this.setMode = setMode;
  11183. this.render = render;
  11184. this.renderInstances = renderInstances;
  11185. }
  11186. /**
  11187. * @author mrdoob / http://mrdoob.com/
  11188. */
  11189. function WebGLCapabilities(gl, extensions, parameters) {
  11190. var maxAnisotropy;
  11191. function getMaxAnisotropy() {
  11192. if (maxAnisotropy !== undefined) return maxAnisotropy;
  11193. var extension = extensions.get('EXT_texture_filter_anisotropic');
  11194. if (extension !== null) {
  11195. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  11196. } else {
  11197. maxAnisotropy = 0;
  11198. }
  11199. return maxAnisotropy;
  11200. }
  11201. function getMaxPrecision(precision) {
  11202. if (precision === 'highp') {
  11203. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  11204. return 'highp';
  11205. }
  11206. precision = 'mediump';
  11207. }
  11208. if (precision === 'mediump') {
  11209. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  11210. return 'mediump';
  11211. }
  11212. }
  11213. return 'lowp';
  11214. }
  11215. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  11216. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11217. var maxPrecision = getMaxPrecision(precision);
  11218. if (maxPrecision !== precision) {
  11219. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  11220. precision = maxPrecision;
  11221. }
  11222. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  11223. var maxTextures = gl.getParameter(34930);
  11224. var maxVertexTextures = gl.getParameter(35660);
  11225. var maxTextureSize = gl.getParameter(3379);
  11226. var maxCubemapSize = gl.getParameter(34076);
  11227. var maxAttributes = gl.getParameter(34921);
  11228. var maxVertexUniforms = gl.getParameter(36347);
  11229. var maxVaryings = gl.getParameter(36348);
  11230. var maxFragmentUniforms = gl.getParameter(36349);
  11231. var vertexTextures = maxVertexTextures > 0;
  11232. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  11233. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11234. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  11235. return {
  11236. isWebGL2: isWebGL2,
  11237. getMaxAnisotropy: getMaxAnisotropy,
  11238. getMaxPrecision: getMaxPrecision,
  11239. precision: precision,
  11240. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11241. maxTextures: maxTextures,
  11242. maxVertexTextures: maxVertexTextures,
  11243. maxTextureSize: maxTextureSize,
  11244. maxCubemapSize: maxCubemapSize,
  11245. maxAttributes: maxAttributes,
  11246. maxVertexUniforms: maxVertexUniforms,
  11247. maxVaryings: maxVaryings,
  11248. maxFragmentUniforms: maxFragmentUniforms,
  11249. vertexTextures: vertexTextures,
  11250. floatFragmentTextures: floatFragmentTextures,
  11251. floatVertexTextures: floatVertexTextures,
  11252. maxSamples: maxSamples
  11253. };
  11254. }
  11255. /**
  11256. * @author tschw
  11257. */
  11258. function WebGLClipping() {
  11259. var scope = this,
  11260. globalState = null,
  11261. numGlobalPlanes = 0,
  11262. localClippingEnabled = false,
  11263. renderingShadows = false,
  11264. plane = new Plane(),
  11265. viewNormalMatrix = new Matrix3(),
  11266. uniform = {
  11267. value: null,
  11268. needsUpdate: false
  11269. };
  11270. this.uniform = uniform;
  11271. this.numPlanes = 0;
  11272. this.numIntersection = 0;
  11273. this.init = function (planes, enableLocalClipping, camera) {
  11274. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  11275. // run another frame in order to reset the state:
  11276. numGlobalPlanes !== 0 || localClippingEnabled;
  11277. localClippingEnabled = enableLocalClipping;
  11278. globalState = projectPlanes(planes, camera, 0);
  11279. numGlobalPlanes = planes.length;
  11280. return enabled;
  11281. };
  11282. this.beginShadows = function () {
  11283. renderingShadows = true;
  11284. projectPlanes(null);
  11285. };
  11286. this.endShadows = function () {
  11287. renderingShadows = false;
  11288. resetGlobalState();
  11289. };
  11290. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  11291. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  11292. // there's no local clipping
  11293. if (renderingShadows) {
  11294. // there's no global clipping
  11295. projectPlanes(null);
  11296. } else {
  11297. resetGlobalState();
  11298. }
  11299. } else {
  11300. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11301. lGlobal = nGlobal * 4,
  11302. dstArray = cache.clippingState || null;
  11303. uniform.value = dstArray; // ensure unique state
  11304. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  11305. for (var i = 0; i !== lGlobal; ++i) {
  11306. dstArray[i] = globalState[i];
  11307. }
  11308. cache.clippingState = dstArray;
  11309. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11310. this.numPlanes += nGlobal;
  11311. }
  11312. };
  11313. function resetGlobalState() {
  11314. if (uniform.value !== globalState) {
  11315. uniform.value = globalState;
  11316. uniform.needsUpdate = numGlobalPlanes > 0;
  11317. }
  11318. scope.numPlanes = numGlobalPlanes;
  11319. scope.numIntersection = 0;
  11320. }
  11321. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  11322. var nPlanes = planes !== null ? planes.length : 0,
  11323. dstArray = null;
  11324. if (nPlanes !== 0) {
  11325. dstArray = uniform.value;
  11326. if (skipTransform !== true || dstArray === null) {
  11327. var flatSize = dstOffset + nPlanes * 4,
  11328. viewMatrix = camera.matrixWorldInverse;
  11329. viewNormalMatrix.getNormalMatrix(viewMatrix);
  11330. if (dstArray === null || dstArray.length < flatSize) {
  11331. dstArray = new Float32Array(flatSize);
  11332. }
  11333. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  11334. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  11335. plane.normal.toArray(dstArray, i4);
  11336. dstArray[i4 + 3] = plane.constant;
  11337. }
  11338. }
  11339. uniform.value = dstArray;
  11340. uniform.needsUpdate = true;
  11341. }
  11342. scope.numPlanes = nPlanes;
  11343. return dstArray;
  11344. }
  11345. }
  11346. /**
  11347. * @author mrdoob / http://mrdoob.com/
  11348. */
  11349. function WebGLExtensions(gl) {
  11350. var extensions = {};
  11351. return {
  11352. get: function (name) {
  11353. if (extensions[name] !== undefined) {
  11354. return extensions[name];
  11355. }
  11356. var extension;
  11357. switch (name) {
  11358. case 'WEBGL_depth_texture':
  11359. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  11360. break;
  11361. case 'EXT_texture_filter_anisotropic':
  11362. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  11363. break;
  11364. case 'WEBGL_compressed_texture_s3tc':
  11365. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11366. break;
  11367. case 'WEBGL_compressed_texture_pvrtc':
  11368. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11369. break;
  11370. default:
  11371. extension = gl.getExtension(name);
  11372. }
  11373. if (extension === null) {
  11374. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  11375. }
  11376. extensions[name] = extension;
  11377. return extension;
  11378. }
  11379. };
  11380. }
  11381. /**
  11382. * @author mrdoob / http://mrdoob.com/
  11383. */
  11384. function WebGLGeometries(gl, attributes, info) {
  11385. var geometries = new WeakMap();
  11386. var wireframeAttributes = new WeakMap();
  11387. function onGeometryDispose(event) {
  11388. var geometry = event.target;
  11389. var buffergeometry = geometries.get(geometry);
  11390. if (buffergeometry.index !== null) {
  11391. attributes.remove(buffergeometry.index);
  11392. }
  11393. for (var name in buffergeometry.attributes) {
  11394. attributes.remove(buffergeometry.attributes[name]);
  11395. }
  11396. geometry.removeEventListener('dispose', onGeometryDispose);
  11397. geometries.delete(geometry);
  11398. var attribute = wireframeAttributes.get(buffergeometry);
  11399. if (attribute) {
  11400. attributes.remove(attribute);
  11401. wireframeAttributes.delete(buffergeometry);
  11402. } //
  11403. info.memory.geometries--;
  11404. }
  11405. function get(object, geometry) {
  11406. var buffergeometry = geometries.get(geometry);
  11407. if (buffergeometry) return buffergeometry;
  11408. geometry.addEventListener('dispose', onGeometryDispose);
  11409. if (geometry.isBufferGeometry) {
  11410. buffergeometry = geometry;
  11411. } else if (geometry.isGeometry) {
  11412. if (geometry._bufferGeometry === undefined) {
  11413. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  11414. }
  11415. buffergeometry = geometry._bufferGeometry;
  11416. }
  11417. geometries.set(geometry, buffergeometry);
  11418. info.memory.geometries++;
  11419. return buffergeometry;
  11420. }
  11421. function update(geometry) {
  11422. var index = geometry.index;
  11423. var geometryAttributes = geometry.attributes;
  11424. if (index !== null) {
  11425. attributes.update(index, 34963);
  11426. }
  11427. for (var name in geometryAttributes) {
  11428. attributes.update(geometryAttributes[name], 34962);
  11429. } // morph targets
  11430. var morphAttributes = geometry.morphAttributes;
  11431. for (var name in morphAttributes) {
  11432. var array = morphAttributes[name];
  11433. for (var i = 0, l = array.length; i < l; i++) {
  11434. attributes.update(array[i], 34962);
  11435. }
  11436. }
  11437. }
  11438. function updateWireframeAttribute(geometry) {
  11439. var indices = [];
  11440. var geometryIndex = geometry.index;
  11441. var geometryPosition = geometry.attributes.position;
  11442. var version = 0;
  11443. if (geometryIndex !== null) {
  11444. var array = geometryIndex.array;
  11445. version = geometryIndex.version;
  11446. for (var i = 0, l = array.length; i < l; i += 3) {
  11447. var a = array[i + 0];
  11448. var b = array[i + 1];
  11449. var c = array[i + 2];
  11450. indices.push(a, b, b, c, c, a);
  11451. }
  11452. } else {
  11453. var array = geometryPosition.array;
  11454. version = geometryPosition.version;
  11455. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  11456. var a = i + 0;
  11457. var b = i + 1;
  11458. var c = i + 2;
  11459. indices.push(a, b, b, c, c, a);
  11460. }
  11461. }
  11462. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  11463. attribute.version = version;
  11464. attributes.update(attribute, 34963); //
  11465. var previousAttribute = wireframeAttributes.get(geometry);
  11466. if (previousAttribute) attributes.remove(previousAttribute); //
  11467. wireframeAttributes.set(geometry, attribute);
  11468. }
  11469. function getWireframeAttribute(geometry) {
  11470. var currentAttribute = wireframeAttributes.get(geometry);
  11471. if (currentAttribute) {
  11472. var geometryIndex = geometry.index;
  11473. if (geometryIndex !== null) {
  11474. // if the attribute is obsolete, create a new one
  11475. if (currentAttribute.version < geometryIndex.version) {
  11476. updateWireframeAttribute(geometry);
  11477. }
  11478. }
  11479. } else {
  11480. updateWireframeAttribute(geometry);
  11481. }
  11482. return wireframeAttributes.get(geometry);
  11483. }
  11484. return {
  11485. get: get,
  11486. update: update,
  11487. getWireframeAttribute: getWireframeAttribute
  11488. };
  11489. }
  11490. /**
  11491. * @author mrdoob / http://mrdoob.com/
  11492. */
  11493. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  11494. var mode;
  11495. function setMode(value) {
  11496. mode = value;
  11497. }
  11498. var type, bytesPerElement;
  11499. function setIndex(value) {
  11500. type = value.type;
  11501. bytesPerElement = value.bytesPerElement;
  11502. }
  11503. function render(start, count) {
  11504. gl.drawElements(mode, count, type, start * bytesPerElement);
  11505. info.update(count, mode);
  11506. }
  11507. function renderInstances(geometry, start, count, primcount) {
  11508. if (primcount === 0) return;
  11509. var extension, methodName;
  11510. if (capabilities.isWebGL2) {
  11511. extension = gl;
  11512. methodName = 'drawElementsInstanced';
  11513. } else {
  11514. extension = extensions.get('ANGLE_instanced_arrays');
  11515. methodName = 'drawElementsInstancedANGLE';
  11516. if (extension === null) {
  11517. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11518. return;
  11519. }
  11520. }
  11521. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  11522. info.update(count, mode, primcount);
  11523. } //
  11524. this.setMode = setMode;
  11525. this.setIndex = setIndex;
  11526. this.render = render;
  11527. this.renderInstances = renderInstances;
  11528. }
  11529. /**
  11530. * @author Mugen87 / https://github.com/Mugen87
  11531. */
  11532. function WebGLInfo(gl) {
  11533. var memory = {
  11534. geometries: 0,
  11535. textures: 0
  11536. };
  11537. var render = {
  11538. frame: 0,
  11539. calls: 0,
  11540. triangles: 0,
  11541. points: 0,
  11542. lines: 0
  11543. };
  11544. function update(count, mode, instanceCount) {
  11545. instanceCount = instanceCount || 1;
  11546. render.calls++;
  11547. switch (mode) {
  11548. case 4:
  11549. render.triangles += instanceCount * (count / 3);
  11550. break;
  11551. case 5:
  11552. case 6:
  11553. render.triangles += instanceCount * (count - 2);
  11554. break;
  11555. case 1:
  11556. render.lines += instanceCount * (count / 2);
  11557. break;
  11558. case 3:
  11559. render.lines += instanceCount * (count - 1);
  11560. break;
  11561. case 2:
  11562. render.lines += instanceCount * count;
  11563. break;
  11564. case 0:
  11565. render.points += instanceCount * count;
  11566. break;
  11567. default:
  11568. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  11569. break;
  11570. }
  11571. }
  11572. function reset() {
  11573. render.frame++;
  11574. render.calls = 0;
  11575. render.triangles = 0;
  11576. render.points = 0;
  11577. render.lines = 0;
  11578. }
  11579. return {
  11580. memory: memory,
  11581. render: render,
  11582. programs: null,
  11583. autoReset: true,
  11584. reset: reset,
  11585. update: update
  11586. };
  11587. }
  11588. /**
  11589. * @author mrdoob / http://mrdoob.com/
  11590. */
  11591. function absNumericalSort(a, b) {
  11592. return Math.abs(b[1]) - Math.abs(a[1]);
  11593. }
  11594. function WebGLMorphtargets(gl) {
  11595. var influencesList = {};
  11596. var morphInfluences = new Float32Array(8);
  11597. function update(object, geometry, material, program) {
  11598. var objectInfluences = object.morphTargetInfluences;
  11599. var length = objectInfluences.length;
  11600. var influences = influencesList[geometry.id];
  11601. if (influences === undefined) {
  11602. // initialise list
  11603. influences = [];
  11604. for (var i = 0; i < length; i++) {
  11605. influences[i] = [i, 0];
  11606. }
  11607. influencesList[geometry.id] = influences;
  11608. }
  11609. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  11610. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  11611. for (var i = 0; i < length; i++) {
  11612. var influence = influences[i];
  11613. if (influence[1] !== 0) {
  11614. if (morphTargets) geometry.removeAttribute('morphTarget' + i);
  11615. if (morphNormals) geometry.removeAttribute('morphNormal' + i);
  11616. }
  11617. } // Collect influences
  11618. for (var i = 0; i < length; i++) {
  11619. var influence = influences[i];
  11620. influence[0] = i;
  11621. influence[1] = objectInfluences[i];
  11622. }
  11623. influences.sort(absNumericalSort); // Add morphAttributes
  11624. for (var i = 0; i < 8; i++) {
  11625. var influence = influences[i];
  11626. if (influence) {
  11627. var index = influence[0];
  11628. var value = influence[1];
  11629. if (value) {
  11630. if (morphTargets) geometry.addAttribute('morphTarget' + i, morphTargets[index]);
  11631. if (morphNormals) geometry.addAttribute('morphNormal' + i, morphNormals[index]);
  11632. morphInfluences[i] = value;
  11633. continue;
  11634. }
  11635. }
  11636. morphInfluences[i] = 0;
  11637. }
  11638. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  11639. }
  11640. return {
  11641. update: update
  11642. };
  11643. }
  11644. /**
  11645. * @author mrdoob / http://mrdoob.com/
  11646. */
  11647. function WebGLObjects(gl, geometries, attributes, info) {
  11648. var updateList = {};
  11649. function update(object) {
  11650. var frame = info.render.frame;
  11651. var geometry = object.geometry;
  11652. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  11653. if (updateList[buffergeometry.id] !== frame) {
  11654. if (geometry.isGeometry) {
  11655. buffergeometry.updateFromObject(object);
  11656. }
  11657. geometries.update(buffergeometry);
  11658. updateList[buffergeometry.id] = frame;
  11659. }
  11660. if (object.isInstancedMesh) {
  11661. attributes.update(object.instanceMatrix, 34962);
  11662. }
  11663. return buffergeometry;
  11664. }
  11665. function dispose() {
  11666. updateList = {};
  11667. }
  11668. return {
  11669. update: update,
  11670. dispose: dispose
  11671. };
  11672. }
  11673. /**
  11674. * @author mrdoob / http://mrdoob.com/
  11675. */
  11676. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  11677. images = images !== undefined ? images : [];
  11678. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  11679. format = format !== undefined ? format : RGBFormat;
  11680. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  11681. this.flipY = false;
  11682. }
  11683. CubeTexture.prototype = Object.create(Texture.prototype);
  11684. CubeTexture.prototype.constructor = CubeTexture;
  11685. CubeTexture.prototype.isCubeTexture = true;
  11686. Object.defineProperty(CubeTexture.prototype, 'images', {
  11687. get: function () {
  11688. return this.image;
  11689. },
  11690. set: function (value) {
  11691. this.image = value;
  11692. }
  11693. });
  11694. /**
  11695. * @author Takahiro https://github.com/takahirox
  11696. */
  11697. function DataTexture2DArray(data, width, height, depth) {
  11698. Texture.call(this, null);
  11699. this.image = {
  11700. data: data || null,
  11701. width: width || 1,
  11702. height: height || 1,
  11703. depth: depth || 1
  11704. };
  11705. this.magFilter = NearestFilter;
  11706. this.minFilter = NearestFilter;
  11707. this.wrapR = ClampToEdgeWrapping;
  11708. this.generateMipmaps = false;
  11709. this.flipY = false;
  11710. this.needsUpdate = true;
  11711. }
  11712. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  11713. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  11714. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  11715. /**
  11716. * @author Artur Trzesiok
  11717. */
  11718. function DataTexture3D(data, width, height, depth) {
  11719. // We're going to add .setXXX() methods for setting properties later.
  11720. // Users can still set in DataTexture3D directly.
  11721. //
  11722. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  11723. // texture.anisotropy = 16;
  11724. //
  11725. // See #14839
  11726. Texture.call(this, null);
  11727. this.image = {
  11728. data: data || null,
  11729. width: width || 1,
  11730. height: height || 1,
  11731. depth: depth || 1
  11732. };
  11733. this.magFilter = NearestFilter;
  11734. this.minFilter = NearestFilter;
  11735. this.wrapR = ClampToEdgeWrapping;
  11736. this.generateMipmaps = false;
  11737. this.flipY = false;
  11738. this.needsUpdate = true;
  11739. }
  11740. DataTexture3D.prototype = Object.create(Texture.prototype);
  11741. DataTexture3D.prototype.constructor = DataTexture3D;
  11742. DataTexture3D.prototype.isDataTexture3D = true;
  11743. /**
  11744. * @author tschw
  11745. * @author Mugen87 / https://github.com/Mugen87
  11746. * @author mrdoob / http://mrdoob.com/
  11747. *
  11748. * Uniforms of a program.
  11749. * Those form a tree structure with a special top-level container for the root,
  11750. * which you get by calling 'new WebGLUniforms( gl, program )'.
  11751. *
  11752. *
  11753. * Properties of inner nodes including the top-level container:
  11754. *
  11755. * .seq - array of nested uniforms
  11756. * .map - nested uniforms by name
  11757. *
  11758. *
  11759. * Methods of all nodes except the top-level container:
  11760. *
  11761. * .setValue( gl, value, [textures] )
  11762. *
  11763. * uploads a uniform value(s)
  11764. * the 'textures' parameter is needed for sampler uniforms
  11765. *
  11766. *
  11767. * Static methods of the top-level container (textures factorizations):
  11768. *
  11769. * .upload( gl, seq, values, textures )
  11770. *
  11771. * sets uniforms in 'seq' to 'values[id].value'
  11772. *
  11773. * .seqWithValue( seq, values ) : filteredSeq
  11774. *
  11775. * filters 'seq' entries with corresponding entry in values
  11776. *
  11777. *
  11778. * Methods of the top-level container (textures factorizations):
  11779. *
  11780. * .setValue( gl, name, value, textures )
  11781. *
  11782. * sets uniform with name 'name' to 'value'
  11783. *
  11784. * .setOptional( gl, obj, prop )
  11785. *
  11786. * like .set for an optional property of the object
  11787. *
  11788. */
  11789. var emptyTexture = new Texture();
  11790. var emptyTexture2dArray = new DataTexture2DArray();
  11791. var emptyTexture3d = new DataTexture3D();
  11792. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  11793. // Array Caches (provide typed arrays for temporary by size)
  11794. var arrayCacheF32 = [];
  11795. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  11796. var mat4array = new Float32Array(16);
  11797. var mat3array = new Float32Array(9);
  11798. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  11799. function flatten(array, nBlocks, blockSize) {
  11800. var firstElem = array[0];
  11801. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  11802. // see http://jacksondunstan.com/articles/983
  11803. var n = nBlocks * blockSize,
  11804. r = arrayCacheF32[n];
  11805. if (r === undefined) {
  11806. r = new Float32Array(n);
  11807. arrayCacheF32[n] = r;
  11808. }
  11809. if (nBlocks !== 0) {
  11810. firstElem.toArray(r, 0);
  11811. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  11812. offset += blockSize;
  11813. array[i].toArray(r, offset);
  11814. }
  11815. }
  11816. return r;
  11817. }
  11818. function arraysEqual(a, b) {
  11819. if (a.length !== b.length) return false;
  11820. for (var i = 0, l = a.length; i < l; i++) {
  11821. if (a[i] !== b[i]) return false;
  11822. }
  11823. return true;
  11824. }
  11825. function copyArray(a, b) {
  11826. for (var i = 0, l = b.length; i < l; i++) {
  11827. a[i] = b[i];
  11828. }
  11829. } // Texture unit allocation
  11830. function allocTexUnits(textures, n) {
  11831. var r = arrayCacheI32[n];
  11832. if (r === undefined) {
  11833. r = new Int32Array(n);
  11834. arrayCacheI32[n] = r;
  11835. }
  11836. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  11837. return r;
  11838. } // --- Setters ---
  11839. // Note: Defining these methods externally, because they come in a bunch
  11840. // and this way their names minify.
  11841. // Single scalar
  11842. function setValueV1f(gl, v) {
  11843. var cache = this.cache;
  11844. if (cache[0] === v) return;
  11845. gl.uniform1f(this.addr, v);
  11846. cache[0] = v;
  11847. } // Single float vector (from flat array or THREE.VectorN)
  11848. function setValueV2f(gl, v) {
  11849. var cache = this.cache;
  11850. if (v.x !== undefined) {
  11851. if (cache[0] !== v.x || cache[1] !== v.y) {
  11852. gl.uniform2f(this.addr, v.x, v.y);
  11853. cache[0] = v.x;
  11854. cache[1] = v.y;
  11855. }
  11856. } else {
  11857. if (arraysEqual(cache, v)) return;
  11858. gl.uniform2fv(this.addr, v);
  11859. copyArray(cache, v);
  11860. }
  11861. }
  11862. function setValueV3f(gl, v) {
  11863. var cache = this.cache;
  11864. if (v.x !== undefined) {
  11865. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  11866. gl.uniform3f(this.addr, v.x, v.y, v.z);
  11867. cache[0] = v.x;
  11868. cache[1] = v.y;
  11869. cache[2] = v.z;
  11870. }
  11871. } else if (v.r !== undefined) {
  11872. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  11873. gl.uniform3f(this.addr, v.r, v.g, v.b);
  11874. cache[0] = v.r;
  11875. cache[1] = v.g;
  11876. cache[2] = v.b;
  11877. }
  11878. } else {
  11879. if (arraysEqual(cache, v)) return;
  11880. gl.uniform3fv(this.addr, v);
  11881. copyArray(cache, v);
  11882. }
  11883. }
  11884. function setValueV4f(gl, v) {
  11885. var cache = this.cache;
  11886. if (v.x !== undefined) {
  11887. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  11888. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  11889. cache[0] = v.x;
  11890. cache[1] = v.y;
  11891. cache[2] = v.z;
  11892. cache[3] = v.w;
  11893. }
  11894. } else {
  11895. if (arraysEqual(cache, v)) return;
  11896. gl.uniform4fv(this.addr, v);
  11897. copyArray(cache, v);
  11898. }
  11899. } // Single matrix (from flat array or MatrixN)
  11900. function setValueM2(gl, v) {
  11901. var cache = this.cache;
  11902. var elements = v.elements;
  11903. if (elements === undefined) {
  11904. if (arraysEqual(cache, v)) return;
  11905. gl.uniformMatrix2fv(this.addr, false, v);
  11906. copyArray(cache, v);
  11907. } else {
  11908. if (arraysEqual(cache, elements)) return;
  11909. mat2array.set(elements);
  11910. gl.uniformMatrix2fv(this.addr, false, mat2array);
  11911. copyArray(cache, elements);
  11912. }
  11913. }
  11914. function setValueM3(gl, v) {
  11915. var cache = this.cache;
  11916. var elements = v.elements;
  11917. if (elements === undefined) {
  11918. if (arraysEqual(cache, v)) return;
  11919. gl.uniformMatrix3fv(this.addr, false, v);
  11920. copyArray(cache, v);
  11921. } else {
  11922. if (arraysEqual(cache, elements)) return;
  11923. mat3array.set(elements);
  11924. gl.uniformMatrix3fv(this.addr, false, mat3array);
  11925. copyArray(cache, elements);
  11926. }
  11927. }
  11928. function setValueM4(gl, v) {
  11929. var cache = this.cache;
  11930. var elements = v.elements;
  11931. if (elements === undefined) {
  11932. if (arraysEqual(cache, v)) return;
  11933. gl.uniformMatrix4fv(this.addr, false, v);
  11934. copyArray(cache, v);
  11935. } else {
  11936. if (arraysEqual(cache, elements)) return;
  11937. mat4array.set(elements);
  11938. gl.uniformMatrix4fv(this.addr, false, mat4array);
  11939. copyArray(cache, elements);
  11940. }
  11941. } // Single texture (2D / Cube)
  11942. function setValueT1(gl, v, textures) {
  11943. var cache = this.cache;
  11944. var unit = textures.allocateTextureUnit();
  11945. if (cache[0] !== unit) {
  11946. gl.uniform1i(this.addr, unit);
  11947. cache[0] = unit;
  11948. }
  11949. textures.safeSetTexture2D(v || emptyTexture, unit);
  11950. }
  11951. function setValueT2DArray1(gl, v, textures) {
  11952. var cache = this.cache;
  11953. var unit = textures.allocateTextureUnit();
  11954. if (cache[0] !== unit) {
  11955. gl.uniform1i(this.addr, unit);
  11956. cache[0] = unit;
  11957. }
  11958. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  11959. }
  11960. function setValueT3D1(gl, v, textures) {
  11961. var cache = this.cache;
  11962. var unit = textures.allocateTextureUnit();
  11963. if (cache[0] !== unit) {
  11964. gl.uniform1i(this.addr, unit);
  11965. cache[0] = unit;
  11966. }
  11967. textures.setTexture3D(v || emptyTexture3d, unit);
  11968. }
  11969. function setValueT6(gl, v, textures) {
  11970. var cache = this.cache;
  11971. var unit = textures.allocateTextureUnit();
  11972. if (cache[0] !== unit) {
  11973. gl.uniform1i(this.addr, unit);
  11974. cache[0] = unit;
  11975. }
  11976. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  11977. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11978. function setValueV1i(gl, v) {
  11979. var cache = this.cache;
  11980. if (cache[0] === v) return;
  11981. gl.uniform1i(this.addr, v);
  11982. cache[0] = v;
  11983. }
  11984. function setValueV2i(gl, v) {
  11985. var cache = this.cache;
  11986. if (arraysEqual(cache, v)) return;
  11987. gl.uniform2iv(this.addr, v);
  11988. copyArray(cache, v);
  11989. }
  11990. function setValueV3i(gl, v) {
  11991. var cache = this.cache;
  11992. if (arraysEqual(cache, v)) return;
  11993. gl.uniform3iv(this.addr, v);
  11994. copyArray(cache, v);
  11995. }
  11996. function setValueV4i(gl, v) {
  11997. var cache = this.cache;
  11998. if (arraysEqual(cache, v)) return;
  11999. gl.uniform4iv(this.addr, v);
  12000. copyArray(cache, v);
  12001. } // Helper to pick the right setter for the singular case
  12002. function getSingularSetter(type) {
  12003. switch (type) {
  12004. case 0x1406:
  12005. return setValueV1f;
  12006. // FLOAT
  12007. case 0x8b50:
  12008. return setValueV2f;
  12009. // _VEC2
  12010. case 0x8b51:
  12011. return setValueV3f;
  12012. // _VEC3
  12013. case 0x8b52:
  12014. return setValueV4f;
  12015. // _VEC4
  12016. case 0x8b5a:
  12017. return setValueM2;
  12018. // _MAT2
  12019. case 0x8b5b:
  12020. return setValueM3;
  12021. // _MAT3
  12022. case 0x8b5c:
  12023. return setValueM4;
  12024. // _MAT4
  12025. case 0x8b5e:
  12026. case 0x8d66:
  12027. return setValueT1;
  12028. // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  12029. case 0x8b5f:
  12030. return setValueT3D1;
  12031. // SAMPLER_3D
  12032. case 0x8b60:
  12033. return setValueT6;
  12034. // SAMPLER_CUBE
  12035. case 0x8DC1:
  12036. return setValueT2DArray1;
  12037. // SAMPLER_2D_ARRAY
  12038. case 0x1404:
  12039. case 0x8b56:
  12040. return setValueV1i;
  12041. // INT, BOOL
  12042. case 0x8b53:
  12043. case 0x8b57:
  12044. return setValueV2i;
  12045. // _VEC2
  12046. case 0x8b54:
  12047. case 0x8b58:
  12048. return setValueV3i;
  12049. // _VEC3
  12050. case 0x8b55:
  12051. case 0x8b59:
  12052. return setValueV4i;
  12053. // _VEC4
  12054. }
  12055. } // Array of scalars
  12056. function setValueV1fArray(gl, v) {
  12057. gl.uniform1fv(this.addr, v);
  12058. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  12059. function setValueV1iArray(gl, v) {
  12060. gl.uniform1iv(this.addr, v);
  12061. }
  12062. function setValueV2iArray(gl, v) {
  12063. gl.uniform2iv(this.addr, v);
  12064. }
  12065. function setValueV3iArray(gl, v) {
  12066. gl.uniform3iv(this.addr, v);
  12067. }
  12068. function setValueV4iArray(gl, v) {
  12069. gl.uniform4iv(this.addr, v);
  12070. } // Array of vectors (flat or from THREE classes)
  12071. function setValueV2fArray(gl, v) {
  12072. var data = flatten(v, this.size, 2);
  12073. gl.uniform2fv(this.addr, data);
  12074. }
  12075. function setValueV3fArray(gl, v) {
  12076. var data = flatten(v, this.size, 3);
  12077. gl.uniform3fv(this.addr, data);
  12078. }
  12079. function setValueV4fArray(gl, v) {
  12080. var data = flatten(v, this.size, 4);
  12081. gl.uniform4fv(this.addr, data);
  12082. } // Array of matrices (flat or from THREE clases)
  12083. function setValueM2Array(gl, v) {
  12084. var data = flatten(v, this.size, 4);
  12085. gl.uniformMatrix2fv(this.addr, false, data);
  12086. }
  12087. function setValueM3Array(gl, v) {
  12088. var data = flatten(v, this.size, 9);
  12089. gl.uniformMatrix3fv(this.addr, false, data);
  12090. }
  12091. function setValueM4Array(gl, v) {
  12092. var data = flatten(v, this.size, 16);
  12093. gl.uniformMatrix4fv(this.addr, false, data);
  12094. } // Array of textures (2D / Cube)
  12095. function setValueT1Array(gl, v, textures) {
  12096. var n = v.length;
  12097. var units = allocTexUnits(textures, n);
  12098. gl.uniform1iv(this.addr, units);
  12099. for (var i = 0; i !== n; ++i) {
  12100. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  12101. }
  12102. }
  12103. function setValueT6Array(gl, v, textures) {
  12104. var n = v.length;
  12105. var units = allocTexUnits(textures, n);
  12106. gl.uniform1iv(this.addr, units);
  12107. for (var i = 0; i !== n; ++i) {
  12108. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  12109. }
  12110. } // Helper to pick the right setter for a pure (bottom-level) array
  12111. function getPureArraySetter(type) {
  12112. switch (type) {
  12113. case 0x1406:
  12114. return setValueV1fArray;
  12115. // FLOAT
  12116. case 0x8b50:
  12117. return setValueV2fArray;
  12118. // _VEC2
  12119. case 0x8b51:
  12120. return setValueV3fArray;
  12121. // _VEC3
  12122. case 0x8b52:
  12123. return setValueV4fArray;
  12124. // _VEC4
  12125. case 0x8b5a:
  12126. return setValueM2Array;
  12127. // _MAT2
  12128. case 0x8b5b:
  12129. return setValueM3Array;
  12130. // _MAT3
  12131. case 0x8b5c:
  12132. return setValueM4Array;
  12133. // _MAT4
  12134. case 0x8b5e:
  12135. return setValueT1Array;
  12136. // SAMPLER_2D
  12137. case 0x8b60:
  12138. return setValueT6Array;
  12139. // SAMPLER_CUBE
  12140. case 0x1404:
  12141. case 0x8b56:
  12142. return setValueV1iArray;
  12143. // INT, BOOL
  12144. case 0x8b53:
  12145. case 0x8b57:
  12146. return setValueV2iArray;
  12147. // _VEC2
  12148. case 0x8b54:
  12149. case 0x8b58:
  12150. return setValueV3iArray;
  12151. // _VEC3
  12152. case 0x8b55:
  12153. case 0x8b59:
  12154. return setValueV4iArray;
  12155. // _VEC4
  12156. }
  12157. } // --- Uniform Classes ---
  12158. function SingleUniform(id, activeInfo, addr) {
  12159. this.id = id;
  12160. this.addr = addr;
  12161. this.cache = [];
  12162. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12163. }
  12164. function PureArrayUniform(id, activeInfo, addr) {
  12165. this.id = id;
  12166. this.addr = addr;
  12167. this.cache = [];
  12168. this.size = activeInfo.size;
  12169. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12170. }
  12171. PureArrayUniform.prototype.updateCache = function (data) {
  12172. var cache = this.cache;
  12173. if (data instanceof Float32Array && cache.length !== data.length) {
  12174. this.cache = new Float32Array(data.length);
  12175. }
  12176. copyArray(cache, data);
  12177. };
  12178. function StructuredUniform(id) {
  12179. this.id = id;
  12180. this.seq = [];
  12181. this.map = {};
  12182. }
  12183. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  12184. var seq = this.seq;
  12185. for (var i = 0, n = seq.length; i !== n; ++i) {
  12186. var u = seq[i];
  12187. u.setValue(gl, value[u.id], textures);
  12188. }
  12189. }; // --- Top-level ---
  12190. // Parser - builds up the property tree from the path strings
  12191. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  12192. // - the identifier (member name or array index)
  12193. // - followed by an optional right bracket (found when array index)
  12194. // - followed by an optional left bracket or dot (type of subscript)
  12195. //
  12196. // Note: These portions can be read in a non-overlapping fashion and
  12197. // allow straightforward parsing of the hierarchy that WebGL encodes
  12198. // in the uniform names.
  12199. function addUniform(container, uniformObject) {
  12200. container.seq.push(uniformObject);
  12201. container.map[uniformObject.id] = uniformObject;
  12202. }
  12203. function parseUniform(activeInfo, addr, container) {
  12204. var path = activeInfo.name,
  12205. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  12206. RePathPart.lastIndex = 0;
  12207. while (true) {
  12208. var match = RePathPart.exec(path),
  12209. matchEnd = RePathPart.lastIndex,
  12210. id = match[1],
  12211. idIsIndex = match[2] === ']',
  12212. subscript = match[3];
  12213. if (idIsIndex) id = id | 0; // convert to integer
  12214. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  12215. // bare name or "pure" bottom-level array "[0]" suffix
  12216. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  12217. break;
  12218. } else {
  12219. // step into inner node / create it in case it doesn't exist
  12220. var map = container.map,
  12221. next = map[id];
  12222. if (next === undefined) {
  12223. next = new StructuredUniform(id);
  12224. addUniform(container, next);
  12225. }
  12226. container = next;
  12227. }
  12228. }
  12229. } // Root Container
  12230. function WebGLUniforms(gl, program) {
  12231. this.seq = [];
  12232. this.map = {};
  12233. var n = gl.getProgramParameter(program, 35718);
  12234. for (var i = 0; i < n; ++i) {
  12235. var info = gl.getActiveUniform(program, i),
  12236. addr = gl.getUniformLocation(program, info.name);
  12237. parseUniform(info, addr, this);
  12238. }
  12239. }
  12240. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  12241. var u = this.map[name];
  12242. if (u !== undefined) u.setValue(gl, value, textures);
  12243. };
  12244. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  12245. var v = object[name];
  12246. if (v !== undefined) this.setValue(gl, name, v);
  12247. }; // Static interface
  12248. WebGLUniforms.upload = function (gl, seq, values, textures) {
  12249. for (var i = 0, n = seq.length; i !== n; ++i) {
  12250. var u = seq[i],
  12251. v = values[u.id];
  12252. if (v.needsUpdate !== false) {
  12253. // note: always updating when .needsUpdate is undefined
  12254. u.setValue(gl, v.value, textures);
  12255. }
  12256. }
  12257. };
  12258. WebGLUniforms.seqWithValue = function (seq, values) {
  12259. var r = [];
  12260. for (var i = 0, n = seq.length; i !== n; ++i) {
  12261. var u = seq[i];
  12262. if (u.id in values) r.push(u);
  12263. }
  12264. return r;
  12265. };
  12266. /**
  12267. * @author mrdoob / http://mrdoob.com/
  12268. */
  12269. function WebGLShader(gl, type, string) {
  12270. var shader = gl.createShader(type);
  12271. gl.shaderSource(shader, string);
  12272. gl.compileShader(shader);
  12273. return shader;
  12274. }
  12275. /**
  12276. * @author mrdoob / http://mrdoob.com/
  12277. */
  12278. var programIdCount = 0;
  12279. function addLineNumbers(string) {
  12280. var lines = string.split('\n');
  12281. for (var i = 0; i < lines.length; i++) {
  12282. lines[i] = i + 1 + ': ' + lines[i];
  12283. }
  12284. return lines.join('\n');
  12285. }
  12286. function getEncodingComponents(encoding) {
  12287. switch (encoding) {
  12288. case LinearEncoding:
  12289. return ['Linear', '( value )'];
  12290. case sRGBEncoding:
  12291. return ['sRGB', '( value )'];
  12292. case RGBEEncoding:
  12293. return ['RGBE', '( value )'];
  12294. case RGBM7Encoding:
  12295. return ['RGBM', '( value, 7.0 )'];
  12296. case RGBM16Encoding:
  12297. return ['RGBM', '( value, 16.0 )'];
  12298. case RGBDEncoding:
  12299. return ['RGBD', '( value, 256.0 )'];
  12300. case GammaEncoding:
  12301. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  12302. case LogLuvEncoding:
  12303. return ['LogLuv', '( value )'];
  12304. default:
  12305. throw new Error('unsupported encoding: ' + encoding);
  12306. }
  12307. }
  12308. function getShaderErrors(gl, shader, type) {
  12309. var status = gl.getShaderParameter(shader, 35713);
  12310. var log = gl.getShaderInfoLog(shader).trim();
  12311. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  12312. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  12313. var source = gl.getShaderSource(shader);
  12314. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  12315. }
  12316. function getTexelDecodingFunction(functionName, encoding) {
  12317. var components = getEncodingComponents(encoding);
  12318. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  12319. }
  12320. function getTexelEncodingFunction(functionName, encoding) {
  12321. var components = getEncodingComponents(encoding);
  12322. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  12323. }
  12324. function getToneMappingFunction(functionName, toneMapping) {
  12325. var toneMappingName;
  12326. switch (toneMapping) {
  12327. case LinearToneMapping:
  12328. toneMappingName = 'Linear';
  12329. break;
  12330. case ReinhardToneMapping:
  12331. toneMappingName = 'Reinhard';
  12332. break;
  12333. case Uncharted2ToneMapping:
  12334. toneMappingName = 'Uncharted2';
  12335. break;
  12336. case CineonToneMapping:
  12337. toneMappingName = 'OptimizedCineon';
  12338. break;
  12339. case ACESFilmicToneMapping:
  12340. toneMappingName = 'ACESFilmic';
  12341. break;
  12342. default:
  12343. throw new Error('unsupported toneMapping: ' + toneMapping);
  12344. }
  12345. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  12346. }
  12347. function generateExtensions(extensions, parameters, rendererExtensions) {
  12348. extensions = extensions || {};
  12349. var chunks = [extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading ? '#extension GL_OES_standard_derivatives : enable' : '', (extensions.fragDepth || parameters.logarithmicDepthBuffer) && rendererExtensions.get('EXT_frag_depth') ? '#extension GL_EXT_frag_depth : enable' : '', extensions.drawBuffers && rendererExtensions.get('WEBGL_draw_buffers') ? '#extension GL_EXT_draw_buffers : require' : '', (extensions.shaderTextureLOD || parameters.envMap) && rendererExtensions.get('EXT_shader_texture_lod') ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  12350. return chunks.filter(filterEmptyLine).join('\n');
  12351. }
  12352. function generateDefines(defines) {
  12353. var chunks = [];
  12354. for (var name in defines) {
  12355. var value = defines[name];
  12356. if (value === false) continue;
  12357. chunks.push('#define ' + name + ' ' + value);
  12358. }
  12359. return chunks.join('\n');
  12360. }
  12361. function fetchAttributeLocations(gl, program) {
  12362. var attributes = {};
  12363. var n = gl.getProgramParameter(program, 35721);
  12364. for (var i = 0; i < n; i++) {
  12365. var info = gl.getActiveAttrib(program, i);
  12366. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  12367. attributes[name] = gl.getAttribLocation(program, name);
  12368. }
  12369. return attributes;
  12370. }
  12371. function filterEmptyLine(string) {
  12372. return string !== '';
  12373. }
  12374. function replaceLightNums(string, parameters) {
  12375. 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);
  12376. }
  12377. function replaceClippingPlaneNums(string, parameters) {
  12378. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  12379. } // Resolve Includes
  12380. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  12381. function resolveIncludes(string) {
  12382. return string.replace(includePattern, includeReplacer);
  12383. }
  12384. function includeReplacer(match, include) {
  12385. var string = ShaderChunk[include];
  12386. if (string === undefined) {
  12387. throw new Error('Can not resolve #include <' + include + '>');
  12388. }
  12389. return resolveIncludes(string);
  12390. } // Unroll Loops
  12391. var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  12392. function unrollLoops(string) {
  12393. return string.replace(loopPattern, loopReplacer);
  12394. }
  12395. function loopReplacer(match, start, end, snippet) {
  12396. var string = '';
  12397. for (var i = parseInt(start); i < parseInt(end); i++) {
  12398. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  12399. }
  12400. return string;
  12401. } //
  12402. function generatePrecision(parameters) {
  12403. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  12404. if (parameters.precision === "highp") {
  12405. precisionstring += "\n#define HIGH_PRECISION";
  12406. } else if (parameters.precision === "mediump") {
  12407. precisionstring += "\n#define MEDIUM_PRECISION";
  12408. } else if (parameters.precision === "lowp") {
  12409. precisionstring += "\n#define LOW_PRECISION";
  12410. }
  12411. return precisionstring;
  12412. }
  12413. function generateShadowMapTypeDefine(parameters) {
  12414. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  12415. if (parameters.shadowMapType === PCFShadowMap) {
  12416. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  12417. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  12418. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  12419. } else if (parameters.shadowMapType === VSMShadowMap) {
  12420. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  12421. }
  12422. return shadowMapTypeDefine;
  12423. }
  12424. function generateEnvMapTypeDefine(parameters, material) {
  12425. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12426. if (parameters.envMap) {
  12427. switch (material.envMap.mapping) {
  12428. case CubeReflectionMapping:
  12429. case CubeRefractionMapping:
  12430. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12431. break;
  12432. case CubeUVReflectionMapping:
  12433. case CubeUVRefractionMapping:
  12434. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  12435. break;
  12436. case EquirectangularReflectionMapping:
  12437. case EquirectangularRefractionMapping:
  12438. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  12439. break;
  12440. case SphericalReflectionMapping:
  12441. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  12442. break;
  12443. }
  12444. }
  12445. return envMapTypeDefine;
  12446. }
  12447. function generateEnvMapModeDefine(parameters, material) {
  12448. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  12449. if (parameters.envMap) {
  12450. switch (material.envMap.mapping) {
  12451. case CubeRefractionMapping:
  12452. case EquirectangularRefractionMapping:
  12453. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  12454. break;
  12455. }
  12456. }
  12457. return envMapModeDefine;
  12458. }
  12459. function generateEnvMapBlendingDefine(parameters, material) {
  12460. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12461. if (parameters.envMap) {
  12462. switch (material.combine) {
  12463. case MultiplyOperation:
  12464. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12465. break;
  12466. case MixOperation:
  12467. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  12468. break;
  12469. case AddOperation:
  12470. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  12471. break;
  12472. }
  12473. }
  12474. return envMapBlendingDefine;
  12475. }
  12476. function WebGLProgram(renderer, extensions, code, material, shader, parameters) {
  12477. var gl = renderer.getContext();
  12478. var defines = material.defines;
  12479. var vertexShader = shader.vertexShader;
  12480. var fragmentShader = shader.fragmentShader;
  12481. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  12482. var envMapTypeDefine = generateEnvMapTypeDefine(parameters, material);
  12483. var envMapModeDefine = generateEnvMapModeDefine(parameters, material);
  12484. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters, material);
  12485. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  12486. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(material.extensions, parameters, extensions);
  12487. var customDefines = generateDefines(defines);
  12488. var program = gl.createProgram();
  12489. var prefixVertex, prefixFragment;
  12490. var renderTarget = renderer.getRenderTarget();
  12491. var numMultiviewViews = renderTarget && renderTarget.isWebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
  12492. if (material.isRawShaderMaterial) {
  12493. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  12494. if (prefixVertex.length > 0) {
  12495. prefixVertex += '\n';
  12496. }
  12497. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  12498. if (prefixFragment.length > 0) {
  12499. prefixFragment += '\n';
  12500. }
  12501. } else {
  12502. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && (parameters.isWebGL2 || extensions.get('EXT_frag_depth')) ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#ifdef USE_COLOR', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  12503. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  12504. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && (parameters.isWebGL2 || extensions.get('EXT_frag_depth')) ? '#define USE_LOGDEPTHBUF_EXT' : '', ((material.extensions ? material.extensions.shaderTextureLOD : false) || parameters.envMap) && (parameters.isWebGL2 || extensions.get('EXT_shader_texture_lod')) ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  12505. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ? ShaderChunk['encodings_pars_fragment'] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  12506. parameters.mapEncoding ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcapEncoding ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMapEncoding ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMapEncoding ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.outputEncoding ? getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding) : '', parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  12507. }
  12508. vertexShader = resolveIncludes(vertexShader);
  12509. vertexShader = replaceLightNums(vertexShader, parameters);
  12510. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  12511. fragmentShader = resolveIncludes(fragmentShader);
  12512. fragmentShader = replaceLightNums(fragmentShader, parameters);
  12513. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  12514. vertexShader = unrollLoops(vertexShader);
  12515. fragmentShader = unrollLoops(fragmentShader);
  12516. if (parameters.isWebGL2 && !material.isRawShaderMaterial) {
  12517. var isGLSL3ShaderMaterial = false;
  12518. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  12519. if (material.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  12520. isGLSL3ShaderMaterial = true;
  12521. vertexShader = vertexShader.replace(versionRegex, '');
  12522. fragmentShader = fragmentShader.replace(versionRegex, '');
  12523. } // GLSL 3.0 conversion
  12524. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  12525. prefixFragment = ['#version 300 es\n', '#define varying in', isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;', isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment; // Multiview
  12526. if (numMultiviewViews > 0) {
  12527. prefixVertex = prefixVertex.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', 'layout(num_views = ' + numMultiviewViews + ') in;', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  12528. prefixVertex = prefixVertex.replace(['uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;'].join('\n'), ['uniform mat4 modelViewMatrices[' + numMultiviewViews + '];', 'uniform mat4 projectionMatrices[' + numMultiviewViews + '];', 'uniform mat4 viewMatrices[' + numMultiviewViews + '];', 'uniform mat3 normalMatrices[' + numMultiviewViews + '];', '#define modelViewMatrix modelViewMatrices[VIEW_ID]', '#define projectionMatrix projectionMatrices[VIEW_ID]', '#define viewMatrix viewMatrices[VIEW_ID]', '#define normalMatrix normalMatrices[VIEW_ID]'].join('\n'));
  12529. prefixFragment = prefixFragment.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  12530. prefixFragment = prefixFragment.replace('uniform mat4 viewMatrix;', ['uniform mat4 viewMatrices[' + numMultiviewViews + '];', '#define viewMatrix viewMatrices[VIEW_ID]'].join('\n'));
  12531. }
  12532. }
  12533. var vertexGlsl = prefixVertex + vertexShader;
  12534. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  12535. // console.log( '*FRAGMENT*', fragmentGlsl );
  12536. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  12537. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  12538. gl.attachShader(program, glVertexShader);
  12539. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  12540. if (material.index0AttributeName !== undefined) {
  12541. gl.bindAttribLocation(program, 0, material.index0AttributeName);
  12542. } else if (parameters.morphTargets === true) {
  12543. // programs with morphTargets displace position out of attribute 0
  12544. gl.bindAttribLocation(program, 0, 'position');
  12545. }
  12546. gl.linkProgram(program); // check for link errors
  12547. if (renderer.debug.checkShaderErrors) {
  12548. var programLog = gl.getProgramInfoLog(program).trim();
  12549. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  12550. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  12551. var runnable = true;
  12552. var haveDiagnostics = true;
  12553. if (gl.getProgramParameter(program, 35714) === false) {
  12554. runnable = false;
  12555. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  12556. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  12557. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  12558. } else if (programLog !== '') {
  12559. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  12560. } else if (vertexLog === '' || fragmentLog === '') {
  12561. haveDiagnostics = false;
  12562. }
  12563. if (haveDiagnostics) {
  12564. this.diagnostics = {
  12565. runnable: runnable,
  12566. material: material,
  12567. programLog: programLog,
  12568. vertexShader: {
  12569. log: vertexLog,
  12570. prefix: prefixVertex
  12571. },
  12572. fragmentShader: {
  12573. log: fragmentLog,
  12574. prefix: prefixFragment
  12575. }
  12576. };
  12577. }
  12578. } // clean up
  12579. gl.deleteShader(glVertexShader);
  12580. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  12581. var cachedUniforms;
  12582. this.getUniforms = function () {
  12583. if (cachedUniforms === undefined) {
  12584. cachedUniforms = new WebGLUniforms(gl, program);
  12585. }
  12586. return cachedUniforms;
  12587. }; // set up caching for attribute locations
  12588. var cachedAttributes;
  12589. this.getAttributes = function () {
  12590. if (cachedAttributes === undefined) {
  12591. cachedAttributes = fetchAttributeLocations(gl, program);
  12592. }
  12593. return cachedAttributes;
  12594. }; // free resource
  12595. this.destroy = function () {
  12596. gl.deleteProgram(program);
  12597. this.program = undefined;
  12598. }; //
  12599. this.name = shader.name;
  12600. this.id = programIdCount++;
  12601. this.code = code;
  12602. this.usedTimes = 1;
  12603. this.program = program;
  12604. this.vertexShader = glVertexShader;
  12605. this.fragmentShader = glFragmentShader;
  12606. this.numMultiviewViews = numMultiviewViews;
  12607. return this;
  12608. }
  12609. /**
  12610. * @author mrdoob / http://mrdoob.com/
  12611. */
  12612. function WebGLPrograms(renderer, extensions, capabilities) {
  12613. var programs = [];
  12614. var shaderIDs = {
  12615. MeshDepthMaterial: 'depth',
  12616. MeshDistanceMaterial: 'distanceRGBA',
  12617. MeshNormalMaterial: 'normal',
  12618. MeshBasicMaterial: 'basic',
  12619. MeshLambertMaterial: 'lambert',
  12620. MeshPhongMaterial: 'phong',
  12621. MeshToonMaterial: 'phong',
  12622. MeshStandardMaterial: 'physical',
  12623. MeshPhysicalMaterial: 'physical',
  12624. MeshMatcapMaterial: 'matcap',
  12625. LineBasicMaterial: 'basic',
  12626. LineDashedMaterial: 'dashed',
  12627. PointsMaterial: 'points',
  12628. ShadowMaterial: 'shadow',
  12629. SpriteMaterial: 'sprite'
  12630. };
  12631. var parameterNames = ["precision", "supportsVertexTextures", "instancing", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen"];
  12632. function allocateBones(object) {
  12633. var skeleton = object.skeleton;
  12634. var bones = skeleton.bones;
  12635. if (capabilities.floatVertexTextures) {
  12636. return 1024;
  12637. } else {
  12638. // default for when object is not specified
  12639. // ( for example when prebuilding shader to be used with multiple objects )
  12640. //
  12641. // - leave some extra space for other uniforms
  12642. // - limit here is ANGLE's 254 max uniform vectors
  12643. // (up to 54 should be safe)
  12644. var nVertexUniforms = capabilities.maxVertexUniforms;
  12645. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  12646. var maxBones = Math.min(nVertexMatrices, bones.length);
  12647. if (maxBones < bones.length) {
  12648. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  12649. return 0;
  12650. }
  12651. return maxBones;
  12652. }
  12653. }
  12654. function getTextureEncodingFromMap(map, gammaOverrideLinear) {
  12655. var encoding;
  12656. if (!map) {
  12657. encoding = LinearEncoding;
  12658. } else if (map.isTexture) {
  12659. encoding = map.encoding;
  12660. } else if (map.isWebGLRenderTarget) {
  12661. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  12662. encoding = map.texture.encoding;
  12663. } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  12664. if (encoding === LinearEncoding && gammaOverrideLinear) {
  12665. encoding = GammaEncoding;
  12666. }
  12667. return encoding;
  12668. }
  12669. this.getParameters = function (material, lights, shadows, fog, nClipPlanes, nClipIntersection, object) {
  12670. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  12671. // (not to blow over maxLights budget)
  12672. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  12673. var precision = capabilities.precision;
  12674. if (material.precision !== null) {
  12675. precision = capabilities.getMaxPrecision(material.precision);
  12676. if (precision !== material.precision) {
  12677. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  12678. }
  12679. }
  12680. var currentRenderTarget = renderer.getRenderTarget();
  12681. var parameters = {
  12682. isWebGL2: capabilities.isWebGL2,
  12683. shaderID: shaderID,
  12684. precision: precision,
  12685. instancing: object.isInstancedMesh === true,
  12686. supportsVertexTextures: capabilities.vertexTextures,
  12687. outputEncoding: getTextureEncodingFromMap(!currentRenderTarget ? null : currentRenderTarget.texture, renderer.gammaOutput),
  12688. map: !!material.map,
  12689. mapEncoding: getTextureEncodingFromMap(material.map, renderer.gammaInput),
  12690. matcap: !!material.matcap,
  12691. matcapEncoding: getTextureEncodingFromMap(material.matcap, renderer.gammaInput),
  12692. envMap: !!material.envMap,
  12693. envMapMode: material.envMap && material.envMap.mapping,
  12694. envMapEncoding: getTextureEncodingFromMap(material.envMap, renderer.gammaInput),
  12695. envMapCubeUV: !!material.envMap && (material.envMap.mapping === CubeUVReflectionMapping || material.envMap.mapping === CubeUVRefractionMapping),
  12696. lightMap: !!material.lightMap,
  12697. aoMap: !!material.aoMap,
  12698. emissiveMap: !!material.emissiveMap,
  12699. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap, renderer.gammaInput),
  12700. bumpMap: !!material.bumpMap,
  12701. normalMap: !!material.normalMap,
  12702. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  12703. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  12704. clearcoatNormalMap: !!material.clearcoatNormalMap,
  12705. displacementMap: !!material.displacementMap,
  12706. roughnessMap: !!material.roughnessMap,
  12707. metalnessMap: !!material.metalnessMap,
  12708. specularMap: !!material.specularMap,
  12709. alphaMap: !!material.alphaMap,
  12710. gradientMap: !!material.gradientMap,
  12711. sheen: !!material.sheen,
  12712. combine: material.combine,
  12713. vertexTangents: material.normalMap && material.vertexTangents,
  12714. vertexColors: material.vertexColors,
  12715. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap,
  12716. fog: !!fog,
  12717. useFog: material.fog,
  12718. fogExp2: fog && fog.isFogExp2,
  12719. flatShading: material.flatShading,
  12720. sizeAttenuation: material.sizeAttenuation,
  12721. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  12722. skinning: material.skinning && maxBones > 0,
  12723. maxBones: maxBones,
  12724. useVertexTexture: capabilities.floatVertexTextures,
  12725. morphTargets: material.morphTargets,
  12726. morphNormals: material.morphNormals,
  12727. maxMorphTargets: renderer.maxMorphTargets,
  12728. maxMorphNormals: renderer.maxMorphNormals,
  12729. numDirLights: lights.directional.length,
  12730. numPointLights: lights.point.length,
  12731. numSpotLights: lights.spot.length,
  12732. numRectAreaLights: lights.rectArea.length,
  12733. numHemiLights: lights.hemi.length,
  12734. numDirLightShadows: lights.directionalShadowMap.length,
  12735. numPointLightShadows: lights.pointShadowMap.length,
  12736. numSpotLightShadows: lights.spotShadowMap.length,
  12737. numClippingPlanes: nClipPlanes,
  12738. numClipIntersection: nClipIntersection,
  12739. dithering: material.dithering,
  12740. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12741. shadowMapType: renderer.shadowMap.type,
  12742. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12743. physicallyCorrectLights: renderer.physicallyCorrectLights,
  12744. premultipliedAlpha: material.premultipliedAlpha,
  12745. alphaTest: material.alphaTest,
  12746. doubleSided: material.side === DoubleSide,
  12747. flipSided: material.side === BackSide,
  12748. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false
  12749. };
  12750. return parameters;
  12751. };
  12752. this.getProgramCode = function (material, parameters) {
  12753. var array = [];
  12754. if (parameters.shaderID) {
  12755. array.push(parameters.shaderID);
  12756. } else {
  12757. array.push(material.fragmentShader);
  12758. array.push(material.vertexShader);
  12759. }
  12760. if (material.defines !== undefined) {
  12761. for (var name in material.defines) {
  12762. array.push(name);
  12763. array.push(material.defines[name]);
  12764. }
  12765. }
  12766. for (var i = 0; i < parameterNames.length; i++) {
  12767. array.push(parameters[parameterNames[i]]);
  12768. }
  12769. array.push(material.onBeforeCompile.toString());
  12770. array.push(renderer.gammaOutput);
  12771. array.push(renderer.gammaFactor);
  12772. return array.join();
  12773. };
  12774. this.acquireProgram = function (material, shader, parameters, code) {
  12775. var program; // Check if code has been already compiled
  12776. for (var p = 0, pl = programs.length; p < pl; p++) {
  12777. var programInfo = programs[p];
  12778. if (programInfo.code === code) {
  12779. program = programInfo;
  12780. ++program.usedTimes;
  12781. break;
  12782. }
  12783. }
  12784. if (program === undefined) {
  12785. program = new WebGLProgram(renderer, extensions, code, material, shader, parameters);
  12786. programs.push(program);
  12787. }
  12788. return program;
  12789. };
  12790. this.releaseProgram = function (program) {
  12791. if (--program.usedTimes === 0) {
  12792. // Remove from unordered set
  12793. var i = programs.indexOf(program);
  12794. programs[i] = programs[programs.length - 1];
  12795. programs.pop(); // Free WebGL resources
  12796. program.destroy();
  12797. }
  12798. }; // Exposed for resource monitoring & error feedback via renderer.info:
  12799. this.programs = programs;
  12800. }
  12801. /**
  12802. * @author fordacious / fordacious.github.io
  12803. */
  12804. function WebGLProperties() {
  12805. var properties = new WeakMap();
  12806. function get(object) {
  12807. var map = properties.get(object);
  12808. if (map === undefined) {
  12809. map = {};
  12810. properties.set(object, map);
  12811. }
  12812. return map;
  12813. }
  12814. function remove(object) {
  12815. properties.delete(object);
  12816. }
  12817. function update(object, key, value) {
  12818. properties.get(object)[key] = value;
  12819. }
  12820. function dispose() {
  12821. properties = new WeakMap();
  12822. }
  12823. return {
  12824. get: get,
  12825. remove: remove,
  12826. update: update,
  12827. dispose: dispose
  12828. };
  12829. }
  12830. /**
  12831. * @author mrdoob / http://mrdoob.com/
  12832. */
  12833. function painterSortStable(a, b) {
  12834. if (a.groupOrder !== b.groupOrder) {
  12835. return a.groupOrder - b.groupOrder;
  12836. } else if (a.renderOrder !== b.renderOrder) {
  12837. return a.renderOrder - b.renderOrder;
  12838. } else if (a.program !== b.program) {
  12839. return a.program.id - b.program.id;
  12840. } else if (a.material.id !== b.material.id) {
  12841. return a.material.id - b.material.id;
  12842. } else if (a.z !== b.z) {
  12843. return a.z - b.z;
  12844. } else {
  12845. return a.id - b.id;
  12846. }
  12847. }
  12848. function reversePainterSortStable(a, b) {
  12849. if (a.groupOrder !== b.groupOrder) {
  12850. return a.groupOrder - b.groupOrder;
  12851. } else if (a.renderOrder !== b.renderOrder) {
  12852. return a.renderOrder - b.renderOrder;
  12853. } else if (a.z !== b.z) {
  12854. return b.z - a.z;
  12855. } else {
  12856. return a.id - b.id;
  12857. }
  12858. }
  12859. function WebGLRenderList() {
  12860. var renderItems = [];
  12861. var renderItemsIndex = 0;
  12862. var opaque = [];
  12863. var transparent = [];
  12864. var defaultProgram = {
  12865. id: -1
  12866. };
  12867. function init() {
  12868. renderItemsIndex = 0;
  12869. opaque.length = 0;
  12870. transparent.length = 0;
  12871. }
  12872. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12873. var renderItem = renderItems[renderItemsIndex];
  12874. if (renderItem === undefined) {
  12875. renderItem = {
  12876. id: object.id,
  12877. object: object,
  12878. geometry: geometry,
  12879. material: material,
  12880. program: material.program || defaultProgram,
  12881. groupOrder: groupOrder,
  12882. renderOrder: object.renderOrder,
  12883. z: z,
  12884. group: group
  12885. };
  12886. renderItems[renderItemsIndex] = renderItem;
  12887. } else {
  12888. renderItem.id = object.id;
  12889. renderItem.object = object;
  12890. renderItem.geometry = geometry;
  12891. renderItem.material = material;
  12892. renderItem.program = material.program || defaultProgram;
  12893. renderItem.groupOrder = groupOrder;
  12894. renderItem.renderOrder = object.renderOrder;
  12895. renderItem.z = z;
  12896. renderItem.group = group;
  12897. }
  12898. renderItemsIndex++;
  12899. return renderItem;
  12900. }
  12901. function push(object, geometry, material, groupOrder, z, group) {
  12902. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12903. (material.transparent === true ? transparent : opaque).push(renderItem);
  12904. }
  12905. function unshift(object, geometry, material, groupOrder, z, group) {
  12906. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12907. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  12908. }
  12909. function sort() {
  12910. if (opaque.length > 1) opaque.sort(painterSortStable);
  12911. if (transparent.length > 1) transparent.sort(reversePainterSortStable);
  12912. }
  12913. return {
  12914. opaque: opaque,
  12915. transparent: transparent,
  12916. init: init,
  12917. push: push,
  12918. unshift: unshift,
  12919. sort: sort
  12920. };
  12921. }
  12922. function WebGLRenderLists() {
  12923. var lists = new WeakMap();
  12924. function onSceneDispose(event) {
  12925. var scene = event.target;
  12926. scene.removeEventListener('dispose', onSceneDispose);
  12927. lists.delete(scene);
  12928. }
  12929. function get(scene, camera) {
  12930. var cameras = lists.get(scene);
  12931. var list;
  12932. if (cameras === undefined) {
  12933. list = new WebGLRenderList();
  12934. lists.set(scene, new WeakMap());
  12935. lists.get(scene).set(camera, list);
  12936. scene.addEventListener('dispose', onSceneDispose);
  12937. } else {
  12938. list = cameras.get(camera);
  12939. if (list === undefined) {
  12940. list = new WebGLRenderList();
  12941. cameras.set(camera, list);
  12942. }
  12943. }
  12944. return list;
  12945. }
  12946. function dispose() {
  12947. lists = new WeakMap();
  12948. }
  12949. return {
  12950. get: get,
  12951. dispose: dispose
  12952. };
  12953. }
  12954. /**
  12955. * @author mrdoob / http://mrdoob.com/
  12956. */
  12957. function UniformsCache() {
  12958. var lights = {};
  12959. return {
  12960. get: function (light) {
  12961. if (lights[light.id] !== undefined) {
  12962. return lights[light.id];
  12963. }
  12964. var uniforms;
  12965. switch (light.type) {
  12966. case 'DirectionalLight':
  12967. uniforms = {
  12968. direction: new Vector3(),
  12969. color: new Color(),
  12970. shadow: false,
  12971. shadowBias: 0,
  12972. shadowRadius: 1,
  12973. shadowMapSize: new Vector2()
  12974. };
  12975. break;
  12976. case 'SpotLight':
  12977. uniforms = {
  12978. position: new Vector3(),
  12979. direction: new Vector3(),
  12980. color: new Color(),
  12981. distance: 0,
  12982. coneCos: 0,
  12983. penumbraCos: 0,
  12984. decay: 0,
  12985. shadow: false,
  12986. shadowBias: 0,
  12987. shadowRadius: 1,
  12988. shadowMapSize: new Vector2()
  12989. };
  12990. break;
  12991. case 'PointLight':
  12992. uniforms = {
  12993. position: new Vector3(),
  12994. color: new Color(),
  12995. distance: 0,
  12996. decay: 0,
  12997. shadow: false,
  12998. shadowBias: 0,
  12999. shadowRadius: 1,
  13000. shadowMapSize: new Vector2(),
  13001. shadowCameraNear: 1,
  13002. shadowCameraFar: 1000
  13003. };
  13004. break;
  13005. case 'HemisphereLight':
  13006. uniforms = {
  13007. direction: new Vector3(),
  13008. skyColor: new Color(),
  13009. groundColor: new Color()
  13010. };
  13011. break;
  13012. case 'RectAreaLight':
  13013. uniforms = {
  13014. color: new Color(),
  13015. position: new Vector3(),
  13016. halfWidth: new Vector3(),
  13017. halfHeight: new Vector3() // TODO (abelnation): set RectAreaLight shadow uniforms
  13018. };
  13019. break;
  13020. }
  13021. lights[light.id] = uniforms;
  13022. return uniforms;
  13023. }
  13024. };
  13025. }
  13026. var nextVersion = 0;
  13027. function shadowCastingLightsFirst(lightA, lightB) {
  13028. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  13029. }
  13030. function WebGLLights() {
  13031. var cache = new UniformsCache();
  13032. var state = {
  13033. version: 0,
  13034. hash: {
  13035. directionalLength: -1,
  13036. pointLength: -1,
  13037. spotLength: -1,
  13038. rectAreaLength: -1,
  13039. hemiLength: -1,
  13040. numDirectionalShadows: -1,
  13041. numPointShadows: -1,
  13042. numSpotShadows: -1
  13043. },
  13044. ambient: [0, 0, 0],
  13045. probe: [],
  13046. directional: [],
  13047. directionalShadowMap: [],
  13048. directionalShadowMatrix: [],
  13049. spot: [],
  13050. spotShadowMap: [],
  13051. spotShadowMatrix: [],
  13052. rectArea: [],
  13053. point: [],
  13054. pointShadowMap: [],
  13055. pointShadowMatrix: [],
  13056. hemi: [],
  13057. numDirectionalShadows: -1,
  13058. numPointShadows: -1,
  13059. numSpotShadows: -1
  13060. };
  13061. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  13062. var vector3 = new Vector3();
  13063. var matrix4 = new Matrix4();
  13064. var matrix42 = new Matrix4();
  13065. function setup(lights, shadows, camera) {
  13066. var r = 0,
  13067. g = 0,
  13068. b = 0;
  13069. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  13070. var directionalLength = 0;
  13071. var pointLength = 0;
  13072. var spotLength = 0;
  13073. var rectAreaLength = 0;
  13074. var hemiLength = 0;
  13075. var numDirectionalShadows = 0;
  13076. var numPointShadows = 0;
  13077. var numSpotShadows = 0;
  13078. var viewMatrix = camera.matrixWorldInverse;
  13079. lights.sort(shadowCastingLightsFirst);
  13080. for (var i = 0, l = lights.length; i < l; i++) {
  13081. var light = lights[i];
  13082. var color = light.color;
  13083. var intensity = light.intensity;
  13084. var distance = light.distance;
  13085. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  13086. if (light.isAmbientLight) {
  13087. r += color.r * intensity;
  13088. g += color.g * intensity;
  13089. b += color.b * intensity;
  13090. } else if (light.isLightProbe) {
  13091. for (var j = 0; j < 9; j++) {
  13092. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  13093. }
  13094. } else if (light.isDirectionalLight) {
  13095. var uniforms = cache.get(light);
  13096. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13097. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13098. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13099. uniforms.direction.sub(vector3);
  13100. uniforms.direction.transformDirection(viewMatrix);
  13101. uniforms.shadow = light.castShadow;
  13102. if (light.castShadow) {
  13103. var shadow = light.shadow;
  13104. uniforms.shadowBias = shadow.bias;
  13105. uniforms.shadowRadius = shadow.radius;
  13106. uniforms.shadowMapSize = shadow.mapSize;
  13107. state.directionalShadowMap[directionalLength] = shadowMap;
  13108. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  13109. numDirectionalShadows++;
  13110. }
  13111. state.directional[directionalLength] = uniforms;
  13112. directionalLength++;
  13113. } else if (light.isSpotLight) {
  13114. var uniforms = cache.get(light);
  13115. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13116. uniforms.position.applyMatrix4(viewMatrix);
  13117. uniforms.color.copy(color).multiplyScalar(intensity);
  13118. uniforms.distance = distance;
  13119. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13120. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13121. uniforms.direction.sub(vector3);
  13122. uniforms.direction.transformDirection(viewMatrix);
  13123. uniforms.coneCos = Math.cos(light.angle);
  13124. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  13125. uniforms.decay = light.decay;
  13126. uniforms.shadow = light.castShadow;
  13127. if (light.castShadow) {
  13128. var shadow = light.shadow;
  13129. uniforms.shadowBias = shadow.bias;
  13130. uniforms.shadowRadius = shadow.radius;
  13131. uniforms.shadowMapSize = shadow.mapSize;
  13132. state.spotShadowMap[spotLength] = shadowMap;
  13133. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  13134. numSpotShadows++;
  13135. }
  13136. state.spot[spotLength] = uniforms;
  13137. spotLength++;
  13138. } else if (light.isRectAreaLight) {
  13139. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  13140. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  13141. // (b) intensity is the brightness of the light
  13142. uniforms.color.copy(color).multiplyScalar(intensity);
  13143. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13144. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  13145. matrix42.identity();
  13146. matrix4.copy(light.matrixWorld);
  13147. matrix4.premultiply(viewMatrix);
  13148. matrix42.extractRotation(matrix4);
  13149. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  13150. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  13151. uniforms.halfWidth.applyMatrix4(matrix42);
  13152. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  13153. // uniforms.distance = distance;
  13154. state.rectArea[rectAreaLength] = uniforms;
  13155. rectAreaLength++;
  13156. } else if (light.isPointLight) {
  13157. var uniforms = cache.get(light);
  13158. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13159. uniforms.position.applyMatrix4(viewMatrix);
  13160. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13161. uniforms.distance = light.distance;
  13162. uniforms.decay = light.decay;
  13163. uniforms.shadow = light.castShadow;
  13164. if (light.castShadow) {
  13165. var shadow = light.shadow;
  13166. uniforms.shadowBias = shadow.bias;
  13167. uniforms.shadowRadius = shadow.radius;
  13168. uniforms.shadowMapSize = shadow.mapSize;
  13169. uniforms.shadowCameraNear = shadow.camera.near;
  13170. uniforms.shadowCameraFar = shadow.camera.far;
  13171. state.pointShadowMap[pointLength] = shadowMap;
  13172. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  13173. numPointShadows++;
  13174. }
  13175. state.point[pointLength] = uniforms;
  13176. pointLength++;
  13177. } else if (light.isHemisphereLight) {
  13178. var uniforms = cache.get(light);
  13179. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13180. uniforms.direction.transformDirection(viewMatrix);
  13181. uniforms.direction.normalize();
  13182. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  13183. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  13184. state.hemi[hemiLength] = uniforms;
  13185. hemiLength++;
  13186. }
  13187. }
  13188. state.ambient[0] = r;
  13189. state.ambient[1] = g;
  13190. state.ambient[2] = b;
  13191. var hash = state.hash;
  13192. 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) {
  13193. state.directional.length = directionalLength;
  13194. state.spot.length = spotLength;
  13195. state.rectArea.length = rectAreaLength;
  13196. state.point.length = pointLength;
  13197. state.hemi.length = hemiLength;
  13198. state.directionalShadowMap.length = numDirectionalShadows;
  13199. state.pointShadowMap.length = numPointShadows;
  13200. state.spotShadowMap.length = numSpotShadows;
  13201. state.directionalShadowMatrix.length = numDirectionalShadows;
  13202. state.pointShadowMatrix.length = numPointShadows;
  13203. state.spotShadowMatrix.length = numSpotShadows;
  13204. hash.directionalLength = directionalLength;
  13205. hash.pointLength = pointLength;
  13206. hash.spotLength = spotLength;
  13207. hash.rectAreaLength = rectAreaLength;
  13208. hash.hemiLength = hemiLength;
  13209. hash.numDirectionalShadows = numDirectionalShadows;
  13210. hash.numPointShadows = numPointShadows;
  13211. hash.numSpotShadows = numSpotShadows;
  13212. state.version = nextVersion++;
  13213. }
  13214. }
  13215. return {
  13216. setup: setup,
  13217. state: state
  13218. };
  13219. }
  13220. /**
  13221. * @author Mugen87 / https://github.com/Mugen87
  13222. */
  13223. function WebGLRenderState() {
  13224. var lights = new WebGLLights();
  13225. var lightsArray = [];
  13226. var shadowsArray = [];
  13227. function init() {
  13228. lightsArray.length = 0;
  13229. shadowsArray.length = 0;
  13230. }
  13231. function pushLight(light) {
  13232. lightsArray.push(light);
  13233. }
  13234. function pushShadow(shadowLight) {
  13235. shadowsArray.push(shadowLight);
  13236. }
  13237. function setupLights(camera) {
  13238. lights.setup(lightsArray, shadowsArray, camera);
  13239. }
  13240. var state = {
  13241. lightsArray: lightsArray,
  13242. shadowsArray: shadowsArray,
  13243. lights: lights
  13244. };
  13245. return {
  13246. init: init,
  13247. state: state,
  13248. setupLights: setupLights,
  13249. pushLight: pushLight,
  13250. pushShadow: pushShadow
  13251. };
  13252. }
  13253. function WebGLRenderStates() {
  13254. var renderStates = new WeakMap();
  13255. function onSceneDispose(event) {
  13256. var scene = event.target;
  13257. scene.removeEventListener('dispose', onSceneDispose);
  13258. renderStates.delete(scene);
  13259. }
  13260. function get(scene, camera) {
  13261. var renderState;
  13262. if (renderStates.has(scene) === false) {
  13263. renderState = new WebGLRenderState();
  13264. renderStates.set(scene, new WeakMap());
  13265. renderStates.get(scene).set(camera, renderState);
  13266. scene.addEventListener('dispose', onSceneDispose);
  13267. } else {
  13268. if (renderStates.get(scene).has(camera) === false) {
  13269. renderState = new WebGLRenderState();
  13270. renderStates.get(scene).set(camera, renderState);
  13271. } else {
  13272. renderState = renderStates.get(scene).get(camera);
  13273. }
  13274. }
  13275. return renderState;
  13276. }
  13277. function dispose() {
  13278. renderStates = new WeakMap();
  13279. }
  13280. return {
  13281. get: get,
  13282. dispose: dispose
  13283. };
  13284. }
  13285. /**
  13286. * @author mrdoob / http://mrdoob.com/
  13287. * @author alteredq / http://alteredqualia.com/
  13288. * @author bhouston / https://clara.io
  13289. * @author WestLangley / http://github.com/WestLangley
  13290. *
  13291. * parameters = {
  13292. *
  13293. * opacity: <float>,
  13294. *
  13295. * map: new THREE.Texture( <Image> ),
  13296. *
  13297. * alphaMap: new THREE.Texture( <Image> ),
  13298. *
  13299. * displacementMap: new THREE.Texture( <Image> ),
  13300. * displacementScale: <float>,
  13301. * displacementBias: <float>,
  13302. *
  13303. * wireframe: <boolean>,
  13304. * wireframeLinewidth: <float>
  13305. * }
  13306. */
  13307. function MeshDepthMaterial(parameters) {
  13308. Material.call(this);
  13309. this.type = 'MeshDepthMaterial';
  13310. this.depthPacking = BasicDepthPacking;
  13311. this.skinning = false;
  13312. this.morphTargets = false;
  13313. this.map = null;
  13314. this.alphaMap = null;
  13315. this.displacementMap = null;
  13316. this.displacementScale = 1;
  13317. this.displacementBias = 0;
  13318. this.wireframe = false;
  13319. this.wireframeLinewidth = 1;
  13320. this.fog = false;
  13321. this.setValues(parameters);
  13322. }
  13323. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  13324. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  13325. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  13326. MeshDepthMaterial.prototype.copy = function (source) {
  13327. Material.prototype.copy.call(this, source);
  13328. this.depthPacking = source.depthPacking;
  13329. this.skinning = source.skinning;
  13330. this.morphTargets = source.morphTargets;
  13331. this.map = source.map;
  13332. this.alphaMap = source.alphaMap;
  13333. this.displacementMap = source.displacementMap;
  13334. this.displacementScale = source.displacementScale;
  13335. this.displacementBias = source.displacementBias;
  13336. this.wireframe = source.wireframe;
  13337. this.wireframeLinewidth = source.wireframeLinewidth;
  13338. return this;
  13339. };
  13340. /**
  13341. * @author WestLangley / http://github.com/WestLangley
  13342. *
  13343. * parameters = {
  13344. *
  13345. * referencePosition: <float>,
  13346. * nearDistance: <float>,
  13347. * farDistance: <float>,
  13348. *
  13349. * skinning: <bool>,
  13350. * morphTargets: <bool>,
  13351. *
  13352. * map: new THREE.Texture( <Image> ),
  13353. *
  13354. * alphaMap: new THREE.Texture( <Image> ),
  13355. *
  13356. * displacementMap: new THREE.Texture( <Image> ),
  13357. * displacementScale: <float>,
  13358. * displacementBias: <float>
  13359. *
  13360. * }
  13361. */
  13362. function MeshDistanceMaterial(parameters) {
  13363. Material.call(this);
  13364. this.type = 'MeshDistanceMaterial';
  13365. this.referencePosition = new Vector3();
  13366. this.nearDistance = 1;
  13367. this.farDistance = 1000;
  13368. this.skinning = false;
  13369. this.morphTargets = false;
  13370. this.map = null;
  13371. this.alphaMap = null;
  13372. this.displacementMap = null;
  13373. this.displacementScale = 1;
  13374. this.displacementBias = 0;
  13375. this.fog = false;
  13376. this.setValues(parameters);
  13377. }
  13378. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  13379. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  13380. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  13381. MeshDistanceMaterial.prototype.copy = function (source) {
  13382. Material.prototype.copy.call(this, source);
  13383. this.referencePosition.copy(source.referencePosition);
  13384. this.nearDistance = source.nearDistance;
  13385. this.farDistance = source.farDistance;
  13386. this.skinning = source.skinning;
  13387. this.morphTargets = source.morphTargets;
  13388. this.map = source.map;
  13389. this.alphaMap = source.alphaMap;
  13390. this.displacementMap = source.displacementMap;
  13391. this.displacementScale = source.displacementScale;
  13392. this.displacementBias = source.displacementBias;
  13393. return this;
  13394. };
  13395. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n \n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = decodeHalfRGBA ( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = pow( squared_mean - mean * mean, 0.5 );\n gl_FragColor = encodeHalfRGBA( vec2( mean, std_dev ) );\n}";
  13396. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13397. /**
  13398. * @author alteredq / http://alteredqualia.com/
  13399. * @author mrdoob / http://mrdoob.com/
  13400. */
  13401. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  13402. var _frustum = new Frustum(),
  13403. _shadowMapSize = new Vector2(),
  13404. _viewportSize = new Vector2(),
  13405. _viewport = new Vector4(),
  13406. _MorphingFlag = 1,
  13407. _SkinningFlag = 2,
  13408. _NumberOfMaterialVariants = (_MorphingFlag | _SkinningFlag) + 1,
  13409. _depthMaterials = new Array(_NumberOfMaterialVariants),
  13410. _distanceMaterials = new Array(_NumberOfMaterialVariants),
  13411. _materialCache = {};
  13412. var shadowSide = {
  13413. 0: BackSide,
  13414. 1: FrontSide,
  13415. 2: DoubleSide
  13416. };
  13417. var shadowMaterialVertical = new ShaderMaterial({
  13418. defines: {
  13419. SAMPLE_RATE: 2.0 / 8.0,
  13420. HALF_SAMPLE_RATE: 1.0 / 8.0
  13421. },
  13422. uniforms: {
  13423. shadow_pass: {
  13424. value: null
  13425. },
  13426. resolution: {
  13427. value: new Vector2()
  13428. },
  13429. radius: {
  13430. value: 4.0
  13431. }
  13432. },
  13433. vertexShader: vsm_vert,
  13434. fragmentShader: vsm_frag
  13435. });
  13436. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  13437. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  13438. var fullScreenTri = new BufferGeometry();
  13439. fullScreenTri.addAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  13440. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); // init
  13441. for (var i = 0; i !== _NumberOfMaterialVariants; ++i) {
  13442. var useMorphing = (i & _MorphingFlag) !== 0;
  13443. var useSkinning = (i & _SkinningFlag) !== 0;
  13444. var depthMaterial = new MeshDepthMaterial({
  13445. depthPacking: RGBADepthPacking,
  13446. morphTargets: useMorphing,
  13447. skinning: useSkinning
  13448. });
  13449. _depthMaterials[i] = depthMaterial;
  13450. var distanceMaterial = new MeshDistanceMaterial({
  13451. morphTargets: useMorphing,
  13452. skinning: useSkinning
  13453. });
  13454. _distanceMaterials[i] = distanceMaterial;
  13455. }
  13456. var scope = this;
  13457. this.enabled = false;
  13458. this.autoUpdate = true;
  13459. this.needsUpdate = false;
  13460. this.type = PCFShadowMap;
  13461. this.render = function (lights, scene, camera) {
  13462. if (scope.enabled === false) return;
  13463. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  13464. if (lights.length === 0) return;
  13465. var currentRenderTarget = _renderer.getRenderTarget();
  13466. var activeCubeFace = _renderer.getActiveCubeFace();
  13467. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13468. var _state = _renderer.state; // Set GL state for depth map.
  13469. _state.setBlending(NoBlending);
  13470. _state.buffers.color.setClear(1, 1, 1, 1);
  13471. _state.buffers.depth.setTest(true);
  13472. _state.setScissorTest(false); // render depth map
  13473. for (var i = 0, il = lights.length; i < il; i++) {
  13474. var light = lights[i];
  13475. var shadow = light.shadow;
  13476. if (shadow === undefined) {
  13477. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  13478. continue;
  13479. }
  13480. _shadowMapSize.copy(shadow.mapSize);
  13481. var shadowFrameExtents = shadow.getFrameExtents();
  13482. _shadowMapSize.multiply(shadowFrameExtents);
  13483. _viewportSize.copy(shadow.mapSize);
  13484. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  13485. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  13486. if (_shadowMapSize.x > maxTextureSize) {
  13487. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  13488. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13489. shadow.mapSize.x = _viewportSize.x;
  13490. }
  13491. if (_shadowMapSize.y > maxTextureSize) {
  13492. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  13493. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13494. shadow.mapSize.y = _viewportSize.y;
  13495. }
  13496. }
  13497. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13498. var pars = {
  13499. minFilter: LinearFilter,
  13500. magFilter: LinearFilter,
  13501. format: RGBAFormat
  13502. };
  13503. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13504. shadow.map.texture.name = light.name + ".shadowMap";
  13505. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13506. shadow.camera.updateProjectionMatrix();
  13507. }
  13508. if (shadow.map === null) {
  13509. var pars = {
  13510. minFilter: NearestFilter,
  13511. magFilter: NearestFilter,
  13512. format: RGBAFormat
  13513. };
  13514. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13515. shadow.map.texture.name = light.name + ".shadowMap";
  13516. shadow.camera.updateProjectionMatrix();
  13517. }
  13518. _renderer.setRenderTarget(shadow.map);
  13519. _renderer.clear();
  13520. var viewportCount = shadow.getViewportCount();
  13521. for (var vp = 0; vp < viewportCount; vp++) {
  13522. var viewport = shadow.getViewport(vp);
  13523. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  13524. _state.viewport(_viewport);
  13525. shadow.updateMatrices(light, camera, vp);
  13526. _frustum = shadow.getFrustum();
  13527. renderObject(scene, camera, shadow.camera, light, this.type);
  13528. } // do blur pass for VSM
  13529. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13530. VSMPass(shadow, camera);
  13531. }
  13532. }
  13533. scope.needsUpdate = false;
  13534. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  13535. };
  13536. function VSMPass(shadow, camera) {
  13537. var geometry = _objects.update(fullScreenMesh); // vertical pass
  13538. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13539. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13540. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13541. _renderer.setRenderTarget(shadow.mapPass);
  13542. _renderer.clear();
  13543. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  13544. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13545. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  13546. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  13547. _renderer.setRenderTarget(shadow.map);
  13548. _renderer.clear();
  13549. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  13550. }
  13551. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  13552. var geometry = object.geometry;
  13553. var result = null;
  13554. var materialVariants = _depthMaterials;
  13555. var customMaterial = object.customDepthMaterial;
  13556. if (light.isPointLight) {
  13557. materialVariants = _distanceMaterials;
  13558. customMaterial = object.customDistanceMaterial;
  13559. }
  13560. if (!customMaterial) {
  13561. var useMorphing = false;
  13562. if (material.morphTargets) {
  13563. if (geometry && geometry.isBufferGeometry) {
  13564. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  13565. } else if (geometry && geometry.isGeometry) {
  13566. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  13567. }
  13568. }
  13569. if (object.isSkinnedMesh && material.skinning === false) {
  13570. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  13571. }
  13572. var useSkinning = object.isSkinnedMesh && material.skinning;
  13573. var variantIndex = 0;
  13574. if (useMorphing) variantIndex |= _MorphingFlag;
  13575. if (useSkinning) variantIndex |= _SkinningFlag;
  13576. result = materialVariants[variantIndex];
  13577. } else {
  13578. result = customMaterial;
  13579. }
  13580. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  13581. // in this case we need a unique material instance reflecting the
  13582. // appropriate state
  13583. var keyA = result.uuid,
  13584. keyB = material.uuid;
  13585. var materialsForVariant = _materialCache[keyA];
  13586. if (materialsForVariant === undefined) {
  13587. materialsForVariant = {};
  13588. _materialCache[keyA] = materialsForVariant;
  13589. }
  13590. var cachedMaterial = materialsForVariant[keyB];
  13591. if (cachedMaterial === undefined) {
  13592. cachedMaterial = result.clone();
  13593. materialsForVariant[keyB] = cachedMaterial;
  13594. }
  13595. result = cachedMaterial;
  13596. }
  13597. result.visible = material.visible;
  13598. result.wireframe = material.wireframe;
  13599. if (type === VSMShadowMap) {
  13600. result.side = material.shadowSide != null ? material.shadowSide : material.side;
  13601. } else {
  13602. result.side = material.shadowSide != null ? material.shadowSide : shadowSide[material.side];
  13603. }
  13604. result.clipShadows = material.clipShadows;
  13605. result.clippingPlanes = material.clippingPlanes;
  13606. result.clipIntersection = material.clipIntersection;
  13607. result.wireframeLinewidth = material.wireframeLinewidth;
  13608. result.linewidth = material.linewidth;
  13609. if (light.isPointLight && result.isMeshDistanceMaterial) {
  13610. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  13611. result.nearDistance = shadowCameraNear;
  13612. result.farDistance = shadowCameraFar;
  13613. }
  13614. return result;
  13615. }
  13616. function renderObject(object, camera, shadowCamera, light, type) {
  13617. if (object.visible === false) return;
  13618. var visible = object.layers.test(camera.layers);
  13619. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  13620. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  13621. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  13622. var geometry = _objects.update(object);
  13623. var material = object.material;
  13624. if (Array.isArray(material)) {
  13625. var groups = geometry.groups;
  13626. for (var k = 0, kl = groups.length; k < kl; k++) {
  13627. var group = groups[k];
  13628. var groupMaterial = material[group.materialIndex];
  13629. if (groupMaterial && groupMaterial.visible) {
  13630. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  13631. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  13632. }
  13633. }
  13634. } else if (material.visible) {
  13635. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  13636. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  13637. }
  13638. }
  13639. }
  13640. var children = object.children;
  13641. for (var i = 0, l = children.length; i < l; i++) {
  13642. renderObject(children[i], camera, shadowCamera, light, type);
  13643. }
  13644. }
  13645. }
  13646. /**
  13647. * @author mrdoob / http://mrdoob.com/
  13648. */
  13649. function WebGLState(gl, extensions, utils, capabilities) {
  13650. function ColorBuffer() {
  13651. var locked = false;
  13652. var color = new Vector4();
  13653. var currentColorMask = null;
  13654. var currentColorClear = new Vector4(0, 0, 0, 0);
  13655. return {
  13656. setMask: function (colorMask) {
  13657. if (currentColorMask !== colorMask && !locked) {
  13658. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  13659. currentColorMask = colorMask;
  13660. }
  13661. },
  13662. setLocked: function (lock) {
  13663. locked = lock;
  13664. },
  13665. setClear: function (r, g, b, a, premultipliedAlpha) {
  13666. if (premultipliedAlpha === true) {
  13667. r *= a;
  13668. g *= a;
  13669. b *= a;
  13670. }
  13671. color.set(r, g, b, a);
  13672. if (currentColorClear.equals(color) === false) {
  13673. gl.clearColor(r, g, b, a);
  13674. currentColorClear.copy(color);
  13675. }
  13676. },
  13677. reset: function () {
  13678. locked = false;
  13679. currentColorMask = null;
  13680. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  13681. }
  13682. };
  13683. }
  13684. function DepthBuffer() {
  13685. var locked = false;
  13686. var currentDepthMask = null;
  13687. var currentDepthFunc = null;
  13688. var currentDepthClear = null;
  13689. return {
  13690. setTest: function (depthTest) {
  13691. if (depthTest) {
  13692. enable(2929);
  13693. } else {
  13694. disable(2929);
  13695. }
  13696. },
  13697. setMask: function (depthMask) {
  13698. if (currentDepthMask !== depthMask && !locked) {
  13699. gl.depthMask(depthMask);
  13700. currentDepthMask = depthMask;
  13701. }
  13702. },
  13703. setFunc: function (depthFunc) {
  13704. if (currentDepthFunc !== depthFunc) {
  13705. if (depthFunc) {
  13706. switch (depthFunc) {
  13707. case NeverDepth:
  13708. gl.depthFunc(512);
  13709. break;
  13710. case AlwaysDepth:
  13711. gl.depthFunc(519);
  13712. break;
  13713. case LessDepth:
  13714. gl.depthFunc(513);
  13715. break;
  13716. case LessEqualDepth:
  13717. gl.depthFunc(515);
  13718. break;
  13719. case EqualDepth:
  13720. gl.depthFunc(514);
  13721. break;
  13722. case GreaterEqualDepth:
  13723. gl.depthFunc(518);
  13724. break;
  13725. case GreaterDepth:
  13726. gl.depthFunc(516);
  13727. break;
  13728. case NotEqualDepth:
  13729. gl.depthFunc(517);
  13730. break;
  13731. default:
  13732. gl.depthFunc(515);
  13733. }
  13734. } else {
  13735. gl.depthFunc(515);
  13736. }
  13737. currentDepthFunc = depthFunc;
  13738. }
  13739. },
  13740. setLocked: function (lock) {
  13741. locked = lock;
  13742. },
  13743. setClear: function (depth) {
  13744. if (currentDepthClear !== depth) {
  13745. gl.clearDepth(depth);
  13746. currentDepthClear = depth;
  13747. }
  13748. },
  13749. reset: function () {
  13750. locked = false;
  13751. currentDepthMask = null;
  13752. currentDepthFunc = null;
  13753. currentDepthClear = null;
  13754. }
  13755. };
  13756. }
  13757. function StencilBuffer() {
  13758. var locked = false;
  13759. var currentStencilMask = null;
  13760. var currentStencilFunc = null;
  13761. var currentStencilRef = null;
  13762. var currentStencilFuncMask = null;
  13763. var currentStencilFail = null;
  13764. var currentStencilZFail = null;
  13765. var currentStencilZPass = null;
  13766. var currentStencilClear = null;
  13767. return {
  13768. setTest: function (stencilTest) {
  13769. if (!locked) {
  13770. if (stencilTest) {
  13771. enable(2960);
  13772. } else {
  13773. disable(2960);
  13774. }
  13775. }
  13776. },
  13777. setMask: function (stencilMask) {
  13778. if (currentStencilMask !== stencilMask && !locked) {
  13779. gl.stencilMask(stencilMask);
  13780. currentStencilMask = stencilMask;
  13781. }
  13782. },
  13783. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  13784. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  13785. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  13786. currentStencilFunc = stencilFunc;
  13787. currentStencilRef = stencilRef;
  13788. currentStencilFuncMask = stencilMask;
  13789. }
  13790. },
  13791. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  13792. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13793. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13794. currentStencilFail = stencilFail;
  13795. currentStencilZFail = stencilZFail;
  13796. currentStencilZPass = stencilZPass;
  13797. }
  13798. },
  13799. setLocked: function (lock) {
  13800. locked = lock;
  13801. },
  13802. setClear: function (stencil) {
  13803. if (currentStencilClear !== stencil) {
  13804. gl.clearStencil(stencil);
  13805. currentStencilClear = stencil;
  13806. }
  13807. },
  13808. reset: function () {
  13809. locked = false;
  13810. currentStencilMask = null;
  13811. currentStencilFunc = null;
  13812. currentStencilRef = null;
  13813. currentStencilFuncMask = null;
  13814. currentStencilFail = null;
  13815. currentStencilZFail = null;
  13816. currentStencilZPass = null;
  13817. currentStencilClear = null;
  13818. }
  13819. };
  13820. } //
  13821. var colorBuffer = new ColorBuffer();
  13822. var depthBuffer = new DepthBuffer();
  13823. var stencilBuffer = new StencilBuffer();
  13824. var maxVertexAttributes = gl.getParameter(34921);
  13825. var newAttributes = new Uint8Array(maxVertexAttributes);
  13826. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  13827. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  13828. var enabledCapabilities = {};
  13829. var compressedTextureFormats = null;
  13830. var currentProgram = null;
  13831. var currentBlendingEnabled = null;
  13832. var currentBlending = null;
  13833. var currentBlendEquation = null;
  13834. var currentBlendSrc = null;
  13835. var currentBlendDst = null;
  13836. var currentBlendEquationAlpha = null;
  13837. var currentBlendSrcAlpha = null;
  13838. var currentBlendDstAlpha = null;
  13839. var currentPremultipledAlpha = false;
  13840. var currentFlipSided = null;
  13841. var currentCullFace = null;
  13842. var currentLineWidth = null;
  13843. var currentPolygonOffsetFactor = null;
  13844. var currentPolygonOffsetUnits = null;
  13845. var maxTextures = gl.getParameter(35661);
  13846. var lineWidthAvailable = false;
  13847. var version = 0;
  13848. var glVersion = gl.getParameter(7938);
  13849. if (glVersion.indexOf('WebGL') !== -1) {
  13850. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  13851. lineWidthAvailable = version >= 1.0;
  13852. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13853. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  13854. lineWidthAvailable = version >= 2.0;
  13855. }
  13856. var currentTextureSlot = null;
  13857. var currentBoundTextures = {};
  13858. var currentScissor = new Vector4();
  13859. var currentViewport = new Vector4();
  13860. function createTexture(type, target, count) {
  13861. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13862. var texture = gl.createTexture();
  13863. gl.bindTexture(type, texture);
  13864. gl.texParameteri(type, 10241, 9728);
  13865. gl.texParameteri(type, 10240, 9728);
  13866. for (var i = 0; i < count; i++) {
  13867. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  13868. }
  13869. return texture;
  13870. }
  13871. var emptyTextures = {};
  13872. emptyTextures[3553] = createTexture(3553, 3553, 1);
  13873. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  13874. colorBuffer.setClear(0, 0, 0, 1);
  13875. depthBuffer.setClear(1);
  13876. stencilBuffer.setClear(0);
  13877. enable(2929);
  13878. depthBuffer.setFunc(LessEqualDepth);
  13879. setFlipSided(false);
  13880. setCullFace(CullFaceBack);
  13881. enable(2884);
  13882. setBlending(NoBlending); //
  13883. function initAttributes() {
  13884. for (var i = 0, l = newAttributes.length; i < l; i++) {
  13885. newAttributes[i] = 0;
  13886. }
  13887. }
  13888. function enableAttribute(attribute) {
  13889. enableAttributeAndDivisor(attribute, 0);
  13890. }
  13891. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  13892. newAttributes[attribute] = 1;
  13893. if (enabledAttributes[attribute] === 0) {
  13894. gl.enableVertexAttribArray(attribute);
  13895. enabledAttributes[attribute] = 1;
  13896. }
  13897. if (attributeDivisors[attribute] !== meshPerAttribute) {
  13898. var extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  13899. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  13900. attributeDivisors[attribute] = meshPerAttribute;
  13901. }
  13902. }
  13903. function disableUnusedAttributes() {
  13904. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  13905. if (enabledAttributes[i] !== newAttributes[i]) {
  13906. gl.disableVertexAttribArray(i);
  13907. enabledAttributes[i] = 0;
  13908. }
  13909. }
  13910. }
  13911. function enable(id) {
  13912. if (enabledCapabilities[id] !== true) {
  13913. gl.enable(id);
  13914. enabledCapabilities[id] = true;
  13915. }
  13916. }
  13917. function disable(id) {
  13918. if (enabledCapabilities[id] !== false) {
  13919. gl.disable(id);
  13920. enabledCapabilities[id] = false;
  13921. }
  13922. }
  13923. function getCompressedTextureFormats() {
  13924. if (compressedTextureFormats === null) {
  13925. compressedTextureFormats = [];
  13926. if (extensions.get('WEBGL_compressed_texture_pvrtc') || extensions.get('WEBGL_compressed_texture_s3tc') || extensions.get('WEBGL_compressed_texture_etc1') || extensions.get('WEBGL_compressed_texture_astc')) {
  13927. var formats = gl.getParameter(34467);
  13928. for (var i = 0; i < formats.length; i++) {
  13929. compressedTextureFormats.push(formats[i]);
  13930. }
  13931. }
  13932. }
  13933. return compressedTextureFormats;
  13934. }
  13935. function useProgram(program) {
  13936. if (currentProgram !== program) {
  13937. gl.useProgram(program);
  13938. currentProgram = program;
  13939. return true;
  13940. }
  13941. return false;
  13942. }
  13943. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13944. if (blending === NoBlending) {
  13945. if (currentBlendingEnabled) {
  13946. disable(3042);
  13947. currentBlendingEnabled = false;
  13948. }
  13949. return;
  13950. }
  13951. if (!currentBlendingEnabled) {
  13952. enable(3042);
  13953. currentBlendingEnabled = true;
  13954. }
  13955. if (blending !== CustomBlending) {
  13956. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13957. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13958. gl.blendEquation(32774);
  13959. currentBlendEquation = AddEquation;
  13960. currentBlendEquationAlpha = AddEquation;
  13961. }
  13962. if (premultipliedAlpha) {
  13963. switch (blending) {
  13964. case NormalBlending:
  13965. gl.blendFuncSeparate(1, 771, 1, 771);
  13966. break;
  13967. case AdditiveBlending:
  13968. gl.blendFunc(1, 1);
  13969. break;
  13970. case SubtractiveBlending:
  13971. gl.blendFuncSeparate(0, 0, 769, 771);
  13972. break;
  13973. case MultiplyBlending:
  13974. gl.blendFuncSeparate(0, 768, 0, 770);
  13975. break;
  13976. default:
  13977. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13978. break;
  13979. }
  13980. } else {
  13981. switch (blending) {
  13982. case NormalBlending:
  13983. gl.blendFuncSeparate(770, 771, 1, 771);
  13984. break;
  13985. case AdditiveBlending:
  13986. gl.blendFunc(770, 1);
  13987. break;
  13988. case SubtractiveBlending:
  13989. gl.blendFunc(0, 769);
  13990. break;
  13991. case MultiplyBlending:
  13992. gl.blendFunc(0, 768);
  13993. break;
  13994. default:
  13995. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13996. break;
  13997. }
  13998. }
  13999. currentBlendSrc = null;
  14000. currentBlendDst = null;
  14001. currentBlendSrcAlpha = null;
  14002. currentBlendDstAlpha = null;
  14003. currentBlending = blending;
  14004. currentPremultipledAlpha = premultipliedAlpha;
  14005. }
  14006. return;
  14007. } // custom blending
  14008. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14009. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14010. blendDstAlpha = blendDstAlpha || blendDst;
  14011. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  14012. gl.blendEquationSeparate(utils.convert(blendEquation), utils.convert(blendEquationAlpha));
  14013. currentBlendEquation = blendEquation;
  14014. currentBlendEquationAlpha = blendEquationAlpha;
  14015. }
  14016. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  14017. gl.blendFuncSeparate(utils.convert(blendSrc), utils.convert(blendDst), utils.convert(blendSrcAlpha), utils.convert(blendDstAlpha));
  14018. currentBlendSrc = blendSrc;
  14019. currentBlendDst = blendDst;
  14020. currentBlendSrcAlpha = blendSrcAlpha;
  14021. currentBlendDstAlpha = blendDstAlpha;
  14022. }
  14023. currentBlending = blending;
  14024. currentPremultipledAlpha = null;
  14025. }
  14026. function setMaterial(material, frontFaceCW) {
  14027. material.side === DoubleSide ? disable(2884) : enable(2884);
  14028. var flipSided = material.side === BackSide;
  14029. if (frontFaceCW) flipSided = !flipSided;
  14030. setFlipSided(flipSided);
  14031. 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);
  14032. depthBuffer.setFunc(material.depthFunc);
  14033. depthBuffer.setTest(material.depthTest);
  14034. depthBuffer.setMask(material.depthWrite);
  14035. colorBuffer.setMask(material.colorWrite);
  14036. var stencilWrite = material.stencilWrite;
  14037. stencilBuffer.setTest(stencilWrite);
  14038. if (stencilWrite) {
  14039. stencilBuffer.setMask(material.stencilWriteMask);
  14040. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  14041. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  14042. }
  14043. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  14044. } //
  14045. function setFlipSided(flipSided) {
  14046. if (currentFlipSided !== flipSided) {
  14047. if (flipSided) {
  14048. gl.frontFace(2304);
  14049. } else {
  14050. gl.frontFace(2305);
  14051. }
  14052. currentFlipSided = flipSided;
  14053. }
  14054. }
  14055. function setCullFace(cullFace) {
  14056. if (cullFace !== CullFaceNone) {
  14057. enable(2884);
  14058. if (cullFace !== currentCullFace) {
  14059. if (cullFace === CullFaceBack) {
  14060. gl.cullFace(1029);
  14061. } else if (cullFace === CullFaceFront) {
  14062. gl.cullFace(1028);
  14063. } else {
  14064. gl.cullFace(1032);
  14065. }
  14066. }
  14067. } else {
  14068. disable(2884);
  14069. }
  14070. currentCullFace = cullFace;
  14071. }
  14072. function setLineWidth(width) {
  14073. if (width !== currentLineWidth) {
  14074. if (lineWidthAvailable) gl.lineWidth(width);
  14075. currentLineWidth = width;
  14076. }
  14077. }
  14078. function setPolygonOffset(polygonOffset, factor, units) {
  14079. if (polygonOffset) {
  14080. enable(32823);
  14081. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  14082. gl.polygonOffset(factor, units);
  14083. currentPolygonOffsetFactor = factor;
  14084. currentPolygonOffsetUnits = units;
  14085. }
  14086. } else {
  14087. disable(32823);
  14088. }
  14089. }
  14090. function setScissorTest(scissorTest) {
  14091. if (scissorTest) {
  14092. enable(3089);
  14093. } else {
  14094. disable(3089);
  14095. }
  14096. } // texture
  14097. function activeTexture(webglSlot) {
  14098. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  14099. if (currentTextureSlot !== webglSlot) {
  14100. gl.activeTexture(webglSlot);
  14101. currentTextureSlot = webglSlot;
  14102. }
  14103. }
  14104. function bindTexture(webglType, webglTexture) {
  14105. if (currentTextureSlot === null) {
  14106. activeTexture();
  14107. }
  14108. var boundTexture = currentBoundTextures[currentTextureSlot];
  14109. if (boundTexture === undefined) {
  14110. boundTexture = {
  14111. type: undefined,
  14112. texture: undefined
  14113. };
  14114. currentBoundTextures[currentTextureSlot] = boundTexture;
  14115. }
  14116. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  14117. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  14118. boundTexture.type = webglType;
  14119. boundTexture.texture = webglTexture;
  14120. }
  14121. }
  14122. function compressedTexImage2D() {
  14123. try {
  14124. gl.compressedTexImage2D.apply(gl, arguments);
  14125. } catch (error) {
  14126. console.error('THREE.WebGLState:', error);
  14127. }
  14128. }
  14129. function texImage2D() {
  14130. try {
  14131. gl.texImage2D.apply(gl, arguments);
  14132. } catch (error) {
  14133. console.error('THREE.WebGLState:', error);
  14134. }
  14135. }
  14136. function texImage3D() {
  14137. try {
  14138. gl.texImage3D.apply(gl, arguments);
  14139. } catch (error) {
  14140. console.error('THREE.WebGLState:', error);
  14141. }
  14142. } //
  14143. function scissor(scissor) {
  14144. if (currentScissor.equals(scissor) === false) {
  14145. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  14146. currentScissor.copy(scissor);
  14147. }
  14148. }
  14149. function viewport(viewport) {
  14150. if (currentViewport.equals(viewport) === false) {
  14151. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  14152. currentViewport.copy(viewport);
  14153. }
  14154. } //
  14155. function reset() {
  14156. for (var i = 0; i < enabledAttributes.length; i++) {
  14157. if (enabledAttributes[i] === 1) {
  14158. gl.disableVertexAttribArray(i);
  14159. enabledAttributes[i] = 0;
  14160. }
  14161. }
  14162. enabledCapabilities = {};
  14163. compressedTextureFormats = null;
  14164. currentTextureSlot = null;
  14165. currentBoundTextures = {};
  14166. currentProgram = null;
  14167. currentBlending = null;
  14168. currentFlipSided = null;
  14169. currentCullFace = null;
  14170. colorBuffer.reset();
  14171. depthBuffer.reset();
  14172. stencilBuffer.reset();
  14173. }
  14174. return {
  14175. buffers: {
  14176. color: colorBuffer,
  14177. depth: depthBuffer,
  14178. stencil: stencilBuffer
  14179. },
  14180. initAttributes: initAttributes,
  14181. enableAttribute: enableAttribute,
  14182. enableAttributeAndDivisor: enableAttributeAndDivisor,
  14183. disableUnusedAttributes: disableUnusedAttributes,
  14184. enable: enable,
  14185. disable: disable,
  14186. getCompressedTextureFormats: getCompressedTextureFormats,
  14187. useProgram: useProgram,
  14188. setBlending: setBlending,
  14189. setMaterial: setMaterial,
  14190. setFlipSided: setFlipSided,
  14191. setCullFace: setCullFace,
  14192. setLineWidth: setLineWidth,
  14193. setPolygonOffset: setPolygonOffset,
  14194. setScissorTest: setScissorTest,
  14195. activeTexture: activeTexture,
  14196. bindTexture: bindTexture,
  14197. compressedTexImage2D: compressedTexImage2D,
  14198. texImage2D: texImage2D,
  14199. texImage3D: texImage3D,
  14200. scissor: scissor,
  14201. viewport: viewport,
  14202. reset: reset
  14203. };
  14204. }
  14205. /**
  14206. * @author mrdoob / http://mrdoob.com/
  14207. */
  14208. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  14209. var _videoTextures = new WeakMap();
  14210. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14211. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14212. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  14213. function createCanvas(width, height) {
  14214. // Use OffscreenCanvas when available. Specially needed in web workers
  14215. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14216. }
  14217. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  14218. var scale = 1; // handle case if texture exceeds max size
  14219. if (image.width > maxSize || image.height > maxSize) {
  14220. scale = maxSize / Math.max(image.width, image.height);
  14221. } // only perform resize if necessary
  14222. if (scale < 1 || needsPowerOfTwo === true) {
  14223. // only perform resize for certain image types
  14224. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  14225. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  14226. var width = floor(scale * image.width);
  14227. var height = floor(scale * image.height);
  14228. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  14229. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  14230. canvas.width = width;
  14231. canvas.height = height;
  14232. var context = canvas.getContext('2d');
  14233. context.drawImage(image, 0, 0, width, height);
  14234. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  14235. return canvas;
  14236. } else {
  14237. if ('data' in image) {
  14238. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  14239. }
  14240. return image;
  14241. }
  14242. }
  14243. return image;
  14244. }
  14245. function isPowerOfTwo(image) {
  14246. return _Math.isPowerOfTwo(image.width) && _Math.isPowerOfTwo(image.height);
  14247. }
  14248. function textureNeedsPowerOfTwo(texture) {
  14249. if (capabilities.isWebGL2) return false;
  14250. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14251. }
  14252. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  14253. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14254. }
  14255. function generateMipmap(target, texture, width, height) {
  14256. _gl.generateMipmap(target);
  14257. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  14258. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  14259. }
  14260. function getInternalFormat(glFormat, glType) {
  14261. if (!capabilities.isWebGL2) return glFormat;
  14262. var internalFormat = glFormat;
  14263. if (glFormat === 6403) {
  14264. if (glType === 5126) internalFormat = 33326;
  14265. if (glType === 5131) internalFormat = 33325;
  14266. if (glType === 5121) internalFormat = 33321;
  14267. }
  14268. if (glFormat === 6407) {
  14269. if (glType === 5126) internalFormat = 34837;
  14270. if (glType === 5131) internalFormat = 34843;
  14271. if (glType === 5121) internalFormat = 32849;
  14272. }
  14273. if (glFormat === 6408) {
  14274. if (glType === 5126) internalFormat = 34836;
  14275. if (glType === 5131) internalFormat = 34842;
  14276. if (glType === 5121) internalFormat = 32856;
  14277. }
  14278. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  14279. extensions.get('EXT_color_buffer_float');
  14280. } else if (internalFormat === 34843 || internalFormat === 34837) {
  14281. console.warn('THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.');
  14282. }
  14283. return internalFormat;
  14284. } // Fallback filters for non-power-of-2 textures
  14285. function filterFallback(f) {
  14286. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  14287. return 9728;
  14288. }
  14289. return 9729;
  14290. } //
  14291. function onTextureDispose(event) {
  14292. var texture = event.target;
  14293. texture.removeEventListener('dispose', onTextureDispose);
  14294. deallocateTexture(texture);
  14295. if (texture.isVideoTexture) {
  14296. _videoTextures.delete(texture);
  14297. }
  14298. info.memory.textures--;
  14299. }
  14300. function onRenderTargetDispose(event) {
  14301. var renderTarget = event.target;
  14302. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  14303. deallocateRenderTarget(renderTarget);
  14304. info.memory.textures--;
  14305. } //
  14306. function deallocateTexture(texture) {
  14307. var textureProperties = properties.get(texture);
  14308. if (textureProperties.__webglInit === undefined) return;
  14309. _gl.deleteTexture(textureProperties.__webglTexture);
  14310. properties.remove(texture);
  14311. }
  14312. function deallocateRenderTarget(renderTarget) {
  14313. var renderTargetProperties = properties.get(renderTarget);
  14314. var textureProperties = properties.get(renderTarget.texture);
  14315. if (!renderTarget) return;
  14316. if (textureProperties.__webglTexture !== undefined) {
  14317. _gl.deleteTexture(textureProperties.__webglTexture);
  14318. }
  14319. if (renderTarget.depthTexture) {
  14320. renderTarget.depthTexture.dispose();
  14321. }
  14322. if (renderTarget.isWebGLRenderTargetCube) {
  14323. for (var i = 0; i < 6; i++) {
  14324. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  14325. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  14326. }
  14327. } else {
  14328. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  14329. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  14330. }
  14331. if (renderTarget.isWebGLMultiviewRenderTarget) {
  14332. _gl.deleteTexture(renderTargetProperties.__webglColorTexture);
  14333. _gl.deleteTexture(renderTargetProperties.__webglDepthStencilTexture);
  14334. info.memory.textures -= 2;
  14335. for (var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i++) {
  14336. _gl.deleteFramebuffer(renderTargetProperties.__webglViewFramebuffers[i]);
  14337. }
  14338. }
  14339. properties.remove(renderTarget.texture);
  14340. properties.remove(renderTarget);
  14341. } //
  14342. var textureUnits = 0;
  14343. function resetTextureUnits() {
  14344. textureUnits = 0;
  14345. }
  14346. function allocateTextureUnit() {
  14347. var textureUnit = textureUnits;
  14348. if (textureUnit >= capabilities.maxTextures) {
  14349. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures);
  14350. }
  14351. textureUnits += 1;
  14352. return textureUnit;
  14353. } //
  14354. function setTexture2D(texture, slot) {
  14355. var textureProperties = properties.get(texture);
  14356. if (texture.isVideoTexture) updateVideoTexture(texture);
  14357. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14358. var image = texture.image;
  14359. if (image === undefined) {
  14360. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  14361. } else if (image.complete === false) {
  14362. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  14363. } else {
  14364. uploadTexture(textureProperties, texture, slot);
  14365. return;
  14366. }
  14367. }
  14368. state.activeTexture(33984 + slot);
  14369. state.bindTexture(3553, textureProperties.__webglTexture);
  14370. }
  14371. function setTexture2DArray(texture, slot) {
  14372. var textureProperties = properties.get(texture);
  14373. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14374. uploadTexture(textureProperties, texture, slot);
  14375. return;
  14376. }
  14377. state.activeTexture(33984 + slot);
  14378. state.bindTexture(35866, textureProperties.__webglTexture);
  14379. }
  14380. function setTexture3D(texture, slot) {
  14381. var textureProperties = properties.get(texture);
  14382. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14383. uploadTexture(textureProperties, texture, slot);
  14384. return;
  14385. }
  14386. state.activeTexture(33984 + slot);
  14387. state.bindTexture(32879, textureProperties.__webglTexture);
  14388. }
  14389. function setTextureCube(texture, slot) {
  14390. if (texture.image.length !== 6) return;
  14391. var textureProperties = properties.get(texture);
  14392. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14393. initTexture(textureProperties, texture);
  14394. state.activeTexture(33984 + slot);
  14395. state.bindTexture(34067, textureProperties.__webglTexture);
  14396. _gl.pixelStorei(37440, texture.flipY);
  14397. var isCompressed = texture && texture.isCompressedTexture;
  14398. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14399. var cubeImage = [];
  14400. for (var i = 0; i < 6; i++) {
  14401. if (!isCompressed && !isDataTexture) {
  14402. cubeImage[i] = resizeImage(texture.image[i], false, true, capabilities.maxCubemapSize);
  14403. } else {
  14404. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14405. }
  14406. }
  14407. var image = cubeImage[0],
  14408. supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14409. glFormat = utils.convert(texture.format),
  14410. glType = utils.convert(texture.type),
  14411. glInternalFormat = getInternalFormat(glFormat, glType);
  14412. setTextureParameters(34067, texture, supportsMips);
  14413. var mipmaps;
  14414. if (isCompressed) {
  14415. for (var i = 0; i < 6; i++) {
  14416. mipmaps = cubeImage[i].mipmaps;
  14417. for (var j = 0; j < mipmaps.length; j++) {
  14418. var mipmap = mipmaps[j];
  14419. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14420. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14421. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14422. } else {
  14423. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14424. }
  14425. } else {
  14426. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14427. }
  14428. }
  14429. }
  14430. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14431. } else {
  14432. mipmaps = texture.mipmaps;
  14433. for (var i = 0; i < 6; i++) {
  14434. if (isDataTexture) {
  14435. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14436. for (var j = 0; j < mipmaps.length; j++) {
  14437. var mipmap = mipmaps[j];
  14438. var mipmapImage = mipmap.image[i].image;
  14439. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14440. }
  14441. } else {
  14442. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14443. for (var j = 0; j < mipmaps.length; j++) {
  14444. var mipmap = mipmaps[j];
  14445. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14446. }
  14447. }
  14448. }
  14449. textureProperties.__maxMipLevel = mipmaps.length;
  14450. }
  14451. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14452. // We assume images for cube map have the same size.
  14453. generateMipmap(34067, texture, image.width, image.height);
  14454. }
  14455. textureProperties.__version = texture.version;
  14456. if (texture.onUpdate) texture.onUpdate(texture);
  14457. } else {
  14458. state.activeTexture(33984 + slot);
  14459. state.bindTexture(34067, textureProperties.__webglTexture);
  14460. }
  14461. }
  14462. function setTextureCubeDynamic(texture, slot) {
  14463. state.activeTexture(33984 + slot);
  14464. state.bindTexture(34067, properties.get(texture).__webglTexture);
  14465. }
  14466. function setTextureParameters(textureType, texture, supportsMips) {
  14467. var extension;
  14468. if (supportsMips) {
  14469. _gl.texParameteri(textureType, 10242, utils.convert(texture.wrapS));
  14470. _gl.texParameteri(textureType, 10243, utils.convert(texture.wrapT));
  14471. if (textureType === 32879 || textureType === 35866) {
  14472. _gl.texParameteri(textureType, 32882, utils.convert(texture.wrapR));
  14473. }
  14474. _gl.texParameteri(textureType, 10240, utils.convert(texture.magFilter));
  14475. _gl.texParameteri(textureType, 10241, utils.convert(texture.minFilter));
  14476. } else {
  14477. _gl.texParameteri(textureType, 10242, 33071);
  14478. _gl.texParameteri(textureType, 10243, 33071);
  14479. if (textureType === 32879 || textureType === 35866) {
  14480. _gl.texParameteri(textureType, 32882, 33071);
  14481. }
  14482. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  14483. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  14484. }
  14485. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  14486. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  14487. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  14488. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  14489. }
  14490. }
  14491. extension = extensions.get('EXT_texture_filter_anisotropic');
  14492. if (extension) {
  14493. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  14494. if (texture.type === HalfFloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  14495. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  14496. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  14497. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  14498. }
  14499. }
  14500. }
  14501. function initTexture(textureProperties, texture) {
  14502. if (textureProperties.__webglInit === undefined) {
  14503. textureProperties.__webglInit = true;
  14504. texture.addEventListener('dispose', onTextureDispose);
  14505. textureProperties.__webglTexture = _gl.createTexture();
  14506. info.memory.textures++;
  14507. }
  14508. }
  14509. function uploadTexture(textureProperties, texture, slot) {
  14510. var textureType = 3553;
  14511. if (texture.isDataTexture2DArray) textureType = 35866;
  14512. if (texture.isDataTexture3D) textureType = 32879;
  14513. initTexture(textureProperties, texture);
  14514. state.activeTexture(33984 + slot);
  14515. state.bindTexture(textureType, textureProperties.__webglTexture);
  14516. _gl.pixelStorei(37440, texture.flipY);
  14517. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  14518. _gl.pixelStorei(3317, texture.unpackAlignment);
  14519. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  14520. var image = resizeImage(texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize);
  14521. var supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14522. glFormat = utils.convert(texture.format),
  14523. glType = utils.convert(texture.type),
  14524. glInternalFormat = getInternalFormat(glFormat, glType);
  14525. setTextureParameters(textureType, texture, supportsMips);
  14526. var mipmap,
  14527. mipmaps = texture.mipmaps;
  14528. if (texture.isDepthTexture) {
  14529. // populate depth texture with dummy data
  14530. glInternalFormat = 6402;
  14531. if (texture.type === FloatType) {
  14532. if (!capabilities.isWebGL2) throw new Error('Float Depth Texture only supported in WebGL2.0');
  14533. glInternalFormat = 36012;
  14534. } else if (capabilities.isWebGL2) {
  14535. // WebGL 2.0 requires signed internalformat for glTexImage2D
  14536. glInternalFormat = 33189;
  14537. }
  14538. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  14539. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14540. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14541. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14542. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  14543. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  14544. texture.type = UnsignedShortType;
  14545. glType = utils.convert(texture.type);
  14546. }
  14547. } // Depth stencil textures need the DEPTH_STENCIL internal format
  14548. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14549. if (texture.format === DepthStencilFormat) {
  14550. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14551. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14552. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14553. if (texture.type !== UnsignedInt248Type) {
  14554. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  14555. texture.type = UnsignedInt248Type;
  14556. glType = utils.convert(texture.type);
  14557. }
  14558. }
  14559. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  14560. } else if (texture.isDataTexture) {
  14561. // use manually created mipmaps if available
  14562. // if there are no manual mipmaps
  14563. // set 0 level mipmap and then use GL to generate other mipmap levels
  14564. if (mipmaps.length > 0 && supportsMips) {
  14565. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14566. mipmap = mipmaps[i];
  14567. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14568. }
  14569. texture.generateMipmaps = false;
  14570. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14571. } else {
  14572. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  14573. textureProperties.__maxMipLevel = 0;
  14574. }
  14575. } else if (texture.isCompressedTexture) {
  14576. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14577. mipmap = mipmaps[i];
  14578. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14579. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14580. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14581. } else {
  14582. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14583. }
  14584. } else {
  14585. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14586. }
  14587. }
  14588. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14589. } else if (texture.isDataTexture2DArray) {
  14590. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14591. textureProperties.__maxMipLevel = 0;
  14592. } else if (texture.isDataTexture3D) {
  14593. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14594. textureProperties.__maxMipLevel = 0;
  14595. } else {
  14596. // regular Texture (image, video, canvas)
  14597. // use manually created mipmaps if available
  14598. // if there are no manual mipmaps
  14599. // set 0 level mipmap and then use GL to generate other mipmap levels
  14600. if (mipmaps.length > 0 && supportsMips) {
  14601. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14602. mipmap = mipmaps[i];
  14603. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  14604. }
  14605. texture.generateMipmaps = false;
  14606. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14607. } else {
  14608. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  14609. textureProperties.__maxMipLevel = 0;
  14610. }
  14611. }
  14612. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14613. generateMipmap(3553, texture, image.width, image.height);
  14614. }
  14615. textureProperties.__version = texture.version;
  14616. if (texture.onUpdate) texture.onUpdate(texture);
  14617. } // Render targets
  14618. // Setup storage for target texture and bind it to correct framebuffer
  14619. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  14620. var glFormat = utils.convert(renderTarget.texture.format);
  14621. var glType = utils.convert(renderTarget.texture.type);
  14622. var glInternalFormat = getInternalFormat(glFormat, glType);
  14623. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14624. _gl.bindFramebuffer(36160, framebuffer);
  14625. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  14626. _gl.bindFramebuffer(36160, null);
  14627. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14628. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14629. _gl.bindRenderbuffer(36161, renderbuffer);
  14630. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14631. if (isMultisample) {
  14632. var samples = getRenderTargetSamples(renderTarget);
  14633. _gl.renderbufferStorageMultisample(36161, samples, 33189, renderTarget.width, renderTarget.height);
  14634. } else {
  14635. _gl.renderbufferStorage(36161, 33189, renderTarget.width, renderTarget.height);
  14636. }
  14637. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  14638. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14639. if (isMultisample) {
  14640. var samples = getRenderTargetSamples(renderTarget);
  14641. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  14642. } else {
  14643. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  14644. }
  14645. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  14646. } else {
  14647. var glFormat = utils.convert(renderTarget.texture.format);
  14648. var glType = utils.convert(renderTarget.texture.type);
  14649. var glInternalFormat = getInternalFormat(glFormat, glType);
  14650. if (isMultisample) {
  14651. var samples = getRenderTargetSamples(renderTarget);
  14652. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14653. } else {
  14654. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  14655. }
  14656. }
  14657. _gl.bindRenderbuffer(36161, null);
  14658. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14659. function setupDepthTexture(framebuffer, renderTarget) {
  14660. var isCube = renderTarget && renderTarget.isWebGLRenderTargetCube;
  14661. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14662. _gl.bindFramebuffer(36160, framebuffer);
  14663. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14664. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14665. } // upload an empty depth texture with framebuffer size
  14666. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14667. renderTarget.depthTexture.image.width = renderTarget.width;
  14668. renderTarget.depthTexture.image.height = renderTarget.height;
  14669. renderTarget.depthTexture.needsUpdate = true;
  14670. }
  14671. setTexture2D(renderTarget.depthTexture, 0);
  14672. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14673. if (renderTarget.depthTexture.format === DepthFormat) {
  14674. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  14675. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14676. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  14677. } else {
  14678. throw new Error('Unknown depthTexture format');
  14679. }
  14680. } // Setup GL resources for a non-texture depth buffer
  14681. function setupDepthRenderbuffer(renderTarget) {
  14682. var renderTargetProperties = properties.get(renderTarget);
  14683. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14684. if (renderTarget.depthTexture) {
  14685. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14686. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14687. } else {
  14688. if (isCube) {
  14689. renderTargetProperties.__webglDepthbuffer = [];
  14690. for (var i = 0; i < 6; i++) {
  14691. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  14692. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14693. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget);
  14694. }
  14695. } else {
  14696. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14697. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14698. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget);
  14699. }
  14700. }
  14701. _gl.bindFramebuffer(36160, null);
  14702. } // Set up GL resources for the render target
  14703. function setupRenderTarget(renderTarget) {
  14704. var renderTargetProperties = properties.get(renderTarget);
  14705. var textureProperties = properties.get(renderTarget.texture);
  14706. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14707. textureProperties.__webglTexture = _gl.createTexture();
  14708. info.memory.textures++;
  14709. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14710. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  14711. var isMultiview = renderTarget.isWebGLMultiviewRenderTarget === true;
  14712. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2; // Setup framebuffer
  14713. if (isCube) {
  14714. renderTargetProperties.__webglFramebuffer = [];
  14715. for (var i = 0; i < 6; i++) {
  14716. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14717. }
  14718. } else {
  14719. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14720. if (isMultisample) {
  14721. if (capabilities.isWebGL2) {
  14722. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14723. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14724. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  14725. var glFormat = utils.convert(renderTarget.texture.format);
  14726. var glType = utils.convert(renderTarget.texture.type);
  14727. var glInternalFormat = getInternalFormat(glFormat, glType);
  14728. var samples = getRenderTargetSamples(renderTarget);
  14729. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14730. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  14731. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  14732. _gl.bindRenderbuffer(36161, null);
  14733. if (renderTarget.depthBuffer) {
  14734. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14735. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14736. }
  14737. _gl.bindFramebuffer(36160, null);
  14738. } else {
  14739. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14740. }
  14741. } else if (isMultiview) {
  14742. var width = renderTarget.width;
  14743. var height = renderTarget.height;
  14744. var numViews = renderTarget.numViews;
  14745. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14746. var ext = extensions.get('OVR_multiview2');
  14747. info.memory.textures += 2;
  14748. var colorTexture = _gl.createTexture();
  14749. _gl.bindTexture(35866, colorTexture);
  14750. _gl.texParameteri(35866, 10240, 9728);
  14751. _gl.texParameteri(35866, 10241, 9728);
  14752. _gl.texImage3D(35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null);
  14753. ext.framebufferTextureMultiviewOVR(36160, 36064, colorTexture, 0, 0, numViews);
  14754. var depthStencilTexture = _gl.createTexture();
  14755. _gl.bindTexture(35866, depthStencilTexture);
  14756. _gl.texParameteri(35866, 10240, 9728);
  14757. _gl.texParameteri(35866, 10241, 9728);
  14758. _gl.texImage3D(35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null);
  14759. ext.framebufferTextureMultiviewOVR(36160, 33306, depthStencilTexture, 0, 0, numViews);
  14760. var viewFramebuffers = new Array(numViews);
  14761. for (var i = 0; i < numViews; ++i) {
  14762. viewFramebuffers[i] = _gl.createFramebuffer();
  14763. _gl.bindFramebuffer(36160, viewFramebuffers[i]);
  14764. _gl.framebufferTextureLayer(36160, 36064, colorTexture, 0, i);
  14765. }
  14766. renderTargetProperties.__webglColorTexture = colorTexture;
  14767. renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
  14768. renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;
  14769. _gl.bindFramebuffer(36160, null);
  14770. _gl.bindTexture(35866, null);
  14771. }
  14772. } // Setup color buffer
  14773. if (isCube) {
  14774. state.bindTexture(34067, textureProperties.__webglTexture);
  14775. setTextureParameters(34067, renderTarget.texture, supportsMips);
  14776. for (var i = 0; i < 6; i++) {
  14777. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  14778. }
  14779. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14780. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  14781. }
  14782. state.bindTexture(34067, null);
  14783. } else if (!isMultiview) {
  14784. state.bindTexture(3553, textureProperties.__webglTexture);
  14785. setTextureParameters(3553, renderTarget.texture, supportsMips);
  14786. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  14787. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14788. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  14789. }
  14790. state.bindTexture(3553, null);
  14791. } // Setup depth and stencil buffers
  14792. if (renderTarget.depthBuffer) {
  14793. setupDepthRenderbuffer(renderTarget);
  14794. }
  14795. }
  14796. function updateRenderTargetMipmap(renderTarget) {
  14797. var texture = renderTarget.texture;
  14798. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2;
  14799. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14800. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  14801. var webglTexture = properties.get(texture).__webglTexture;
  14802. state.bindTexture(target, webglTexture);
  14803. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  14804. state.bindTexture(target, null);
  14805. }
  14806. }
  14807. function updateMultisampleRenderTarget(renderTarget) {
  14808. if (renderTarget.isWebGLMultisampleRenderTarget) {
  14809. if (capabilities.isWebGL2) {
  14810. var renderTargetProperties = properties.get(renderTarget);
  14811. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  14812. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  14813. var width = renderTarget.width;
  14814. var height = renderTarget.height;
  14815. var mask = 16384;
  14816. if (renderTarget.depthBuffer) mask |= 256;
  14817. if (renderTarget.stencilBuffer) mask |= 1024;
  14818. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  14819. } else {
  14820. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14821. }
  14822. }
  14823. }
  14824. function getRenderTargetSamples(renderTarget) {
  14825. return capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(capabilities.maxSamples, renderTarget.samples) : 0;
  14826. }
  14827. function updateVideoTexture(texture) {
  14828. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14829. if (_videoTextures.get(texture) !== frame) {
  14830. _videoTextures.set(texture, frame);
  14831. texture.update();
  14832. }
  14833. } // backwards compatibility
  14834. var warnedTexture2D = false;
  14835. var warnedTextureCube = false;
  14836. function safeSetTexture2D(texture, slot) {
  14837. if (texture && texture.isWebGLRenderTarget) {
  14838. if (warnedTexture2D === false) {
  14839. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  14840. warnedTexture2D = true;
  14841. }
  14842. texture = texture.texture;
  14843. }
  14844. setTexture2D(texture, slot);
  14845. }
  14846. function safeSetTextureCube(texture, slot) {
  14847. if (texture && texture.isWebGLRenderTargetCube) {
  14848. if (warnedTextureCube === false) {
  14849. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  14850. warnedTextureCube = true;
  14851. }
  14852. texture = texture.texture;
  14853. } // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  14854. // TODO: unify these code paths
  14855. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  14856. // CompressedTexture can have Array in image :/
  14857. // this function alone should take care of cube textures
  14858. setTextureCube(texture, slot);
  14859. } else {
  14860. // assumed: texture property of THREE.WebGLRenderTargetCube
  14861. setTextureCubeDynamic(texture, slot);
  14862. }
  14863. } //
  14864. this.allocateTextureUnit = allocateTextureUnit;
  14865. this.resetTextureUnits = resetTextureUnits;
  14866. this.setTexture2D = setTexture2D;
  14867. this.setTexture2DArray = setTexture2DArray;
  14868. this.setTexture3D = setTexture3D;
  14869. this.setTextureCube = setTextureCube;
  14870. this.setTextureCubeDynamic = setTextureCubeDynamic;
  14871. this.setupRenderTarget = setupRenderTarget;
  14872. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14873. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14874. this.safeSetTexture2D = safeSetTexture2D;
  14875. this.safeSetTextureCube = safeSetTextureCube;
  14876. }
  14877. /**
  14878. * @author thespite / http://www.twitter.com/thespite
  14879. */
  14880. function WebGLUtils(gl, extensions, capabilities) {
  14881. function convert(p) {
  14882. var extension;
  14883. if (p === RepeatWrapping) return 10497;
  14884. if (p === ClampToEdgeWrapping) return 33071;
  14885. if (p === MirroredRepeatWrapping) return 33648;
  14886. if (p === NearestFilter) return 9728;
  14887. if (p === NearestMipmapNearestFilter) return 9984;
  14888. if (p === NearestMipmapLinearFilter) return 9986;
  14889. if (p === LinearFilter) return 9729;
  14890. if (p === LinearMipmapNearestFilter) return 9985;
  14891. if (p === LinearMipmapLinearFilter) return 9987;
  14892. if (p === UnsignedByteType) return 5121;
  14893. if (p === UnsignedShort4444Type) return 32819;
  14894. if (p === UnsignedShort5551Type) return 32820;
  14895. if (p === UnsignedShort565Type) return 33635;
  14896. if (p === ByteType) return 5120;
  14897. if (p === ShortType) return 5122;
  14898. if (p === UnsignedShortType) return 5123;
  14899. if (p === IntType) return 5124;
  14900. if (p === UnsignedIntType) return 5125;
  14901. if (p === FloatType) return 5126;
  14902. if (p === HalfFloatType) {
  14903. if (capabilities.isWebGL2) return 5131;
  14904. extension = extensions.get('OES_texture_half_float');
  14905. if (extension !== null) return extension.HALF_FLOAT_OES;
  14906. }
  14907. if (p === AlphaFormat) return 6406;
  14908. if (p === RGBFormat) return 6407;
  14909. if (p === RGBAFormat) return 6408;
  14910. if (p === LuminanceFormat) return 6409;
  14911. if (p === LuminanceAlphaFormat) return 6410;
  14912. if (p === DepthFormat) return 6402;
  14913. if (p === DepthStencilFormat) return 34041;
  14914. if (p === RedFormat) return 6403;
  14915. if (p === AddEquation) return 32774;
  14916. if (p === SubtractEquation) return 32778;
  14917. if (p === ReverseSubtractEquation) return 32779;
  14918. if (p === ZeroFactor) return 0;
  14919. if (p === OneFactor) return 1;
  14920. if (p === SrcColorFactor) return 768;
  14921. if (p === OneMinusSrcColorFactor) return 769;
  14922. if (p === SrcAlphaFactor) return 770;
  14923. if (p === OneMinusSrcAlphaFactor) return 771;
  14924. if (p === DstAlphaFactor) return 772;
  14925. if (p === OneMinusDstAlphaFactor) return 773;
  14926. if (p === DstColorFactor) return 774;
  14927. if (p === OneMinusDstColorFactor) return 775;
  14928. if (p === SrcAlphaSaturateFactor) return 776;
  14929. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14930. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14931. if (extension !== null) {
  14932. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14933. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14934. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14935. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14936. }
  14937. }
  14938. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14939. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14940. if (extension !== null) {
  14941. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14942. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14943. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14944. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14945. }
  14946. }
  14947. if (p === RGB_ETC1_Format) {
  14948. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14949. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14950. }
  14951. 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) {
  14952. extension = extensions.get('WEBGL_compressed_texture_astc');
  14953. if (extension !== null) {
  14954. return p;
  14955. }
  14956. }
  14957. if (p === MinEquation || p === MaxEquation) {
  14958. if (capabilities.isWebGL2) {
  14959. if (p === MinEquation) return 32775;
  14960. if (p === MaxEquation) return 32776;
  14961. }
  14962. extension = extensions.get('EXT_blend_minmax');
  14963. if (extension !== null) {
  14964. if (p === MinEquation) return extension.MIN_EXT;
  14965. if (p === MaxEquation) return extension.MAX_EXT;
  14966. }
  14967. }
  14968. if (p === UnsignedInt248Type) {
  14969. if (capabilities.isWebGL2) return 34042;
  14970. extension = extensions.get('WEBGL_depth_texture');
  14971. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  14972. }
  14973. return 0;
  14974. }
  14975. return {
  14976. convert: convert
  14977. };
  14978. }
  14979. /**
  14980. * @author fernandojsg / http://fernandojsg.com
  14981. * @author Takahiro https://github.com/takahirox
  14982. */
  14983. function WebGLMultiviewRenderTarget(width, height, numViews, options) {
  14984. WebGLRenderTarget.call(this, width, height, options);
  14985. this.depthBuffer = false;
  14986. this.stencilBuffer = false;
  14987. this.numViews = numViews;
  14988. }
  14989. WebGLMultiviewRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  14990. constructor: WebGLMultiviewRenderTarget,
  14991. isWebGLMultiviewRenderTarget: true,
  14992. copy: function (source) {
  14993. WebGLRenderTarget.prototype.copy.call(this, source);
  14994. this.numViews = source.numViews;
  14995. return this;
  14996. },
  14997. setNumViews: function (numViews) {
  14998. if (this.numViews !== numViews) {
  14999. this.numViews = numViews;
  15000. this.dispose();
  15001. }
  15002. return this;
  15003. }
  15004. });
  15005. /**
  15006. * @author fernandojsg / http://fernandojsg.com
  15007. * @author Takahiro https://github.com/takahirox
  15008. */
  15009. function WebGLMultiview(renderer, gl) {
  15010. var DEFAULT_NUMVIEWS = 2;
  15011. var extensions = renderer.extensions;
  15012. var properties = renderer.properties;
  15013. var renderTarget, currentRenderTarget;
  15014. var mat3, mat4, cameraArray, renderSize;
  15015. var available;
  15016. var maxNumViews = 0; //
  15017. function isAvailable() {
  15018. if (available === undefined) {
  15019. var extension = extensions.get('OVR_multiview2');
  15020. available = extension !== null && gl.getContextAttributes().antialias === false;
  15021. if (available) {
  15022. maxNumViews = gl.getParameter(extension.MAX_VIEWS_OVR);
  15023. renderTarget = new WebGLMultiviewRenderTarget(0, 0, DEFAULT_NUMVIEWS);
  15024. renderSize = new Vector2();
  15025. mat4 = [];
  15026. mat3 = [];
  15027. cameraArray = [];
  15028. for (var i = 0; i < maxNumViews; i++) {
  15029. mat4[i] = new Matrix4();
  15030. mat3[i] = new Matrix3();
  15031. }
  15032. }
  15033. }
  15034. return available;
  15035. }
  15036. function getCameraArray(camera) {
  15037. if (camera.isArrayCamera) return camera.cameras;
  15038. cameraArray[0] = camera;
  15039. return cameraArray;
  15040. }
  15041. function updateCameraProjectionMatricesUniform(camera, uniforms) {
  15042. var cameras = getCameraArray(camera);
  15043. for (var i = 0; i < cameras.length; i++) {
  15044. mat4[i].copy(cameras[i].projectionMatrix);
  15045. }
  15046. uniforms.setValue(gl, 'projectionMatrices', mat4);
  15047. }
  15048. function updateCameraViewMatricesUniform(camera, uniforms) {
  15049. var cameras = getCameraArray(camera);
  15050. for (var i = 0; i < cameras.length; i++) {
  15051. mat4[i].copy(cameras[i].matrixWorldInverse);
  15052. }
  15053. uniforms.setValue(gl, 'viewMatrices', mat4);
  15054. }
  15055. function updateObjectMatricesUniforms(object, camera, uniforms) {
  15056. var cameras = getCameraArray(camera);
  15057. for (var i = 0; i < cameras.length; i++) {
  15058. mat4[i].multiplyMatrices(cameras[i].matrixWorldInverse, object.matrixWorld);
  15059. mat3[i].getNormalMatrix(mat4[i]);
  15060. }
  15061. uniforms.setValue(gl, 'modelViewMatrices', mat4);
  15062. uniforms.setValue(gl, 'normalMatrices', mat3);
  15063. }
  15064. function isMultiviewCompatible(camera) {
  15065. if (camera.isArrayCamera === undefined) return true;
  15066. var cameras = camera.cameras;
  15067. if (cameras.length > maxNumViews) return false;
  15068. for (var i = 1, il = cameras.length; i < il; i++) {
  15069. if (cameras[0].viewport.z !== cameras[i].viewport.z || cameras[0].viewport.w !== cameras[i].viewport.w) return false;
  15070. }
  15071. return true;
  15072. }
  15073. function resizeRenderTarget(camera) {
  15074. if (currentRenderTarget) {
  15075. renderSize.set(currentRenderTarget.width, currentRenderTarget.height);
  15076. } else {
  15077. renderer.getDrawingBufferSize(renderSize);
  15078. }
  15079. if (camera.isArrayCamera) {
  15080. var viewport = camera.cameras[0].viewport;
  15081. renderTarget.setSize(viewport.z, viewport.w);
  15082. renderTarget.setNumViews(camera.cameras.length);
  15083. } else {
  15084. renderTarget.setSize(renderSize.x, renderSize.y);
  15085. renderTarget.setNumViews(DEFAULT_NUMVIEWS);
  15086. }
  15087. }
  15088. function attachCamera(camera) {
  15089. if (isMultiviewCompatible(camera) === false) return;
  15090. currentRenderTarget = renderer.getRenderTarget();
  15091. resizeRenderTarget(camera);
  15092. renderer.setRenderTarget(renderTarget);
  15093. }
  15094. function detachCamera(camera) {
  15095. if (renderTarget !== renderer.getRenderTarget()) return;
  15096. renderer.setRenderTarget(currentRenderTarget);
  15097. flush(camera);
  15098. }
  15099. function flush(camera) {
  15100. var srcRenderTarget = renderTarget;
  15101. var numViews = srcRenderTarget.numViews;
  15102. var srcFramebuffers = properties.get(srcRenderTarget).__webglViewFramebuffers;
  15103. var viewWidth = srcRenderTarget.width;
  15104. var viewHeight = srcRenderTarget.height;
  15105. if (camera.isArrayCamera) {
  15106. for (var i = 0; i < numViews; i++) {
  15107. var viewport = camera.cameras[i].viewport;
  15108. var x1 = viewport.x;
  15109. var y1 = viewport.y;
  15110. var x2 = x1 + viewport.z;
  15111. var y2 = y1 + viewport.w;
  15112. gl.bindFramebuffer(36008, srcFramebuffers[i]);
  15113. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728);
  15114. }
  15115. } else {
  15116. gl.bindFramebuffer(36008, srcFramebuffers[0]);
  15117. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728);
  15118. }
  15119. }
  15120. this.isAvailable = isAvailable;
  15121. this.attachCamera = attachCamera;
  15122. this.detachCamera = detachCamera;
  15123. this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
  15124. this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
  15125. this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;
  15126. }
  15127. /**
  15128. * @author mrdoob / http://mrdoob.com/
  15129. */
  15130. function Group() {
  15131. Object3D.call(this);
  15132. this.type = 'Group';
  15133. }
  15134. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  15135. constructor: Group,
  15136. isGroup: true
  15137. });
  15138. /**
  15139. * @author mrdoob / http://mrdoob.com/
  15140. */
  15141. function ArrayCamera(array) {
  15142. PerspectiveCamera.call(this);
  15143. this.cameras = array || [];
  15144. }
  15145. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  15146. constructor: ArrayCamera,
  15147. isArrayCamera: true
  15148. });
  15149. /**
  15150. * @author jsantell / https://www.jsantell.com/
  15151. * @author mrdoob / http://mrdoob.com/
  15152. */
  15153. var cameraLPos = new Vector3();
  15154. var cameraRPos = new Vector3();
  15155. /**
  15156. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15157. * the cameras' projection and world matrices have already been set.
  15158. * And that near and far planes are identical for both cameras.
  15159. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15160. */
  15161. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15162. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15163. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15164. var ipd = cameraLPos.distanceTo(cameraRPos);
  15165. var projL = cameraL.projectionMatrix.elements;
  15166. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15167. // most likely identical top and bottom frustum extents.
  15168. // Use the left camera for these values.
  15169. var near = projL[14] / (projL[10] - 1);
  15170. var far = projL[14] / (projL[10] + 1);
  15171. var topFov = (projL[9] + 1) / projL[5];
  15172. var bottomFov = (projL[9] - 1) / projL[5];
  15173. var leftFov = (projL[8] - 1) / projL[0];
  15174. var rightFov = (projR[8] + 1) / projR[0];
  15175. var left = near * leftFov;
  15176. var right = near * rightFov; // Calculate the new camera's position offset from the
  15177. // left camera. xOffset should be roughly half `ipd`.
  15178. var zOffset = ipd / (-leftFov + rightFov);
  15179. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15180. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15181. camera.translateX(xOffset);
  15182. camera.translateZ(zOffset);
  15183. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15184. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  15185. // the values so that the near plane's position does not change in world space,
  15186. // although must now be relative to the new union camera.
  15187. var near2 = near + zOffset;
  15188. var far2 = far + zOffset;
  15189. var left2 = left - xOffset;
  15190. var right2 = right + (ipd - xOffset);
  15191. var top2 = topFov * far / far2 * near2;
  15192. var bottom2 = bottomFov * far / far2 * near2;
  15193. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15194. }
  15195. /**
  15196. * @author mrdoob / http://mrdoob.com/
  15197. */
  15198. function WebVRManager(renderer) {
  15199. var renderWidth, renderHeight;
  15200. var scope = this;
  15201. var device = null;
  15202. var frameData = null;
  15203. var poseTarget = null;
  15204. var controllers = [];
  15205. var standingMatrix = new Matrix4();
  15206. var standingMatrixInverse = new Matrix4();
  15207. var framebufferScaleFactor = 1.0;
  15208. var referenceSpaceType = 'local-floor';
  15209. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  15210. frameData = new window.VRFrameData();
  15211. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  15212. }
  15213. var matrixWorldInverse = new Matrix4();
  15214. var tempQuaternion = new Quaternion();
  15215. var tempPosition = new Vector3();
  15216. var cameraL = new PerspectiveCamera();
  15217. cameraL.viewport = new Vector4();
  15218. cameraL.layers.enable(1);
  15219. var cameraR = new PerspectiveCamera();
  15220. cameraR.viewport = new Vector4();
  15221. cameraR.layers.enable(2);
  15222. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15223. cameraVR.layers.enable(1);
  15224. cameraVR.layers.enable(2); //
  15225. function isPresenting() {
  15226. return device !== null && device.isPresenting === true;
  15227. }
  15228. var currentSize = new Vector2(),
  15229. currentPixelRatio;
  15230. function onVRDisplayPresentChange() {
  15231. if (isPresenting()) {
  15232. var eyeParameters = device.getEyeParameters('left');
  15233. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  15234. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  15235. currentPixelRatio = renderer.getPixelRatio();
  15236. renderer.getSize(currentSize);
  15237. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  15238. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  15239. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  15240. animation.start();
  15241. scope.dispatchEvent({
  15242. type: 'sessionstart'
  15243. });
  15244. } else {
  15245. if (scope.enabled) {
  15246. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  15247. }
  15248. animation.stop();
  15249. scope.dispatchEvent({
  15250. type: 'sessionend'
  15251. });
  15252. }
  15253. } //
  15254. var triggers = [];
  15255. function findGamepad(id) {
  15256. var gamepads = navigator.getGamepads && navigator.getGamepads();
  15257. for (var i = 0, j = 0, l = gamepads.length; i < l; i++) {
  15258. var gamepad = gamepads[i];
  15259. if (gamepad && (gamepad.id === 'Daydream Controller' || gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' || gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith('Oculus Touch') || gamepad.id.startsWith('HTC Vive Focus') || gamepad.id.startsWith('Spatial Controller'))) {
  15260. if (j === id) return gamepad;
  15261. j++;
  15262. }
  15263. }
  15264. }
  15265. function updateControllers() {
  15266. for (var i = 0; i < controllers.length; i++) {
  15267. var controller = controllers[i];
  15268. var gamepad = findGamepad(i);
  15269. if (gamepad !== undefined && gamepad.pose !== undefined) {
  15270. if (gamepad.pose === null) return; // Pose
  15271. var pose = gamepad.pose;
  15272. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  15273. if (pose.position !== null) controller.position.fromArray(pose.position);
  15274. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  15275. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  15276. controller.matrix.premultiply(standingMatrix);
  15277. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  15278. controller.matrixWorldNeedsUpdate = true;
  15279. controller.visible = true; // Trigger
  15280. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  15281. if (triggers[i] === undefined) triggers[i] = false;
  15282. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  15283. triggers[i] = gamepad.buttons[buttonId].pressed;
  15284. if (triggers[i] === true) {
  15285. controller.dispatchEvent({
  15286. type: 'selectstart'
  15287. });
  15288. } else {
  15289. controller.dispatchEvent({
  15290. type: 'selectend'
  15291. });
  15292. controller.dispatchEvent({
  15293. type: 'select'
  15294. });
  15295. }
  15296. }
  15297. } else {
  15298. controller.visible = false;
  15299. }
  15300. }
  15301. }
  15302. function updateViewportFromBounds(viewport, bounds) {
  15303. if (bounds !== null && bounds.length === 4) {
  15304. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  15305. }
  15306. } //
  15307. this.enabled = false;
  15308. this.getController = function (id) {
  15309. var controller = controllers[id];
  15310. if (controller === undefined) {
  15311. controller = new Group();
  15312. controller.matrixAutoUpdate = false;
  15313. controller.visible = false;
  15314. controllers[id] = controller;
  15315. }
  15316. return controller;
  15317. };
  15318. this.getDevice = function () {
  15319. return device;
  15320. };
  15321. this.setDevice = function (value) {
  15322. if (value !== undefined) device = value;
  15323. animation.setContext(value);
  15324. };
  15325. this.setFramebufferScaleFactor = function (value) {
  15326. framebufferScaleFactor = value;
  15327. };
  15328. this.setReferenceSpaceType = function (value) {
  15329. referenceSpaceType = value;
  15330. };
  15331. this.setPoseTarget = function (object) {
  15332. if (object !== undefined) poseTarget = object;
  15333. };
  15334. this.getCamera = function (camera) {
  15335. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  15336. if (isPresenting() === false) {
  15337. camera.position.set(0, userHeight, 0);
  15338. camera.rotation.set(0, 0, 0);
  15339. return camera;
  15340. }
  15341. device.depthNear = camera.near;
  15342. device.depthFar = camera.far;
  15343. device.getFrameData(frameData); //
  15344. if (referenceSpaceType === 'local-floor') {
  15345. var stageParameters = device.stageParameters;
  15346. if (stageParameters) {
  15347. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  15348. } else {
  15349. standingMatrix.makeTranslation(0, userHeight, 0);
  15350. }
  15351. }
  15352. var pose = frameData.pose;
  15353. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  15354. poseObject.matrix.copy(standingMatrix);
  15355. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  15356. if (pose.orientation !== null) {
  15357. tempQuaternion.fromArray(pose.orientation);
  15358. poseObject.quaternion.multiply(tempQuaternion);
  15359. }
  15360. if (pose.position !== null) {
  15361. tempQuaternion.setFromRotationMatrix(standingMatrix);
  15362. tempPosition.fromArray(pose.position);
  15363. tempPosition.applyQuaternion(tempQuaternion);
  15364. poseObject.position.add(tempPosition);
  15365. }
  15366. poseObject.updateMatrixWorld(); //
  15367. cameraL.near = camera.near;
  15368. cameraR.near = camera.near;
  15369. cameraL.far = camera.far;
  15370. cameraR.far = camera.far;
  15371. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  15372. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  15373. standingMatrixInverse.getInverse(standingMatrix);
  15374. if (referenceSpaceType === 'local-floor') {
  15375. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  15376. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  15377. }
  15378. var parent = poseObject.parent;
  15379. if (parent !== null) {
  15380. matrixWorldInverse.getInverse(parent.matrixWorld);
  15381. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  15382. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  15383. } // envMap and Mirror needs camera.matrixWorld
  15384. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  15385. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  15386. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  15387. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  15388. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  15389. var layers = device.getLayers();
  15390. if (layers.length) {
  15391. var layer = layers[0];
  15392. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  15393. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  15394. }
  15395. updateControllers();
  15396. return cameraVR;
  15397. };
  15398. this.getStandingMatrix = function () {
  15399. return standingMatrix;
  15400. };
  15401. this.isPresenting = isPresenting; // Animation Loop
  15402. var animation = new WebGLAnimation();
  15403. this.setAnimationLoop = function (callback) {
  15404. animation.setAnimationLoop(callback);
  15405. if (isPresenting()) animation.start();
  15406. };
  15407. this.submitFrame = function () {
  15408. if (isPresenting()) device.submitFrame();
  15409. };
  15410. this.dispose = function () {
  15411. if (typeof window !== 'undefined') {
  15412. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  15413. }
  15414. }; // DEPRECATED
  15415. this.setFrameOfReferenceType = function () {
  15416. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  15417. };
  15418. }
  15419. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  15420. /**
  15421. * @author mrdoob / http://mrdoob.com/
  15422. */
  15423. function WebXRManager(renderer, gl) {
  15424. var scope = this;
  15425. var session = null; // var framebufferScaleFactor = 1.0;
  15426. var referenceSpace = null;
  15427. var referenceSpaceType = 'local-floor';
  15428. var pose = null;
  15429. var controllers = [];
  15430. var inputSources = [];
  15431. function isPresenting() {
  15432. return session !== null && referenceSpace !== null;
  15433. } //
  15434. var cameraL = new PerspectiveCamera();
  15435. cameraL.layers.enable(1);
  15436. cameraL.viewport = new Vector4();
  15437. var cameraR = new PerspectiveCamera();
  15438. cameraR.layers.enable(2);
  15439. cameraR.viewport = new Vector4();
  15440. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15441. cameraVR.layers.enable(1);
  15442. cameraVR.layers.enable(2); //
  15443. this.enabled = false;
  15444. this.getController = function (id) {
  15445. var controller = controllers[id];
  15446. if (controller === undefined) {
  15447. controller = new Group();
  15448. controller.matrixAutoUpdate = false;
  15449. controller.visible = false;
  15450. controllers[id] = controller;
  15451. }
  15452. return controller;
  15453. }; //
  15454. function onSessionEvent(event) {
  15455. for (var i = 0; i < controllers.length; i++) {
  15456. if (inputSources[i] === event.inputSource) {
  15457. controllers[i].dispatchEvent({
  15458. type: event.type
  15459. });
  15460. }
  15461. }
  15462. }
  15463. function onSessionEnd() {
  15464. renderer.setFramebuffer(null);
  15465. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  15466. animation.stop();
  15467. scope.dispatchEvent({
  15468. type: 'sessionend'
  15469. });
  15470. }
  15471. function onRequestReferenceSpace(value) {
  15472. referenceSpace = value;
  15473. animation.setContext(session);
  15474. animation.start();
  15475. scope.dispatchEvent({
  15476. type: 'sessionstart'
  15477. });
  15478. }
  15479. this.setFramebufferScaleFactor = function ()
  15480. /* value */
  15481. {// framebufferScaleFactor = value;
  15482. };
  15483. this.setReferenceSpaceType = function (value) {
  15484. referenceSpaceType = value;
  15485. };
  15486. this.getSession = function () {
  15487. return session;
  15488. };
  15489. this.setSession = function (value) {
  15490. session = value;
  15491. if (session !== null) {
  15492. session.addEventListener('select', onSessionEvent);
  15493. session.addEventListener('selectstart', onSessionEvent);
  15494. session.addEventListener('selectend', onSessionEvent);
  15495. session.addEventListener('end', onSessionEnd); // eslint-disable-next-line no-undef
  15496. session.updateRenderState({
  15497. baseLayer: new XRWebGLLayer(session, gl)
  15498. });
  15499. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  15500. inputSources = session.inputSources;
  15501. session.addEventListener('inputsourceschange', function () {
  15502. inputSources = session.inputSources;
  15503. console.log(inputSources);
  15504. for (var i = 0; i < controllers.length; i++) {
  15505. var controller = controllers[i];
  15506. controller.userData.inputSource = inputSources[i];
  15507. }
  15508. });
  15509. }
  15510. };
  15511. function updateCamera(camera, parent) {
  15512. if (parent === null) {
  15513. camera.matrixWorld.copy(camera.matrix);
  15514. } else {
  15515. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15516. }
  15517. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  15518. }
  15519. this.getCamera = function (camera) {
  15520. if (isPresenting()) {
  15521. var parent = camera.parent;
  15522. var cameras = cameraVR.cameras;
  15523. updateCamera(cameraVR, parent);
  15524. for (var i = 0; i < cameras.length; i++) {
  15525. updateCamera(cameras[i], parent);
  15526. } // update camera and its children
  15527. camera.matrixWorld.copy(cameraVR.matrixWorld);
  15528. var children = camera.children;
  15529. for (var i = 0, l = children.length; i < l; i++) {
  15530. children[i].updateMatrixWorld(true);
  15531. }
  15532. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15533. return cameraVR;
  15534. }
  15535. return camera;
  15536. };
  15537. this.isPresenting = isPresenting; // Animation Loop
  15538. var onAnimationFrameCallback = null;
  15539. function onAnimationFrame(time, frame) {
  15540. pose = frame.getViewerPose(referenceSpace);
  15541. if (pose !== null) {
  15542. var views = pose.views;
  15543. var baseLayer = session.renderState.baseLayer;
  15544. renderer.setFramebuffer(baseLayer.framebuffer);
  15545. for (var i = 0; i < views.length; i++) {
  15546. var view = views[i];
  15547. var viewport = baseLayer.getViewport(view);
  15548. var viewMatrix = view.transform.inverse.matrix;
  15549. var camera = cameraVR.cameras[i];
  15550. camera.matrix.fromArray(viewMatrix).getInverse(camera.matrix);
  15551. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15552. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15553. if (i === 0) {
  15554. cameraVR.matrix.copy(camera.matrix);
  15555. }
  15556. }
  15557. } //
  15558. for (var i = 0; i < controllers.length; i++) {
  15559. var controller = controllers[i];
  15560. var inputSource = inputSources[i];
  15561. if (inputSource) {
  15562. var inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  15563. if (inputPose !== null) {
  15564. controller.matrix.fromArray(inputPose.transform.matrix);
  15565. controller.matrix.decompose(controller.position, controller.rotation, controller.scale);
  15566. controller.visible = true;
  15567. continue;
  15568. }
  15569. }
  15570. controller.visible = false;
  15571. }
  15572. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15573. }
  15574. var animation = new WebGLAnimation();
  15575. animation.setAnimationLoop(onAnimationFrame);
  15576. this.setAnimationLoop = function (callback) {
  15577. onAnimationFrameCallback = callback;
  15578. };
  15579. this.dispose = function () {}; // DEPRECATED
  15580. this.getStandingMatrix = function () {
  15581. console.warn('THREE.WebXRManager: getStandingMatrix() is no longer needed.');
  15582. return new Matrix4();
  15583. };
  15584. this.getDevice = function () {
  15585. console.warn('THREE.WebXRManager: getDevice() has been deprecated.');
  15586. };
  15587. this.setDevice = function () {
  15588. console.warn('THREE.WebXRManager: setDevice() has been deprecated.');
  15589. };
  15590. this.setFrameOfReferenceType = function () {
  15591. console.warn('THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.');
  15592. };
  15593. this.submitFrame = function () {};
  15594. }
  15595. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  15596. /**
  15597. * @author supereggbert / http://www.paulbrunt.co.uk/
  15598. * @author mrdoob / http://mrdoob.com/
  15599. * @author alteredq / http://alteredqualia.com/
  15600. * @author szimek / https://github.com/szimek/
  15601. * @author tschw
  15602. */
  15603. function WebGLRenderer(parameters) {
  15604. parameters = parameters || {};
  15605. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  15606. _context = parameters.context !== undefined ? parameters.context : null,
  15607. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15608. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15609. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15610. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15611. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15612. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15613. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15614. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15615. var currentRenderList = null;
  15616. var currentRenderState = null; // public properties
  15617. this.domElement = _canvas; // Debug configuration container
  15618. this.debug = {
  15619. /**
  15620. * Enables error checking and reporting when shader programs are being compiled
  15621. * @type {boolean}
  15622. */
  15623. checkShaderErrors: true
  15624. }; // clearing
  15625. this.autoClear = true;
  15626. this.autoClearColor = true;
  15627. this.autoClearDepth = true;
  15628. this.autoClearStencil = true; // scene graph
  15629. this.sortObjects = true; // user-defined clipping
  15630. this.clippingPlanes = [];
  15631. this.localClippingEnabled = false; // physically based shading
  15632. this.gammaFactor = 2.0; // for backwards compatibility
  15633. this.gammaInput = false;
  15634. this.gammaOutput = false; // physical lights
  15635. this.physicallyCorrectLights = false; // tone mapping
  15636. this.toneMapping = LinearToneMapping;
  15637. this.toneMappingExposure = 1.0;
  15638. this.toneMappingWhitePoint = 1.0; // morphs
  15639. this.maxMorphTargets = 8;
  15640. this.maxMorphNormals = 4; // internal properties
  15641. var _this = this,
  15642. _isContextLost = false,
  15643. // internal state cache
  15644. _framebuffer = null,
  15645. _currentActiveCubeFace = 0,
  15646. _currentActiveMipmapLevel = 0,
  15647. _currentRenderTarget = null,
  15648. _currentFramebuffer = null,
  15649. _currentMaterialId = -1,
  15650. // geometry and program caching
  15651. _currentGeometryProgram = {
  15652. geometry: null,
  15653. program: null,
  15654. wireframe: false
  15655. },
  15656. _currentCamera = null,
  15657. _currentArrayCamera = null,
  15658. _currentViewport = new Vector4(),
  15659. _currentScissor = new Vector4(),
  15660. _currentScissorTest = null,
  15661. //
  15662. _width = _canvas.width,
  15663. _height = _canvas.height,
  15664. _pixelRatio = 1,
  15665. _viewport = new Vector4(0, 0, _width, _height),
  15666. _scissor = new Vector4(0, 0, _width, _height),
  15667. _scissorTest = false,
  15668. // frustum
  15669. _frustum = new Frustum(),
  15670. // clipping
  15671. _clipping = new WebGLClipping(),
  15672. _clippingEnabled = false,
  15673. _localClippingEnabled = false,
  15674. // camera matrices cache
  15675. _projScreenMatrix = new Matrix4(),
  15676. _vector3 = new Vector3();
  15677. function getTargetPixelRatio() {
  15678. return _currentRenderTarget === null ? _pixelRatio : 1;
  15679. } // initialize
  15680. var _gl;
  15681. try {
  15682. var contextAttributes = {
  15683. alpha: _alpha,
  15684. depth: _depth,
  15685. stencil: _stencil,
  15686. antialias: _antialias,
  15687. premultipliedAlpha: _premultipliedAlpha,
  15688. preserveDrawingBuffer: _preserveDrawingBuffer,
  15689. powerPreference: _powerPreference,
  15690. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  15691. xrCompatible: true
  15692. }; // event listeners must be registered before WebGL context is created, see #12753
  15693. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15694. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15695. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  15696. if (_gl === null) {
  15697. if (_canvas.getContext('webgl') !== null) {
  15698. throw new Error('Error creating WebGL context with your selected attributes.');
  15699. } else {
  15700. throw new Error('Error creating WebGL context.');
  15701. }
  15702. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15703. if (_gl.getShaderPrecisionFormat === undefined) {
  15704. _gl.getShaderPrecisionFormat = function () {
  15705. return {
  15706. 'rangeMin': 1,
  15707. 'rangeMax': 1,
  15708. 'precision': 1
  15709. };
  15710. };
  15711. }
  15712. } catch (error) {
  15713. console.error('THREE.WebGLRenderer: ' + error.message);
  15714. throw error;
  15715. }
  15716. var extensions, capabilities, state, info;
  15717. var properties, textures, attributes, geometries, objects;
  15718. var programCache, renderLists, renderStates;
  15719. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15720. var utils;
  15721. function initGLContext() {
  15722. extensions = new WebGLExtensions(_gl);
  15723. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15724. if (capabilities.isWebGL2 === false) {
  15725. extensions.get('WEBGL_depth_texture');
  15726. extensions.get('OES_texture_float');
  15727. extensions.get('OES_texture_half_float');
  15728. extensions.get('OES_texture_half_float_linear');
  15729. extensions.get('OES_standard_derivatives');
  15730. extensions.get('OES_element_index_uint');
  15731. extensions.get('ANGLE_instanced_arrays');
  15732. }
  15733. extensions.get('OES_texture_float_linear');
  15734. utils = new WebGLUtils(_gl, extensions, capabilities);
  15735. state = new WebGLState(_gl, extensions, utils, capabilities);
  15736. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15737. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15738. info = new WebGLInfo(_gl);
  15739. properties = new WebGLProperties();
  15740. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15741. attributes = new WebGLAttributes(_gl);
  15742. geometries = new WebGLGeometries(_gl, attributes, info);
  15743. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15744. morphtargets = new WebGLMorphtargets(_gl);
  15745. programCache = new WebGLPrograms(_this, extensions, capabilities);
  15746. renderLists = new WebGLRenderLists();
  15747. renderStates = new WebGLRenderStates();
  15748. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  15749. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15750. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15751. info.programs = programCache.programs;
  15752. _this.capabilities = capabilities;
  15753. _this.extensions = extensions;
  15754. _this.properties = properties;
  15755. _this.renderLists = renderLists;
  15756. _this.state = state;
  15757. _this.info = info;
  15758. }
  15759. initGLContext(); // vr
  15760. var vr = typeof navigator !== 'undefined' && 'xr' in navigator && 'supportsSession' in navigator.xr ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  15761. this.vr = vr; // Multiview
  15762. var multiview = new WebGLMultiview(_this, _gl); // shadow map
  15763. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  15764. this.shadowMap = shadowMap; // API
  15765. this.getContext = function () {
  15766. return _gl;
  15767. };
  15768. this.getContextAttributes = function () {
  15769. return _gl.getContextAttributes();
  15770. };
  15771. this.forceContextLoss = function () {
  15772. var extension = extensions.get('WEBGL_lose_context');
  15773. if (extension) extension.loseContext();
  15774. };
  15775. this.forceContextRestore = function () {
  15776. var extension = extensions.get('WEBGL_lose_context');
  15777. if (extension) extension.restoreContext();
  15778. };
  15779. this.getPixelRatio = function () {
  15780. return _pixelRatio;
  15781. };
  15782. this.setPixelRatio = function (value) {
  15783. if (value === undefined) return;
  15784. _pixelRatio = value;
  15785. this.setSize(_width, _height, false);
  15786. };
  15787. this.getSize = function (target) {
  15788. if (target === undefined) {
  15789. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  15790. target = new Vector2();
  15791. }
  15792. return target.set(_width, _height);
  15793. };
  15794. this.setSize = function (width, height, updateStyle) {
  15795. if (vr.isPresenting()) {
  15796. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15797. return;
  15798. }
  15799. _width = width;
  15800. _height = height;
  15801. _canvas.width = Math.floor(width * _pixelRatio);
  15802. _canvas.height = Math.floor(height * _pixelRatio);
  15803. if (updateStyle !== false) {
  15804. _canvas.style.width = width + 'px';
  15805. _canvas.style.height = height + 'px';
  15806. }
  15807. this.setViewport(0, 0, width, height);
  15808. };
  15809. this.getDrawingBufferSize = function (target) {
  15810. if (target === undefined) {
  15811. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  15812. target = new Vector2();
  15813. }
  15814. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15815. };
  15816. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15817. _width = width;
  15818. _height = height;
  15819. _pixelRatio = pixelRatio;
  15820. _canvas.width = Math.floor(width * pixelRatio);
  15821. _canvas.height = Math.floor(height * pixelRatio);
  15822. this.setViewport(0, 0, width, height);
  15823. };
  15824. this.getCurrentViewport = function (target) {
  15825. if (target === undefined) {
  15826. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  15827. target = new Vector4();
  15828. }
  15829. return target.copy(_currentViewport);
  15830. };
  15831. this.getViewport = function (target) {
  15832. return target.copy(_viewport);
  15833. };
  15834. this.setViewport = function (x, y, width, height) {
  15835. if (x.isVector4) {
  15836. _viewport.set(x.x, x.y, x.z, x.w);
  15837. } else {
  15838. _viewport.set(x, y, width, height);
  15839. }
  15840. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15841. };
  15842. this.getScissor = function (target) {
  15843. return target.copy(_scissor);
  15844. };
  15845. this.setScissor = function (x, y, width, height) {
  15846. if (x.isVector4) {
  15847. _scissor.set(x.x, x.y, x.z, x.w);
  15848. } else {
  15849. _scissor.set(x, y, width, height);
  15850. }
  15851. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15852. };
  15853. this.getScissorTest = function () {
  15854. return _scissorTest;
  15855. };
  15856. this.setScissorTest = function (boolean) {
  15857. state.setScissorTest(_scissorTest = boolean);
  15858. }; // Clearing
  15859. this.getClearColor = function () {
  15860. return background.getClearColor();
  15861. };
  15862. this.setClearColor = function () {
  15863. background.setClearColor.apply(background, arguments);
  15864. };
  15865. this.getClearAlpha = function () {
  15866. return background.getClearAlpha();
  15867. };
  15868. this.setClearAlpha = function () {
  15869. background.setClearAlpha.apply(background, arguments);
  15870. };
  15871. this.clear = function (color, depth, stencil) {
  15872. var bits = 0;
  15873. if (color === undefined || color) bits |= 16384;
  15874. if (depth === undefined || depth) bits |= 256;
  15875. if (stencil === undefined || stencil) bits |= 1024;
  15876. _gl.clear(bits);
  15877. };
  15878. this.clearColor = function () {
  15879. this.clear(true, false, false);
  15880. };
  15881. this.clearDepth = function () {
  15882. this.clear(false, true, false);
  15883. };
  15884. this.clearStencil = function () {
  15885. this.clear(false, false, true);
  15886. }; //
  15887. this.dispose = function () {
  15888. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15889. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15890. renderLists.dispose();
  15891. renderStates.dispose();
  15892. properties.dispose();
  15893. objects.dispose();
  15894. vr.dispose();
  15895. animation.stop();
  15896. }; // Events
  15897. function onContextLost(event) {
  15898. event.preventDefault();
  15899. console.log('THREE.WebGLRenderer: Context Lost.');
  15900. _isContextLost = true;
  15901. }
  15902. function onContextRestore()
  15903. /* event */
  15904. {
  15905. console.log('THREE.WebGLRenderer: Context Restored.');
  15906. _isContextLost = false;
  15907. initGLContext();
  15908. }
  15909. function onMaterialDispose(event) {
  15910. var material = event.target;
  15911. material.removeEventListener('dispose', onMaterialDispose);
  15912. deallocateMaterial(material);
  15913. } // Buffer deallocation
  15914. function deallocateMaterial(material) {
  15915. releaseMaterialProgramReference(material);
  15916. properties.remove(material);
  15917. }
  15918. function releaseMaterialProgramReference(material) {
  15919. var programInfo = properties.get(material).program;
  15920. material.program = undefined;
  15921. if (programInfo !== undefined) {
  15922. programCache.releaseProgram(programInfo);
  15923. }
  15924. } // Buffer rendering
  15925. function renderObjectImmediate(object, program) {
  15926. object.render(function (object) {
  15927. _this.renderBufferImmediate(object, program);
  15928. });
  15929. }
  15930. this.renderBufferImmediate = function (object, program) {
  15931. state.initAttributes();
  15932. var buffers = properties.get(object);
  15933. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  15934. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  15935. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  15936. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  15937. var programAttributes = program.getAttributes();
  15938. if (object.hasPositions) {
  15939. _gl.bindBuffer(34962, buffers.position);
  15940. _gl.bufferData(34962, object.positionArray, 35048);
  15941. state.enableAttribute(programAttributes.position);
  15942. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  15943. }
  15944. if (object.hasNormals) {
  15945. _gl.bindBuffer(34962, buffers.normal);
  15946. _gl.bufferData(34962, object.normalArray, 35048);
  15947. state.enableAttribute(programAttributes.normal);
  15948. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  15949. }
  15950. if (object.hasUvs) {
  15951. _gl.bindBuffer(34962, buffers.uv);
  15952. _gl.bufferData(34962, object.uvArray, 35048);
  15953. state.enableAttribute(programAttributes.uv);
  15954. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  15955. }
  15956. if (object.hasColors) {
  15957. _gl.bindBuffer(34962, buffers.color);
  15958. _gl.bufferData(34962, object.colorArray, 35048);
  15959. state.enableAttribute(programAttributes.color);
  15960. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  15961. }
  15962. state.disableUnusedAttributes();
  15963. _gl.drawArrays(4, 0, object.count);
  15964. object.count = 0;
  15965. };
  15966. this.renderBufferDirect = function (camera, fog, geometry, material, object, group) {
  15967. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15968. state.setMaterial(material, frontFaceCW);
  15969. var program = setProgram(camera, fog, material, object);
  15970. var updateBuffers = false;
  15971. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  15972. _currentGeometryProgram.geometry = geometry.id;
  15973. _currentGeometryProgram.program = program.id;
  15974. _currentGeometryProgram.wireframe = material.wireframe === true;
  15975. updateBuffers = true;
  15976. }
  15977. if (object.morphTargetInfluences) {
  15978. morphtargets.update(object, geometry, material, program);
  15979. updateBuffers = true;
  15980. } //
  15981. var index = geometry.index;
  15982. var position = geometry.attributes.position;
  15983. var rangeFactor = 1;
  15984. if (material.wireframe === true) {
  15985. index = geometries.getWireframeAttribute(geometry);
  15986. rangeFactor = 2;
  15987. }
  15988. var attribute;
  15989. var renderer = bufferRenderer;
  15990. if (index !== null) {
  15991. attribute = attributes.get(index);
  15992. renderer = indexedBufferRenderer;
  15993. renderer.setIndex(attribute);
  15994. }
  15995. if (updateBuffers) {
  15996. setupVertexAttributes(object, geometry, material, program);
  15997. if (index !== null) {
  15998. _gl.bindBuffer(34963, attribute.buffer);
  15999. }
  16000. } //
  16001. var dataCount = Infinity;
  16002. if (index !== null) {
  16003. dataCount = index.count;
  16004. } else if (position !== undefined) {
  16005. dataCount = position.count;
  16006. }
  16007. var rangeStart = geometry.drawRange.start * rangeFactor;
  16008. var rangeCount = geometry.drawRange.count * rangeFactor;
  16009. var groupStart = group !== null ? group.start * rangeFactor : 0;
  16010. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16011. var drawStart = Math.max(rangeStart, groupStart);
  16012. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  16013. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  16014. if (drawCount === 0) return; //
  16015. if (object.isMesh) {
  16016. if (material.wireframe === true) {
  16017. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  16018. renderer.setMode(1);
  16019. } else {
  16020. switch (object.drawMode) {
  16021. case TrianglesDrawMode:
  16022. renderer.setMode(4);
  16023. break;
  16024. case TriangleStripDrawMode:
  16025. renderer.setMode(5);
  16026. break;
  16027. case TriangleFanDrawMode:
  16028. renderer.setMode(6);
  16029. break;
  16030. }
  16031. }
  16032. } else if (object.isLine) {
  16033. var lineWidth = material.linewidth;
  16034. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16035. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16036. if (object.isLineSegments) {
  16037. renderer.setMode(1);
  16038. } else if (object.isLineLoop) {
  16039. renderer.setMode(2);
  16040. } else {
  16041. renderer.setMode(3);
  16042. }
  16043. } else if (object.isPoints) {
  16044. renderer.setMode(0);
  16045. } else if (object.isSprite) {
  16046. renderer.setMode(4);
  16047. }
  16048. if (object.isInstancedMesh) {
  16049. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  16050. } else if (geometry.isInstancedBufferGeometry) {
  16051. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  16052. } else {
  16053. renderer.render(drawStart, drawCount);
  16054. }
  16055. };
  16056. function setupVertexAttributes(object, geometry, material, program) {
  16057. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  16058. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  16059. }
  16060. state.initAttributes();
  16061. var geometryAttributes = geometry.attributes;
  16062. var programAttributes = program.getAttributes();
  16063. var materialDefaultAttributeValues = material.defaultAttributeValues;
  16064. for (var name in programAttributes) {
  16065. var programAttribute = programAttributes[name];
  16066. if (programAttribute >= 0) {
  16067. var geometryAttribute = geometryAttributes[name];
  16068. if (geometryAttribute !== undefined) {
  16069. var normalized = geometryAttribute.normalized;
  16070. var size = geometryAttribute.itemSize;
  16071. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  16072. if (attribute === undefined) continue;
  16073. var buffer = attribute.buffer;
  16074. var type = attribute.type;
  16075. var bytesPerElement = attribute.bytesPerElement;
  16076. if (geometryAttribute.isInterleavedBufferAttribute) {
  16077. var data = geometryAttribute.data;
  16078. var stride = data.stride;
  16079. var offset = geometryAttribute.offset;
  16080. if (data && data.isInstancedInterleavedBuffer) {
  16081. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  16082. if (geometry.maxInstancedCount === undefined) {
  16083. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  16084. }
  16085. } else {
  16086. state.enableAttribute(programAttribute);
  16087. }
  16088. _gl.bindBuffer(34962, buffer);
  16089. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  16090. } else {
  16091. if (geometryAttribute.isInstancedBufferAttribute) {
  16092. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  16093. if (geometry.maxInstancedCount === undefined) {
  16094. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  16095. }
  16096. } else {
  16097. state.enableAttribute(programAttribute);
  16098. }
  16099. _gl.bindBuffer(34962, buffer);
  16100. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  16101. }
  16102. } else if (name === 'instanceMatrix') {
  16103. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  16104. if (attribute === undefined) continue;
  16105. var buffer = attribute.buffer;
  16106. var type = attribute.type;
  16107. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  16108. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  16109. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  16110. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  16111. _gl.bindBuffer(34962, buffer);
  16112. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  16113. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  16114. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  16115. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  16116. } else if (materialDefaultAttributeValues !== undefined) {
  16117. var value = materialDefaultAttributeValues[name];
  16118. if (value !== undefined) {
  16119. switch (value.length) {
  16120. case 2:
  16121. _gl.vertexAttrib2fv(programAttribute, value);
  16122. break;
  16123. case 3:
  16124. _gl.vertexAttrib3fv(programAttribute, value);
  16125. break;
  16126. case 4:
  16127. _gl.vertexAttrib4fv(programAttribute, value);
  16128. break;
  16129. default:
  16130. _gl.vertexAttrib1fv(programAttribute, value);
  16131. }
  16132. }
  16133. }
  16134. }
  16135. }
  16136. state.disableUnusedAttributes();
  16137. } // Compile
  16138. this.compile = function (scene, camera) {
  16139. currentRenderState = renderStates.get(scene, camera);
  16140. currentRenderState.init();
  16141. scene.traverse(function (object) {
  16142. if (object.isLight) {
  16143. currentRenderState.pushLight(object);
  16144. if (object.castShadow) {
  16145. currentRenderState.pushShadow(object);
  16146. }
  16147. }
  16148. });
  16149. currentRenderState.setupLights(camera);
  16150. scene.traverse(function (object) {
  16151. if (object.material) {
  16152. if (Array.isArray(object.material)) {
  16153. for (var i = 0; i < object.material.length; i++) {
  16154. initMaterial(object.material[i], scene.fog, object);
  16155. }
  16156. } else {
  16157. initMaterial(object.material, scene.fog, object);
  16158. }
  16159. }
  16160. });
  16161. }; // Animation Loop
  16162. var onAnimationFrameCallback = null;
  16163. function onAnimationFrame(time) {
  16164. if (vr.isPresenting()) return;
  16165. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16166. }
  16167. var animation = new WebGLAnimation();
  16168. animation.setAnimationLoop(onAnimationFrame);
  16169. if (typeof window !== 'undefined') animation.setContext(window);
  16170. this.setAnimationLoop = function (callback) {
  16171. onAnimationFrameCallback = callback;
  16172. vr.setAnimationLoop(callback);
  16173. animation.start();
  16174. }; // Rendering
  16175. this.render = function (scene, camera) {
  16176. var renderTarget, forceClear;
  16177. if (arguments[2] !== undefined) {
  16178. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  16179. renderTarget = arguments[2];
  16180. }
  16181. if (arguments[3] !== undefined) {
  16182. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  16183. forceClear = arguments[3];
  16184. }
  16185. if (!(camera && camera.isCamera)) {
  16186. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16187. return;
  16188. }
  16189. if (_isContextLost) return; // reset caching for this frame
  16190. _currentGeometryProgram.geometry = null;
  16191. _currentGeometryProgram.program = null;
  16192. _currentGeometryProgram.wireframe = false;
  16193. _currentMaterialId = -1;
  16194. _currentCamera = null; // update scene graph
  16195. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  16196. if (camera.parent === null) camera.updateMatrixWorld();
  16197. if (vr.enabled) {
  16198. camera = vr.getCamera(camera);
  16199. } //
  16200. currentRenderState = renderStates.get(scene, camera);
  16201. currentRenderState.init();
  16202. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  16203. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16204. _frustum.setFromMatrix(_projScreenMatrix);
  16205. _localClippingEnabled = this.localClippingEnabled;
  16206. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16207. currentRenderList = renderLists.get(scene, camera);
  16208. currentRenderList.init();
  16209. projectObject(scene, camera, 0, _this.sortObjects);
  16210. if (_this.sortObjects === true) {
  16211. currentRenderList.sort();
  16212. } //
  16213. if (_clippingEnabled) _clipping.beginShadows();
  16214. var shadowsArray = currentRenderState.state.shadowsArray;
  16215. shadowMap.render(shadowsArray, scene, camera);
  16216. currentRenderState.setupLights(camera);
  16217. if (_clippingEnabled) _clipping.endShadows(); //
  16218. if (this.info.autoReset) this.info.reset();
  16219. if (renderTarget !== undefined) {
  16220. this.setRenderTarget(renderTarget);
  16221. }
  16222. if (vr.enabled && multiview.isAvailable()) {
  16223. multiview.attachCamera(camera);
  16224. } //
  16225. background.render(currentRenderList, scene, camera, forceClear); // render scene
  16226. var opaqueObjects = currentRenderList.opaque;
  16227. var transparentObjects = currentRenderList.transparent;
  16228. if (scene.overrideMaterial) {
  16229. var overrideMaterial = scene.overrideMaterial;
  16230. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  16231. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  16232. } else {
  16233. // opaque pass (front-to-back order)
  16234. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  16235. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  16236. } //
  16237. scene.onAfterRender(_this, scene, camera); //
  16238. if (_currentRenderTarget !== null) {
  16239. // Generate mipmap if we're using any kind of mipmap filtering
  16240. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  16241. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  16242. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  16243. state.buffers.depth.setTest(true);
  16244. state.buffers.depth.setMask(true);
  16245. state.buffers.color.setMask(true);
  16246. state.setPolygonOffset(false);
  16247. if (vr.enabled) {
  16248. if (multiview.isAvailable()) {
  16249. multiview.detachCamera(camera);
  16250. }
  16251. vr.submitFrame();
  16252. } // _gl.finish();
  16253. currentRenderList = null;
  16254. currentRenderState = null;
  16255. };
  16256. function projectObject(object, camera, groupOrder, sortObjects) {
  16257. if (object.visible === false) return;
  16258. var visible = object.layers.test(camera.layers);
  16259. if (visible) {
  16260. if (object.isGroup) {
  16261. groupOrder = object.renderOrder;
  16262. } else if (object.isLOD) {
  16263. if (object.autoUpdate === true) object.update(camera);
  16264. } else if (object.isLight) {
  16265. currentRenderState.pushLight(object);
  16266. if (object.castShadow) {
  16267. currentRenderState.pushShadow(object);
  16268. }
  16269. } else if (object.isSprite) {
  16270. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16271. if (sortObjects) {
  16272. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16273. }
  16274. var geometry = objects.update(object);
  16275. var material = object.material;
  16276. if (material.visible) {
  16277. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16278. }
  16279. }
  16280. } else if (object.isImmediateRenderObject) {
  16281. if (sortObjects) {
  16282. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16283. }
  16284. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  16285. } else if (object.isMesh || object.isLine || object.isPoints) {
  16286. if (object.isSkinnedMesh) {
  16287. // update skeleton only once in a frame
  16288. if (object.skeleton.frame !== info.render.frame) {
  16289. object.skeleton.update();
  16290. object.skeleton.frame = info.render.frame;
  16291. }
  16292. }
  16293. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16294. if (sortObjects) {
  16295. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16296. }
  16297. var geometry = objects.update(object);
  16298. var material = object.material;
  16299. if (Array.isArray(material)) {
  16300. var groups = geometry.groups;
  16301. for (var i = 0, l = groups.length; i < l; i++) {
  16302. var group = groups[i];
  16303. var groupMaterial = material[group.materialIndex];
  16304. if (groupMaterial && groupMaterial.visible) {
  16305. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16306. }
  16307. }
  16308. } else if (material.visible) {
  16309. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16310. }
  16311. }
  16312. }
  16313. }
  16314. var children = object.children;
  16315. for (var i = 0, l = children.length; i < l; i++) {
  16316. projectObject(children[i], camera, groupOrder, sortObjects);
  16317. }
  16318. }
  16319. function renderObjects(renderList, scene, camera, overrideMaterial) {
  16320. for (var i = 0, l = renderList.length; i < l; i++) {
  16321. var renderItem = renderList[i];
  16322. var object = renderItem.object;
  16323. var geometry = renderItem.geometry;
  16324. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  16325. var group = renderItem.group;
  16326. if (camera.isArrayCamera) {
  16327. _currentArrayCamera = camera;
  16328. if (vr.enabled && multiview.isAvailable()) {
  16329. renderObject(object, scene, camera, geometry, material, group);
  16330. } else {
  16331. var cameras = camera.cameras;
  16332. for (var j = 0, jl = cameras.length; j < jl; j++) {
  16333. var camera2 = cameras[j];
  16334. if (object.layers.test(camera2.layers)) {
  16335. state.viewport(_currentViewport.copy(camera2.viewport));
  16336. currentRenderState.setupLights(camera2);
  16337. renderObject(object, scene, camera2, geometry, material, group);
  16338. }
  16339. }
  16340. }
  16341. } else {
  16342. _currentArrayCamera = null;
  16343. renderObject(object, scene, camera, geometry, material, group);
  16344. }
  16345. }
  16346. }
  16347. function renderObject(object, scene, camera, geometry, material, group) {
  16348. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16349. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16350. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16351. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16352. if (object.isImmediateRenderObject) {
  16353. state.setMaterial(material);
  16354. var program = setProgram(camera, scene.fog, material, object);
  16355. _currentGeometryProgram.geometry = null;
  16356. _currentGeometryProgram.program = null;
  16357. _currentGeometryProgram.wireframe = false;
  16358. renderObjectImmediate(object, program);
  16359. } else {
  16360. _this.renderBufferDirect(camera, scene.fog, geometry, material, object, group);
  16361. }
  16362. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16363. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16364. }
  16365. function initMaterial(material, fog, object) {
  16366. var materialProperties = properties.get(material);
  16367. var lights = currentRenderState.state.lights;
  16368. var shadowsArray = currentRenderState.state.shadowsArray;
  16369. var lightsStateVersion = lights.state.version;
  16370. var parameters = programCache.getParameters(material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object);
  16371. var code = programCache.getProgramCode(material, parameters);
  16372. var program = materialProperties.program;
  16373. var programChange = true;
  16374. if (program === undefined) {
  16375. // new material
  16376. material.addEventListener('dispose', onMaterialDispose);
  16377. } else if (program.code !== code) {
  16378. // changed glsl or parameters
  16379. releaseMaterialProgramReference(material);
  16380. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  16381. materialProperties.lightsStateVersion = lightsStateVersion;
  16382. programChange = false;
  16383. } else if (parameters.shaderID !== undefined) {
  16384. // same glsl and uniform list
  16385. return;
  16386. } else {
  16387. // only rebuild uniform list
  16388. programChange = false;
  16389. }
  16390. if (programChange) {
  16391. if (parameters.shaderID) {
  16392. var shader = ShaderLib[parameters.shaderID];
  16393. materialProperties.shader = {
  16394. name: material.type,
  16395. uniforms: cloneUniforms(shader.uniforms),
  16396. vertexShader: shader.vertexShader,
  16397. fragmentShader: shader.fragmentShader
  16398. };
  16399. } else {
  16400. materialProperties.shader = {
  16401. name: material.type,
  16402. uniforms: material.uniforms,
  16403. vertexShader: material.vertexShader,
  16404. fragmentShader: material.fragmentShader
  16405. };
  16406. }
  16407. material.onBeforeCompile(materialProperties.shader, _this); // Computing code again as onBeforeCompile may have changed the shaders
  16408. code = programCache.getProgramCode(material, parameters);
  16409. program = programCache.acquireProgram(material, materialProperties.shader, parameters, code);
  16410. materialProperties.program = program;
  16411. material.program = program;
  16412. }
  16413. var programAttributes = program.getAttributes();
  16414. if (material.morphTargets) {
  16415. material.numSupportedMorphTargets = 0;
  16416. for (var i = 0; i < _this.maxMorphTargets; i++) {
  16417. if (programAttributes['morphTarget' + i] >= 0) {
  16418. material.numSupportedMorphTargets++;
  16419. }
  16420. }
  16421. }
  16422. if (material.morphNormals) {
  16423. material.numSupportedMorphNormals = 0;
  16424. for (var i = 0; i < _this.maxMorphNormals; i++) {
  16425. if (programAttributes['morphNormal' + i] >= 0) {
  16426. material.numSupportedMorphNormals++;
  16427. }
  16428. }
  16429. }
  16430. var uniforms = materialProperties.shader.uniforms;
  16431. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16432. materialProperties.numClippingPlanes = _clipping.numPlanes;
  16433. materialProperties.numIntersection = _clipping.numIntersection;
  16434. uniforms.clippingPlanes = _clipping.uniform;
  16435. }
  16436. materialProperties.fog = fog; // store the light setup it was created for
  16437. materialProperties.needsLights = materialNeedsLights(material);
  16438. materialProperties.lightsStateVersion = lightsStateVersion;
  16439. if (materialProperties.needsLights) {
  16440. // wire up the material to this renderer's lighting state
  16441. uniforms.ambientLightColor.value = lights.state.ambient;
  16442. uniforms.lightProbe.value = lights.state.probe;
  16443. uniforms.directionalLights.value = lights.state.directional;
  16444. uniforms.spotLights.value = lights.state.spot;
  16445. uniforms.rectAreaLights.value = lights.state.rectArea;
  16446. uniforms.pointLights.value = lights.state.point;
  16447. uniforms.hemisphereLights.value = lights.state.hemi;
  16448. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16449. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16450. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16451. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16452. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16453. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16454. }
  16455. var progUniforms = materialProperties.program.getUniforms(),
  16456. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16457. materialProperties.uniformsList = uniformsList;
  16458. }
  16459. function setProgram(camera, fog, material, object) {
  16460. textures.resetTextureUnits();
  16461. var materialProperties = properties.get(material);
  16462. var lights = currentRenderState.state.lights;
  16463. if (_clippingEnabled) {
  16464. if (_localClippingEnabled || camera !== _currentCamera) {
  16465. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16466. // object instead of the material, once it becomes feasible
  16467. // (#8465, #8379)
  16468. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  16469. }
  16470. }
  16471. if (material.needsUpdate === false) {
  16472. if (materialProperties.program === undefined) {
  16473. material.needsUpdate = true;
  16474. } else if (material.fog && materialProperties.fog !== fog) {
  16475. material.needsUpdate = true;
  16476. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16477. material.needsUpdate = true;
  16478. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  16479. material.needsUpdate = true;
  16480. }
  16481. }
  16482. if (material.needsUpdate) {
  16483. initMaterial(material, fog, object);
  16484. material.needsUpdate = false;
  16485. }
  16486. var refreshProgram = false;
  16487. var refreshMaterial = false;
  16488. var refreshLights = false;
  16489. var program = materialProperties.program,
  16490. p_uniforms = program.getUniforms(),
  16491. m_uniforms = materialProperties.shader.uniforms;
  16492. if (state.useProgram(program.program)) {
  16493. refreshProgram = true;
  16494. refreshMaterial = true;
  16495. refreshLights = true;
  16496. }
  16497. if (material.id !== _currentMaterialId) {
  16498. _currentMaterialId = material.id;
  16499. refreshMaterial = true;
  16500. }
  16501. if (refreshProgram || _currentCamera !== camera) {
  16502. if (program.numMultiviewViews > 0) {
  16503. multiview.updateCameraProjectionMatricesUniform(camera, p_uniforms);
  16504. } else {
  16505. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16506. }
  16507. if (capabilities.logarithmicDepthBuffer) {
  16508. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16509. }
  16510. if (_currentCamera !== camera) {
  16511. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16512. // now, in case this material supports lights - or later, when
  16513. // the next material that does gets activated:
  16514. refreshMaterial = true; // set to true on material change
  16515. refreshLights = true; // remains set until update done
  16516. } // load material specific uniforms
  16517. // (shader material also gets them for the sake of genericity)
  16518. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.envMap) {
  16519. var uCamPos = p_uniforms.map.cameraPosition;
  16520. if (uCamPos !== undefined) {
  16521. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16522. }
  16523. }
  16524. if (material.isMeshPhongMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  16525. if (program.numMultiviewViews > 0) {
  16526. multiview.updateCameraViewMatricesUniform(camera, p_uniforms);
  16527. } else {
  16528. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16529. }
  16530. }
  16531. } // skinning uniforms must be set even if material didn't change
  16532. // auto-setting of texture unit for bone texture must go before other textures
  16533. // not sure why, but otherwise weird things happen
  16534. if (material.skinning) {
  16535. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16536. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16537. var skeleton = object.skeleton;
  16538. if (skeleton) {
  16539. var bones = skeleton.bones;
  16540. if (capabilities.floatVertexTextures) {
  16541. if (skeleton.boneTexture === undefined) {
  16542. // layout (1 matrix = 4 pixels)
  16543. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16544. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16545. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16546. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16547. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16548. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  16549. size = _Math.ceilPowerOfTwo(size);
  16550. size = Math.max(size, 4);
  16551. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16552. boneMatrices.set(skeleton.boneMatrices); // copy current values
  16553. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16554. skeleton.boneMatrices = boneMatrices;
  16555. skeleton.boneTexture = boneTexture;
  16556. skeleton.boneTextureSize = size;
  16557. }
  16558. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16559. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16560. } else {
  16561. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  16562. }
  16563. }
  16564. }
  16565. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16566. materialProperties.receiveShadow = object.receiveShadow;
  16567. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16568. }
  16569. if (refreshMaterial) {
  16570. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16571. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  16572. if (materialProperties.needsLights) {
  16573. // the current material requires lighting info
  16574. // note: all lighting uniforms are always set correctly
  16575. // they simply reference the renderer's state for their
  16576. // values
  16577. //
  16578. // use the current material's .needsUpdate flags to set
  16579. // the GL state when required
  16580. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16581. } // refresh uniforms common to several materials
  16582. if (fog && material.fog) {
  16583. refreshUniformsFog(m_uniforms, fog);
  16584. }
  16585. if (material.isMeshBasicMaterial) {
  16586. refreshUniformsCommon(m_uniforms, material);
  16587. } else if (material.isMeshLambertMaterial) {
  16588. refreshUniformsCommon(m_uniforms, material);
  16589. refreshUniformsLambert(m_uniforms, material);
  16590. } else if (material.isMeshPhongMaterial) {
  16591. refreshUniformsCommon(m_uniforms, material);
  16592. if (material.isMeshToonMaterial) {
  16593. refreshUniformsToon(m_uniforms, material);
  16594. } else {
  16595. refreshUniformsPhong(m_uniforms, material);
  16596. }
  16597. } else if (material.isMeshStandardMaterial) {
  16598. refreshUniformsCommon(m_uniforms, material);
  16599. if (material.isMeshPhysicalMaterial) {
  16600. refreshUniformsPhysical(m_uniforms, material);
  16601. } else {
  16602. refreshUniformsStandard(m_uniforms, material);
  16603. }
  16604. } else if (material.isMeshMatcapMaterial) {
  16605. refreshUniformsCommon(m_uniforms, material);
  16606. refreshUniformsMatcap(m_uniforms, material);
  16607. } else if (material.isMeshDepthMaterial) {
  16608. refreshUniformsCommon(m_uniforms, material);
  16609. refreshUniformsDepth(m_uniforms, material);
  16610. } else if (material.isMeshDistanceMaterial) {
  16611. refreshUniformsCommon(m_uniforms, material);
  16612. refreshUniformsDistance(m_uniforms, material);
  16613. } else if (material.isMeshNormalMaterial) {
  16614. refreshUniformsCommon(m_uniforms, material);
  16615. refreshUniformsNormal(m_uniforms, material);
  16616. } else if (material.isLineBasicMaterial) {
  16617. refreshUniformsLine(m_uniforms, material);
  16618. if (material.isLineDashedMaterial) {
  16619. refreshUniformsDash(m_uniforms, material);
  16620. }
  16621. } else if (material.isPointsMaterial) {
  16622. refreshUniformsPoints(m_uniforms, material);
  16623. } else if (material.isSpriteMaterial) {
  16624. refreshUniformsSprites(m_uniforms, material);
  16625. } else if (material.isShadowMaterial) {
  16626. m_uniforms.color.value.copy(material.color);
  16627. m_uniforms.opacity.value = material.opacity;
  16628. } // RectAreaLight Texture
  16629. // TODO (mrdoob): Find a nicer implementation
  16630. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  16631. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  16632. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16633. }
  16634. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16635. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16636. material.uniformsNeedUpdate = false;
  16637. }
  16638. if (material.isSpriteMaterial) {
  16639. p_uniforms.setValue(_gl, 'center', object.center);
  16640. } // common matrices
  16641. if (program.numMultiviewViews > 0) {
  16642. multiview.updateObjectMatricesUniforms(object, camera, p_uniforms);
  16643. } else {
  16644. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16645. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16646. }
  16647. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16648. return program;
  16649. } // Uniforms (refresh uniforms objects)
  16650. function refreshUniformsCommon(uniforms, material) {
  16651. uniforms.opacity.value = material.opacity;
  16652. if (material.color) {
  16653. uniforms.diffuse.value.copy(material.color);
  16654. }
  16655. if (material.emissive) {
  16656. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  16657. }
  16658. if (material.map) {
  16659. uniforms.map.value = material.map;
  16660. }
  16661. if (material.alphaMap) {
  16662. uniforms.alphaMap.value = material.alphaMap;
  16663. }
  16664. if (material.specularMap) {
  16665. uniforms.specularMap.value = material.specularMap;
  16666. }
  16667. if (material.envMap) {
  16668. uniforms.envMap.value = material.envMap; // don't flip CubeTexture envMaps, flip everything else:
  16669. // WebGLRenderTargetCube will be flipped for backwards compatibility
  16670. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  16671. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  16672. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  16673. uniforms.reflectivity.value = material.reflectivity;
  16674. uniforms.refractionRatio.value = material.refractionRatio;
  16675. uniforms.maxMipLevel.value = properties.get(material.envMap).__maxMipLevel;
  16676. }
  16677. if (material.lightMap) {
  16678. uniforms.lightMap.value = material.lightMap;
  16679. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16680. }
  16681. if (material.aoMap) {
  16682. uniforms.aoMap.value = material.aoMap;
  16683. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16684. } // uv repeat and offset setting priorities
  16685. // 1. color map
  16686. // 2. specular map
  16687. // 3. normal map
  16688. // 4. bump map
  16689. // 5. alpha map
  16690. // 6. emissive map
  16691. var uvScaleMap;
  16692. if (material.map) {
  16693. uvScaleMap = material.map;
  16694. } else if (material.specularMap) {
  16695. uvScaleMap = material.specularMap;
  16696. } else if (material.displacementMap) {
  16697. uvScaleMap = material.displacementMap;
  16698. } else if (material.normalMap) {
  16699. uvScaleMap = material.normalMap;
  16700. } else if (material.bumpMap) {
  16701. uvScaleMap = material.bumpMap;
  16702. } else if (material.roughnessMap) {
  16703. uvScaleMap = material.roughnessMap;
  16704. } else if (material.metalnessMap) {
  16705. uvScaleMap = material.metalnessMap;
  16706. } else if (material.alphaMap) {
  16707. uvScaleMap = material.alphaMap;
  16708. } else if (material.emissiveMap) {
  16709. uvScaleMap = material.emissiveMap;
  16710. }
  16711. if (uvScaleMap !== undefined) {
  16712. // backwards compatibility
  16713. if (uvScaleMap.isWebGLRenderTarget) {
  16714. uvScaleMap = uvScaleMap.texture;
  16715. }
  16716. if (uvScaleMap.matrixAutoUpdate === true) {
  16717. uvScaleMap.updateMatrix();
  16718. }
  16719. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  16720. }
  16721. }
  16722. function refreshUniformsLine(uniforms, material) {
  16723. uniforms.diffuse.value.copy(material.color);
  16724. uniforms.opacity.value = material.opacity;
  16725. }
  16726. function refreshUniformsDash(uniforms, material) {
  16727. uniforms.dashSize.value = material.dashSize;
  16728. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16729. uniforms.scale.value = material.scale;
  16730. }
  16731. function refreshUniformsPoints(uniforms, material) {
  16732. uniforms.diffuse.value.copy(material.color);
  16733. uniforms.opacity.value = material.opacity;
  16734. uniforms.size.value = material.size * _pixelRatio;
  16735. uniforms.scale.value = _height * 0.5;
  16736. uniforms.map.value = material.map;
  16737. if (material.map !== null) {
  16738. if (material.map.matrixAutoUpdate === true) {
  16739. material.map.updateMatrix();
  16740. }
  16741. uniforms.uvTransform.value.copy(material.map.matrix);
  16742. }
  16743. }
  16744. function refreshUniformsSprites(uniforms, material) {
  16745. uniforms.diffuse.value.copy(material.color);
  16746. uniforms.opacity.value = material.opacity;
  16747. uniforms.rotation.value = material.rotation;
  16748. uniforms.map.value = material.map;
  16749. if (material.map !== null) {
  16750. if (material.map.matrixAutoUpdate === true) {
  16751. material.map.updateMatrix();
  16752. }
  16753. uniforms.uvTransform.value.copy(material.map.matrix);
  16754. }
  16755. }
  16756. function refreshUniformsFog(uniforms, fog) {
  16757. uniforms.fogColor.value.copy(fog.color);
  16758. if (fog.isFog) {
  16759. uniforms.fogNear.value = fog.near;
  16760. uniforms.fogFar.value = fog.far;
  16761. } else if (fog.isFogExp2) {
  16762. uniforms.fogDensity.value = fog.density;
  16763. }
  16764. }
  16765. function refreshUniformsLambert(uniforms, material) {
  16766. if (material.emissiveMap) {
  16767. uniforms.emissiveMap.value = material.emissiveMap;
  16768. }
  16769. }
  16770. function refreshUniformsPhong(uniforms, material) {
  16771. uniforms.specular.value.copy(material.specular);
  16772. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  16773. if (material.emissiveMap) {
  16774. uniforms.emissiveMap.value = material.emissiveMap;
  16775. }
  16776. if (material.bumpMap) {
  16777. uniforms.bumpMap.value = material.bumpMap;
  16778. uniforms.bumpScale.value = material.bumpScale;
  16779. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16780. }
  16781. if (material.normalMap) {
  16782. uniforms.normalMap.value = material.normalMap;
  16783. uniforms.normalScale.value.copy(material.normalScale);
  16784. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16785. }
  16786. if (material.displacementMap) {
  16787. uniforms.displacementMap.value = material.displacementMap;
  16788. uniforms.displacementScale.value = material.displacementScale;
  16789. uniforms.displacementBias.value = material.displacementBias;
  16790. }
  16791. }
  16792. function refreshUniformsToon(uniforms, material) {
  16793. refreshUniformsPhong(uniforms, material);
  16794. if (material.gradientMap) {
  16795. uniforms.gradientMap.value = material.gradientMap;
  16796. }
  16797. }
  16798. function refreshUniformsStandard(uniforms, material) {
  16799. uniforms.roughness.value = material.roughness;
  16800. uniforms.metalness.value = material.metalness;
  16801. if (material.roughnessMap) {
  16802. uniforms.roughnessMap.value = material.roughnessMap;
  16803. }
  16804. if (material.metalnessMap) {
  16805. uniforms.metalnessMap.value = material.metalnessMap;
  16806. }
  16807. if (material.emissiveMap) {
  16808. uniforms.emissiveMap.value = material.emissiveMap;
  16809. }
  16810. if (material.bumpMap) {
  16811. uniforms.bumpMap.value = material.bumpMap;
  16812. uniforms.bumpScale.value = material.bumpScale;
  16813. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16814. }
  16815. if (material.normalMap) {
  16816. uniforms.normalMap.value = material.normalMap;
  16817. uniforms.normalScale.value.copy(material.normalScale);
  16818. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16819. }
  16820. if (material.displacementMap) {
  16821. uniforms.displacementMap.value = material.displacementMap;
  16822. uniforms.displacementScale.value = material.displacementScale;
  16823. uniforms.displacementBias.value = material.displacementBias;
  16824. }
  16825. if (material.envMap) {
  16826. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16827. uniforms.envMapIntensity.value = material.envMapIntensity;
  16828. }
  16829. }
  16830. function refreshUniformsPhysical(uniforms, material) {
  16831. refreshUniformsStandard(uniforms, material);
  16832. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  16833. uniforms.clearcoat.value = material.clearcoat;
  16834. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16835. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  16836. if (material.clearcoatNormalMap) {
  16837. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  16838. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16839. if (material.side === BackSide) {
  16840. uniforms.clearcoatNormalScale.value.negate();
  16841. }
  16842. }
  16843. uniforms.transparency.value = material.transparency;
  16844. }
  16845. function refreshUniformsMatcap(uniforms, material) {
  16846. if (material.matcap) {
  16847. uniforms.matcap.value = material.matcap;
  16848. }
  16849. if (material.bumpMap) {
  16850. uniforms.bumpMap.value = material.bumpMap;
  16851. uniforms.bumpScale.value = material.bumpScale;
  16852. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16853. }
  16854. if (material.normalMap) {
  16855. uniforms.normalMap.value = material.normalMap;
  16856. uniforms.normalScale.value.copy(material.normalScale);
  16857. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16858. }
  16859. if (material.displacementMap) {
  16860. uniforms.displacementMap.value = material.displacementMap;
  16861. uniforms.displacementScale.value = material.displacementScale;
  16862. uniforms.displacementBias.value = material.displacementBias;
  16863. }
  16864. }
  16865. function refreshUniformsDepth(uniforms, material) {
  16866. if (material.displacementMap) {
  16867. uniforms.displacementMap.value = material.displacementMap;
  16868. uniforms.displacementScale.value = material.displacementScale;
  16869. uniforms.displacementBias.value = material.displacementBias;
  16870. }
  16871. }
  16872. function refreshUniformsDistance(uniforms, material) {
  16873. if (material.displacementMap) {
  16874. uniforms.displacementMap.value = material.displacementMap;
  16875. uniforms.displacementScale.value = material.displacementScale;
  16876. uniforms.displacementBias.value = material.displacementBias;
  16877. }
  16878. uniforms.referencePosition.value.copy(material.referencePosition);
  16879. uniforms.nearDistance.value = material.nearDistance;
  16880. uniforms.farDistance.value = material.farDistance;
  16881. }
  16882. function refreshUniformsNormal(uniforms, material) {
  16883. if (material.bumpMap) {
  16884. uniforms.bumpMap.value = material.bumpMap;
  16885. uniforms.bumpScale.value = material.bumpScale;
  16886. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16887. }
  16888. if (material.normalMap) {
  16889. uniforms.normalMap.value = material.normalMap;
  16890. uniforms.normalScale.value.copy(material.normalScale);
  16891. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16892. }
  16893. if (material.displacementMap) {
  16894. uniforms.displacementMap.value = material.displacementMap;
  16895. uniforms.displacementScale.value = material.displacementScale;
  16896. uniforms.displacementBias.value = material.displacementBias;
  16897. }
  16898. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16899. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16900. uniforms.ambientLightColor.needsUpdate = value;
  16901. uniforms.lightProbe.needsUpdate = value;
  16902. uniforms.directionalLights.needsUpdate = value;
  16903. uniforms.pointLights.needsUpdate = value;
  16904. uniforms.spotLights.needsUpdate = value;
  16905. uniforms.rectAreaLights.needsUpdate = value;
  16906. uniforms.hemisphereLights.needsUpdate = value;
  16907. }
  16908. function materialNeedsLights(material) {
  16909. return material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16910. } //
  16911. this.setFramebuffer = function (value) {
  16912. if (_framebuffer !== value) _gl.bindFramebuffer(36160, value);
  16913. _framebuffer = value;
  16914. };
  16915. this.getActiveCubeFace = function () {
  16916. return _currentActiveCubeFace;
  16917. };
  16918. this.getActiveMipmapLevel = function () {
  16919. return _currentActiveMipmapLevel;
  16920. };
  16921. this.getRenderTarget = function () {
  16922. return _currentRenderTarget;
  16923. };
  16924. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  16925. _currentRenderTarget = renderTarget;
  16926. _currentActiveCubeFace = activeCubeFace;
  16927. _currentActiveMipmapLevel = activeMipmapLevel;
  16928. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  16929. textures.setupRenderTarget(renderTarget);
  16930. }
  16931. var framebuffer = _framebuffer;
  16932. var isCube = false;
  16933. if (renderTarget) {
  16934. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16935. if (renderTarget.isWebGLRenderTargetCube) {
  16936. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  16937. isCube = true;
  16938. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  16939. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16940. } else {
  16941. framebuffer = __webglFramebuffer;
  16942. }
  16943. _currentViewport.copy(renderTarget.viewport);
  16944. _currentScissor.copy(renderTarget.scissor);
  16945. _currentScissorTest = renderTarget.scissorTest;
  16946. } else {
  16947. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16948. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16949. _currentScissorTest = _scissorTest;
  16950. }
  16951. if (_currentFramebuffer !== framebuffer) {
  16952. _gl.bindFramebuffer(36160, framebuffer);
  16953. _currentFramebuffer = framebuffer;
  16954. }
  16955. state.viewport(_currentViewport);
  16956. state.scissor(_currentScissor);
  16957. state.setScissorTest(_currentScissorTest);
  16958. if (isCube) {
  16959. var textureProperties = properties.get(renderTarget.texture);
  16960. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  16961. }
  16962. };
  16963. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16964. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16965. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16966. return;
  16967. }
  16968. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16969. if (renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined) {
  16970. framebuffer = framebuffer[activeCubeFaceIndex];
  16971. }
  16972. if (framebuffer) {
  16973. var restore = false;
  16974. if (framebuffer !== _currentFramebuffer) {
  16975. _gl.bindFramebuffer(36160, framebuffer);
  16976. restore = true;
  16977. }
  16978. try {
  16979. var texture = renderTarget.texture;
  16980. var textureFormat = texture.format;
  16981. var textureType = texture.type;
  16982. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  16983. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16984. return;
  16985. }
  16986. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  16987. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16988. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  16989. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16990. return;
  16991. }
  16992. if (_gl.checkFramebufferStatus(36160) === 36053) {
  16993. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16994. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16995. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16996. }
  16997. } else {
  16998. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16999. }
  17000. } finally {
  17001. if (restore) {
  17002. _gl.bindFramebuffer(36160, _currentFramebuffer);
  17003. }
  17004. }
  17005. }
  17006. };
  17007. this.copyFramebufferToTexture = function (position, texture, level) {
  17008. var width = texture.image.width;
  17009. var height = texture.image.height;
  17010. var glFormat = utils.convert(texture.format);
  17011. textures.setTexture2D(texture, 0);
  17012. _gl.copyTexImage2D(3553, level || 0, glFormat, position.x, position.y, width, height, 0);
  17013. };
  17014. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  17015. var width = srcTexture.image.width;
  17016. var height = srcTexture.image.height;
  17017. var glFormat = utils.convert(dstTexture.format);
  17018. var glType = utils.convert(dstTexture.type);
  17019. textures.setTexture2D(dstTexture, 0);
  17020. if (srcTexture.isDataTexture) {
  17021. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  17022. } else {
  17023. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  17024. }
  17025. };
  17026. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17027. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17028. detail: this
  17029. })); // eslint-disable-line no-undef
  17030. }
  17031. }
  17032. /**
  17033. * @author mrdoob / http://mrdoob.com/
  17034. * @author alteredq / http://alteredqualia.com/
  17035. */
  17036. function FogExp2(color, density) {
  17037. this.name = '';
  17038. this.color = new Color(color);
  17039. this.density = density !== undefined ? density : 0.00025;
  17040. }
  17041. Object.assign(FogExp2.prototype, {
  17042. isFogExp2: true,
  17043. clone: function () {
  17044. return new FogExp2(this.color, this.density);
  17045. },
  17046. toJSON: function ()
  17047. /* meta */
  17048. {
  17049. return {
  17050. type: 'FogExp2',
  17051. color: this.color.getHex(),
  17052. density: this.density
  17053. };
  17054. }
  17055. });
  17056. /**
  17057. * @author mrdoob / http://mrdoob.com/
  17058. * @author alteredq / http://alteredqualia.com/
  17059. */
  17060. function Fog(color, near, far) {
  17061. this.name = '';
  17062. this.color = new Color(color);
  17063. this.near = near !== undefined ? near : 1;
  17064. this.far = far !== undefined ? far : 1000;
  17065. }
  17066. Object.assign(Fog.prototype, {
  17067. isFog: true,
  17068. clone: function () {
  17069. return new Fog(this.color, this.near, this.far);
  17070. },
  17071. toJSON: function ()
  17072. /* meta */
  17073. {
  17074. return {
  17075. type: 'Fog',
  17076. color: this.color.getHex(),
  17077. near: this.near,
  17078. far: this.far
  17079. };
  17080. }
  17081. });
  17082. /**
  17083. * @author benaadams / https://twitter.com/ben_a_adams
  17084. */
  17085. function InterleavedBuffer(array, stride) {
  17086. this.array = array;
  17087. this.stride = stride;
  17088. this.count = array !== undefined ? array.length / stride : 0;
  17089. this.dynamic = false;
  17090. this.updateRange = {
  17091. offset: 0,
  17092. count: -1
  17093. };
  17094. this.version = 0;
  17095. }
  17096. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  17097. set: function (value) {
  17098. if (value === true) this.version++;
  17099. }
  17100. });
  17101. Object.assign(InterleavedBuffer.prototype, {
  17102. isInterleavedBuffer: true,
  17103. onUploadCallback: function () {},
  17104. setDynamic: function (value) {
  17105. this.dynamic = value;
  17106. return this;
  17107. },
  17108. copy: function (source) {
  17109. this.array = new source.array.constructor(source.array);
  17110. this.count = source.count;
  17111. this.stride = source.stride;
  17112. this.dynamic = source.dynamic;
  17113. return this;
  17114. },
  17115. copyAt: function (index1, attribute, index2) {
  17116. index1 *= this.stride;
  17117. index2 *= attribute.stride;
  17118. for (var i = 0, l = this.stride; i < l; i++) {
  17119. this.array[index1 + i] = attribute.array[index2 + i];
  17120. }
  17121. return this;
  17122. },
  17123. set: function (value, offset) {
  17124. if (offset === undefined) offset = 0;
  17125. this.array.set(value, offset);
  17126. return this;
  17127. },
  17128. clone: function () {
  17129. return new this.constructor().copy(this);
  17130. },
  17131. onUpload: function (callback) {
  17132. this.onUploadCallback = callback;
  17133. return this;
  17134. }
  17135. });
  17136. /**
  17137. * @author benaadams / https://twitter.com/ben_a_adams
  17138. */
  17139. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  17140. this.data = interleavedBuffer;
  17141. this.itemSize = itemSize;
  17142. this.offset = offset;
  17143. this.normalized = normalized === true;
  17144. }
  17145. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  17146. count: {
  17147. get: function () {
  17148. return this.data.count;
  17149. }
  17150. },
  17151. array: {
  17152. get: function () {
  17153. return this.data.array;
  17154. }
  17155. }
  17156. });
  17157. Object.assign(InterleavedBufferAttribute.prototype, {
  17158. isInterleavedBufferAttribute: true,
  17159. setX: function (index, x) {
  17160. this.data.array[index * this.data.stride + this.offset] = x;
  17161. return this;
  17162. },
  17163. setY: function (index, y) {
  17164. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17165. return this;
  17166. },
  17167. setZ: function (index, z) {
  17168. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17169. return this;
  17170. },
  17171. setW: function (index, w) {
  17172. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17173. return this;
  17174. },
  17175. getX: function (index) {
  17176. return this.data.array[index * this.data.stride + this.offset];
  17177. },
  17178. getY: function (index) {
  17179. return this.data.array[index * this.data.stride + this.offset + 1];
  17180. },
  17181. getZ: function (index) {
  17182. return this.data.array[index * this.data.stride + this.offset + 2];
  17183. },
  17184. getW: function (index) {
  17185. return this.data.array[index * this.data.stride + this.offset + 3];
  17186. },
  17187. setXY: function (index, x, y) {
  17188. index = index * this.data.stride + this.offset;
  17189. this.data.array[index + 0] = x;
  17190. this.data.array[index + 1] = y;
  17191. return this;
  17192. },
  17193. setXYZ: function (index, x, y, z) {
  17194. index = index * this.data.stride + this.offset;
  17195. this.data.array[index + 0] = x;
  17196. this.data.array[index + 1] = y;
  17197. this.data.array[index + 2] = z;
  17198. return this;
  17199. },
  17200. setXYZW: function (index, x, y, z, w) {
  17201. index = index * this.data.stride + this.offset;
  17202. this.data.array[index + 0] = x;
  17203. this.data.array[index + 1] = y;
  17204. this.data.array[index + 2] = z;
  17205. this.data.array[index + 3] = w;
  17206. return this;
  17207. }
  17208. });
  17209. /**
  17210. * @author alteredq / http://alteredqualia.com/
  17211. *
  17212. * parameters = {
  17213. * color: <hex>,
  17214. * map: new THREE.Texture( <Image> ),
  17215. * rotation: <float>,
  17216. * sizeAttenuation: <bool>
  17217. * }
  17218. */
  17219. function SpriteMaterial(parameters) {
  17220. Material.call(this);
  17221. this.type = 'SpriteMaterial';
  17222. this.color = new Color(0xffffff);
  17223. this.map = null;
  17224. this.rotation = 0;
  17225. this.sizeAttenuation = true;
  17226. this.transparent = true;
  17227. this.setValues(parameters);
  17228. }
  17229. SpriteMaterial.prototype = Object.create(Material.prototype);
  17230. SpriteMaterial.prototype.constructor = SpriteMaterial;
  17231. SpriteMaterial.prototype.isSpriteMaterial = true;
  17232. SpriteMaterial.prototype.copy = function (source) {
  17233. Material.prototype.copy.call(this, source);
  17234. this.color.copy(source.color);
  17235. this.map = source.map;
  17236. this.rotation = source.rotation;
  17237. this.sizeAttenuation = source.sizeAttenuation;
  17238. return this;
  17239. };
  17240. /**
  17241. * @author mikael emtinger / http://gomo.se/
  17242. * @author alteredq / http://alteredqualia.com/
  17243. */
  17244. var _geometry;
  17245. var _intersectPoint = new Vector3();
  17246. var _worldScale = new Vector3();
  17247. var _mvPosition = new Vector3();
  17248. var _alignedPosition = new Vector2();
  17249. var _rotatedPosition = new Vector2();
  17250. var _viewWorldMatrix = new Matrix4();
  17251. var _vA$1 = new Vector3();
  17252. var _vB$1 = new Vector3();
  17253. var _vC$1 = new Vector3();
  17254. var _uvA$1 = new Vector2();
  17255. var _uvB$1 = new Vector2();
  17256. var _uvC$1 = new Vector2();
  17257. function Sprite(material) {
  17258. Object3D.call(this);
  17259. this.type = 'Sprite';
  17260. if (_geometry === undefined) {
  17261. _geometry = new BufferGeometry();
  17262. 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]);
  17263. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17264. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17265. _geometry.addAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17266. _geometry.addAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17267. }
  17268. this.geometry = _geometry;
  17269. this.material = material !== undefined ? material : new SpriteMaterial();
  17270. this.center = new Vector2(0.5, 0.5);
  17271. }
  17272. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  17273. constructor: Sprite,
  17274. isSprite: true,
  17275. raycast: function (raycaster, intersects) {
  17276. if (raycaster.camera === null) {
  17277. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17278. }
  17279. _worldScale.setFromMatrixScale(this.matrixWorld);
  17280. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17281. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17282. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17283. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17284. _worldScale.multiplyScalar(-_mvPosition.z);
  17285. }
  17286. var rotation = this.material.rotation;
  17287. var sin, cos;
  17288. if (rotation !== 0) {
  17289. cos = Math.cos(rotation);
  17290. sin = Math.sin(rotation);
  17291. }
  17292. var center = this.center;
  17293. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17294. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17295. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17296. _uvA$1.set(0, 0);
  17297. _uvB$1.set(1, 0);
  17298. _uvC$1.set(1, 1); // check first triangle
  17299. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  17300. if (intersect === null) {
  17301. // check second triangle
  17302. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17303. _uvB$1.set(0, 1);
  17304. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  17305. if (intersect === null) {
  17306. return;
  17307. }
  17308. }
  17309. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17310. if (distance < raycaster.near || distance > raycaster.far) return;
  17311. intersects.push({
  17312. distance: distance,
  17313. point: _intersectPoint.clone(),
  17314. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  17315. face: null,
  17316. object: this
  17317. });
  17318. },
  17319. clone: function () {
  17320. return new this.constructor(this.material).copy(this);
  17321. },
  17322. copy: function (source) {
  17323. Object3D.prototype.copy.call(this, source);
  17324. if (source.center !== undefined) this.center.copy(source.center);
  17325. return this;
  17326. }
  17327. });
  17328. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17329. // compute position in camera space
  17330. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17331. if (sin !== undefined) {
  17332. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17333. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17334. } else {
  17335. _rotatedPosition.copy(_alignedPosition);
  17336. }
  17337. vertexPosition.copy(mvPosition);
  17338. vertexPosition.x += _rotatedPosition.x;
  17339. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17340. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17341. }
  17342. /**
  17343. * @author mikael emtinger / http://gomo.se/
  17344. * @author alteredq / http://alteredqualia.com/
  17345. * @author mrdoob / http://mrdoob.com/
  17346. */
  17347. var _v1$4 = new Vector3();
  17348. var _v2$2 = new Vector3();
  17349. function LOD() {
  17350. Object3D.call(this);
  17351. this.type = 'LOD';
  17352. Object.defineProperties(this, {
  17353. levels: {
  17354. enumerable: true,
  17355. value: []
  17356. }
  17357. });
  17358. this.autoUpdate = true;
  17359. }
  17360. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  17361. constructor: LOD,
  17362. isLOD: true,
  17363. copy: function (source) {
  17364. Object3D.prototype.copy.call(this, source, false);
  17365. var levels = source.levels;
  17366. for (var i = 0, l = levels.length; i < l; i++) {
  17367. var level = levels[i];
  17368. this.addLevel(level.object.clone(), level.distance);
  17369. }
  17370. return this;
  17371. },
  17372. addLevel: function (object, distance) {
  17373. if (distance === undefined) distance = 0;
  17374. distance = Math.abs(distance);
  17375. var levels = this.levels;
  17376. for (var l = 0; l < levels.length; l++) {
  17377. if (distance < levels[l].distance) {
  17378. break;
  17379. }
  17380. }
  17381. levels.splice(l, 0, {
  17382. distance: distance,
  17383. object: object
  17384. });
  17385. this.add(object);
  17386. return this;
  17387. },
  17388. getObjectForDistance: function (distance) {
  17389. var levels = this.levels;
  17390. for (var i = 1, l = levels.length; i < l; i++) {
  17391. if (distance < levels[i].distance) {
  17392. break;
  17393. }
  17394. }
  17395. return levels[i - 1].object;
  17396. },
  17397. raycast: function (raycaster, intersects) {
  17398. _v1$4.setFromMatrixPosition(this.matrixWorld);
  17399. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  17400. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17401. },
  17402. update: function (camera) {
  17403. var levels = this.levels;
  17404. if (levels.length > 1) {
  17405. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  17406. _v2$2.setFromMatrixPosition(this.matrixWorld);
  17407. var distance = _v1$4.distanceTo(_v2$2);
  17408. levels[0].object.visible = true;
  17409. for (var i = 1, l = levels.length; i < l; i++) {
  17410. if (distance >= levels[i].distance) {
  17411. levels[i - 1].object.visible = false;
  17412. levels[i].object.visible = true;
  17413. } else {
  17414. break;
  17415. }
  17416. }
  17417. for (; i < l; i++) {
  17418. levels[i].object.visible = false;
  17419. }
  17420. }
  17421. },
  17422. toJSON: function (meta) {
  17423. var data = Object3D.prototype.toJSON.call(this, meta);
  17424. data.object.levels = [];
  17425. var levels = this.levels;
  17426. for (var i = 0, l = levels.length; i < l; i++) {
  17427. var level = levels[i];
  17428. data.object.levels.push({
  17429. object: level.object.uuid,
  17430. distance: level.distance
  17431. });
  17432. }
  17433. return data;
  17434. }
  17435. });
  17436. /**
  17437. * @author mikael emtinger / http://gomo.se/
  17438. * @author alteredq / http://alteredqualia.com/
  17439. * @author ikerr / http://verold.com
  17440. */
  17441. function SkinnedMesh(geometry, material) {
  17442. if (geometry && geometry.isGeometry) {
  17443. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17444. }
  17445. Mesh.call(this, geometry, material);
  17446. this.type = 'SkinnedMesh';
  17447. this.bindMode = 'attached';
  17448. this.bindMatrix = new Matrix4();
  17449. this.bindMatrixInverse = new Matrix4();
  17450. }
  17451. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17452. constructor: SkinnedMesh,
  17453. isSkinnedMesh: true,
  17454. bind: function (skeleton, bindMatrix) {
  17455. this.skeleton = skeleton;
  17456. if (bindMatrix === undefined) {
  17457. this.updateMatrixWorld(true);
  17458. this.skeleton.calculateInverses();
  17459. bindMatrix = this.matrixWorld;
  17460. }
  17461. this.bindMatrix.copy(bindMatrix);
  17462. this.bindMatrixInverse.getInverse(bindMatrix);
  17463. },
  17464. pose: function () {
  17465. this.skeleton.pose();
  17466. },
  17467. normalizeSkinWeights: function () {
  17468. var vector = new Vector4();
  17469. var skinWeight = this.geometry.attributes.skinWeight;
  17470. for (var i = 0, l = skinWeight.count; i < l; i++) {
  17471. vector.x = skinWeight.getX(i);
  17472. vector.y = skinWeight.getY(i);
  17473. vector.z = skinWeight.getZ(i);
  17474. vector.w = skinWeight.getW(i);
  17475. var scale = 1.0 / vector.manhattanLength();
  17476. if (scale !== Infinity) {
  17477. vector.multiplyScalar(scale);
  17478. } else {
  17479. vector.set(1, 0, 0, 0); // do something reasonable
  17480. }
  17481. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17482. }
  17483. },
  17484. updateMatrixWorld: function (force) {
  17485. Mesh.prototype.updateMatrixWorld.call(this, force);
  17486. if (this.bindMode === 'attached') {
  17487. this.bindMatrixInverse.getInverse(this.matrixWorld);
  17488. } else if (this.bindMode === 'detached') {
  17489. this.bindMatrixInverse.getInverse(this.bindMatrix);
  17490. } else {
  17491. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17492. }
  17493. },
  17494. clone: function () {
  17495. return new this.constructor(this.geometry, this.material).copy(this);
  17496. }
  17497. });
  17498. /**
  17499. * @author mikael emtinger / http://gomo.se/
  17500. * @author alteredq / http://alteredqualia.com/
  17501. * @author michael guerrero / http://realitymeltdown.com
  17502. * @author ikerr / http://verold.com
  17503. */
  17504. var _offsetMatrix = new Matrix4();
  17505. var _identityMatrix = new Matrix4();
  17506. function Skeleton(bones, boneInverses) {
  17507. // copy the bone array
  17508. bones = bones || [];
  17509. this.bones = bones.slice(0);
  17510. this.boneMatrices = new Float32Array(this.bones.length * 16);
  17511. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  17512. if (boneInverses === undefined) {
  17513. this.calculateInverses();
  17514. } else {
  17515. if (this.bones.length === boneInverses.length) {
  17516. this.boneInverses = boneInverses.slice(0);
  17517. } else {
  17518. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  17519. this.boneInverses = [];
  17520. for (var i = 0, il = this.bones.length; i < il; i++) {
  17521. this.boneInverses.push(new Matrix4());
  17522. }
  17523. }
  17524. }
  17525. }
  17526. Object.assign(Skeleton.prototype, {
  17527. calculateInverses: function () {
  17528. this.boneInverses = [];
  17529. for (var i = 0, il = this.bones.length; i < il; i++) {
  17530. var inverse = new Matrix4();
  17531. if (this.bones[i]) {
  17532. inverse.getInverse(this.bones[i].matrixWorld);
  17533. }
  17534. this.boneInverses.push(inverse);
  17535. }
  17536. },
  17537. pose: function () {
  17538. var bone, i, il; // recover the bind-time world matrices
  17539. for (i = 0, il = this.bones.length; i < il; i++) {
  17540. bone = this.bones[i];
  17541. if (bone) {
  17542. bone.matrixWorld.getInverse(this.boneInverses[i]);
  17543. }
  17544. } // compute the local matrices, positions, rotations and scales
  17545. for (i = 0, il = this.bones.length; i < il; i++) {
  17546. bone = this.bones[i];
  17547. if (bone) {
  17548. if (bone.parent && bone.parent.isBone) {
  17549. bone.matrix.getInverse(bone.parent.matrixWorld);
  17550. bone.matrix.multiply(bone.matrixWorld);
  17551. } else {
  17552. bone.matrix.copy(bone.matrixWorld);
  17553. }
  17554. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17555. }
  17556. }
  17557. },
  17558. update: function () {
  17559. var bones = this.bones;
  17560. var boneInverses = this.boneInverses;
  17561. var boneMatrices = this.boneMatrices;
  17562. var boneTexture = this.boneTexture; // flatten bone matrices to array
  17563. for (var i = 0, il = bones.length; i < il; i++) {
  17564. // compute the offset between the current and the original transform
  17565. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17566. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17567. _offsetMatrix.toArray(boneMatrices, i * 16);
  17568. }
  17569. if (boneTexture !== undefined) {
  17570. boneTexture.needsUpdate = true;
  17571. }
  17572. },
  17573. clone: function () {
  17574. return new Skeleton(this.bones, this.boneInverses);
  17575. },
  17576. getBoneByName: function (name) {
  17577. for (var i = 0, il = this.bones.length; i < il; i++) {
  17578. var bone = this.bones[i];
  17579. if (bone.name === name) {
  17580. return bone;
  17581. }
  17582. }
  17583. return undefined;
  17584. }
  17585. });
  17586. /**
  17587. * @author mikael emtinger / http://gomo.se/
  17588. * @author alteredq / http://alteredqualia.com/
  17589. * @author ikerr / http://verold.com
  17590. */
  17591. function Bone() {
  17592. Object3D.call(this);
  17593. this.type = 'Bone';
  17594. }
  17595. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  17596. constructor: Bone,
  17597. isBone: true
  17598. });
  17599. /**
  17600. * @author mrdoob / http://mrdoob.com/
  17601. */
  17602. function InstancedMesh(geometry, material, count) {
  17603. Mesh.call(this, geometry, material);
  17604. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  17605. this.count = count;
  17606. }
  17607. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17608. constructor: InstancedMesh,
  17609. isInstancedMesh: true,
  17610. raycast: function () {},
  17611. setMatrixAt: function (index, matrix) {
  17612. matrix.toArray(this.instanceMatrix.array, index * 16);
  17613. },
  17614. updateMorphTargets: function () {}
  17615. });
  17616. /**
  17617. * @author mrdoob / http://mrdoob.com/
  17618. * @author alteredq / http://alteredqualia.com/
  17619. *
  17620. * parameters = {
  17621. * color: <hex>,
  17622. * opacity: <float>,
  17623. *
  17624. * linewidth: <float>,
  17625. * linecap: "round",
  17626. * linejoin: "round"
  17627. * }
  17628. */
  17629. function LineBasicMaterial(parameters) {
  17630. Material.call(this);
  17631. this.type = 'LineBasicMaterial';
  17632. this.color = new Color(0xffffff);
  17633. this.linewidth = 1;
  17634. this.linecap = 'round';
  17635. this.linejoin = 'round';
  17636. this.setValues(parameters);
  17637. }
  17638. LineBasicMaterial.prototype = Object.create(Material.prototype);
  17639. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  17640. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17641. LineBasicMaterial.prototype.copy = function (source) {
  17642. Material.prototype.copy.call(this, source);
  17643. this.color.copy(source.color);
  17644. this.linewidth = source.linewidth;
  17645. this.linecap = source.linecap;
  17646. this.linejoin = source.linejoin;
  17647. return this;
  17648. };
  17649. /**
  17650. * @author mrdoob / http://mrdoob.com/
  17651. */
  17652. var _start = new Vector3();
  17653. var _end = new Vector3();
  17654. var _inverseMatrix$1 = new Matrix4();
  17655. var _ray$1 = new Ray();
  17656. var _sphere$2 = new Sphere();
  17657. function Line(geometry, material, mode) {
  17658. if (mode === 1) {
  17659. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  17660. }
  17661. Object3D.call(this);
  17662. this.type = 'Line';
  17663. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17664. this.material = material !== undefined ? material : new LineBasicMaterial({
  17665. color: Math.random() * 0xffffff
  17666. });
  17667. }
  17668. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  17669. constructor: Line,
  17670. isLine: true,
  17671. computeLineDistances: function () {
  17672. var geometry = this.geometry;
  17673. if (geometry.isBufferGeometry) {
  17674. // we assume non-indexed geometry
  17675. if (geometry.index === null) {
  17676. var positionAttribute = geometry.attributes.position;
  17677. var lineDistances = [0];
  17678. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  17679. _start.fromBufferAttribute(positionAttribute, i - 1);
  17680. _end.fromBufferAttribute(positionAttribute, i);
  17681. lineDistances[i] = lineDistances[i - 1];
  17682. lineDistances[i] += _start.distanceTo(_end);
  17683. }
  17684. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17685. } else {
  17686. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17687. }
  17688. } else if (geometry.isGeometry) {
  17689. var vertices = geometry.vertices;
  17690. var lineDistances = geometry.lineDistances;
  17691. lineDistances[0] = 0;
  17692. for (var i = 1, l = vertices.length; i < l; i++) {
  17693. lineDistances[i] = lineDistances[i - 1];
  17694. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  17695. }
  17696. }
  17697. return this;
  17698. },
  17699. raycast: function (raycaster, intersects) {
  17700. var precision = raycaster.linePrecision;
  17701. var geometry = this.geometry;
  17702. var matrixWorld = this.matrixWorld; // Checking boundingSphere distance to ray
  17703. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17704. _sphere$2.copy(geometry.boundingSphere);
  17705. _sphere$2.applyMatrix4(matrixWorld);
  17706. _sphere$2.radius += precision;
  17707. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  17708. _inverseMatrix$1.getInverse(matrixWorld);
  17709. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17710. var localPrecision = precision / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17711. var localPrecisionSq = localPrecision * localPrecision;
  17712. var vStart = new Vector3();
  17713. var vEnd = new Vector3();
  17714. var interSegment = new Vector3();
  17715. var interRay = new Vector3();
  17716. var step = this && this.isLineSegments ? 2 : 1;
  17717. if (geometry.isBufferGeometry) {
  17718. var index = geometry.index;
  17719. var attributes = geometry.attributes;
  17720. var positions = attributes.position.array;
  17721. if (index !== null) {
  17722. var indices = index.array;
  17723. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  17724. var a = indices[i];
  17725. var b = indices[i + 1];
  17726. vStart.fromArray(positions, a * 3);
  17727. vEnd.fromArray(positions, b * 3);
  17728. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17729. if (distSq > localPrecisionSq) continue;
  17730. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17731. var distance = raycaster.ray.origin.distanceTo(interRay);
  17732. if (distance < raycaster.near || distance > raycaster.far) continue;
  17733. intersects.push({
  17734. distance: distance,
  17735. // What do we want? intersection point on the ray or on the segment??
  17736. // point: raycaster.ray.at( distance ),
  17737. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17738. index: i,
  17739. face: null,
  17740. faceIndex: null,
  17741. object: this
  17742. });
  17743. }
  17744. } else {
  17745. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  17746. vStart.fromArray(positions, 3 * i);
  17747. vEnd.fromArray(positions, 3 * i + 3);
  17748. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17749. if (distSq > localPrecisionSq) continue;
  17750. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17751. var distance = raycaster.ray.origin.distanceTo(interRay);
  17752. if (distance < raycaster.near || distance > raycaster.far) continue;
  17753. intersects.push({
  17754. distance: distance,
  17755. // What do we want? intersection point on the ray or on the segment??
  17756. // point: raycaster.ray.at( distance ),
  17757. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17758. index: i,
  17759. face: null,
  17760. faceIndex: null,
  17761. object: this
  17762. });
  17763. }
  17764. }
  17765. } else if (geometry.isGeometry) {
  17766. var vertices = geometry.vertices;
  17767. var nbVertices = vertices.length;
  17768. for (var i = 0; i < nbVertices - 1; i += step) {
  17769. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  17770. if (distSq > localPrecisionSq) continue;
  17771. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17772. var distance = raycaster.ray.origin.distanceTo(interRay);
  17773. if (distance < raycaster.near || distance > raycaster.far) continue;
  17774. intersects.push({
  17775. distance: distance,
  17776. // What do we want? intersection point on the ray or on the segment??
  17777. // point: raycaster.ray.at( distance ),
  17778. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17779. index: i,
  17780. face: null,
  17781. faceIndex: null,
  17782. object: this
  17783. });
  17784. }
  17785. }
  17786. },
  17787. clone: function () {
  17788. return new this.constructor(this.geometry, this.material).copy(this);
  17789. }
  17790. });
  17791. /**
  17792. * @author mrdoob / http://mrdoob.com/
  17793. */
  17794. var _start$1 = new Vector3();
  17795. var _end$1 = new Vector3();
  17796. function LineSegments(geometry, material) {
  17797. Line.call(this, geometry, material);
  17798. this.type = 'LineSegments';
  17799. }
  17800. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  17801. constructor: LineSegments,
  17802. isLineSegments: true,
  17803. computeLineDistances: function () {
  17804. var geometry = this.geometry;
  17805. if (geometry.isBufferGeometry) {
  17806. // we assume non-indexed geometry
  17807. if (geometry.index === null) {
  17808. var positionAttribute = geometry.attributes.position;
  17809. var lineDistances = [];
  17810. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  17811. _start$1.fromBufferAttribute(positionAttribute, i);
  17812. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  17813. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17814. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17815. }
  17816. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17817. } else {
  17818. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17819. }
  17820. } else if (geometry.isGeometry) {
  17821. var vertices = geometry.vertices;
  17822. var lineDistances = geometry.lineDistances;
  17823. for (var i = 0, l = vertices.length; i < l; i += 2) {
  17824. _start$1.copy(vertices[i]);
  17825. _end$1.copy(vertices[i + 1]);
  17826. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17827. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17828. }
  17829. }
  17830. return this;
  17831. }
  17832. });
  17833. /**
  17834. * @author mgreter / http://github.com/mgreter
  17835. */
  17836. function LineLoop(geometry, material) {
  17837. Line.call(this, geometry, material);
  17838. this.type = 'LineLoop';
  17839. }
  17840. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  17841. constructor: LineLoop,
  17842. isLineLoop: true
  17843. });
  17844. /**
  17845. * @author mrdoob / http://mrdoob.com/
  17846. * @author alteredq / http://alteredqualia.com/
  17847. *
  17848. * parameters = {
  17849. * color: <hex>,
  17850. * opacity: <float>,
  17851. * map: new THREE.Texture( <Image> ),
  17852. *
  17853. * size: <float>,
  17854. * sizeAttenuation: <bool>
  17855. *
  17856. * morphTargets: <bool>
  17857. * }
  17858. */
  17859. function PointsMaterial(parameters) {
  17860. Material.call(this);
  17861. this.type = 'PointsMaterial';
  17862. this.color = new Color(0xffffff);
  17863. this.map = null;
  17864. this.size = 1;
  17865. this.sizeAttenuation = true;
  17866. this.morphTargets = false;
  17867. this.setValues(parameters);
  17868. }
  17869. PointsMaterial.prototype = Object.create(Material.prototype);
  17870. PointsMaterial.prototype.constructor = PointsMaterial;
  17871. PointsMaterial.prototype.isPointsMaterial = true;
  17872. PointsMaterial.prototype.copy = function (source) {
  17873. Material.prototype.copy.call(this, source);
  17874. this.color.copy(source.color);
  17875. this.map = source.map;
  17876. this.size = source.size;
  17877. this.sizeAttenuation = source.sizeAttenuation;
  17878. this.morphTargets = source.morphTargets;
  17879. return this;
  17880. };
  17881. /**
  17882. * @author alteredq / http://alteredqualia.com/
  17883. */
  17884. var _inverseMatrix$2 = new Matrix4();
  17885. var _ray$2 = new Ray();
  17886. var _sphere$3 = new Sphere();
  17887. var _position$1 = new Vector3();
  17888. function Points(geometry, material) {
  17889. Object3D.call(this);
  17890. this.type = 'Points';
  17891. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17892. this.material = material !== undefined ? material : new PointsMaterial({
  17893. color: Math.random() * 0xffffff
  17894. });
  17895. this.updateMorphTargets();
  17896. }
  17897. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  17898. constructor: Points,
  17899. isPoints: true,
  17900. raycast: function (raycaster, intersects) {
  17901. var geometry = this.geometry;
  17902. var matrixWorld = this.matrixWorld;
  17903. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  17904. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17905. _sphere$3.copy(geometry.boundingSphere);
  17906. _sphere$3.applyMatrix4(matrixWorld);
  17907. _sphere$3.radius += threshold;
  17908. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  17909. _inverseMatrix$2.getInverse(matrixWorld);
  17910. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  17911. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17912. var localThresholdSq = localThreshold * localThreshold;
  17913. if (geometry.isBufferGeometry) {
  17914. var index = geometry.index;
  17915. var attributes = geometry.attributes;
  17916. var positions = attributes.position.array;
  17917. if (index !== null) {
  17918. var indices = index.array;
  17919. for (var i = 0, il = indices.length; i < il; i++) {
  17920. var a = indices[i];
  17921. _position$1.fromArray(positions, a * 3);
  17922. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17923. }
  17924. } else {
  17925. for (var i = 0, l = positions.length / 3; i < l; i++) {
  17926. _position$1.fromArray(positions, i * 3);
  17927. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17928. }
  17929. }
  17930. } else {
  17931. var vertices = geometry.vertices;
  17932. for (var i = 0, l = vertices.length; i < l; i++) {
  17933. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17934. }
  17935. }
  17936. },
  17937. updateMorphTargets: function () {
  17938. var geometry = this.geometry;
  17939. var m, ml, name;
  17940. if (geometry.isBufferGeometry) {
  17941. var morphAttributes = geometry.morphAttributes;
  17942. var keys = Object.keys(morphAttributes);
  17943. if (keys.length > 0) {
  17944. var morphAttribute = morphAttributes[keys[0]];
  17945. if (morphAttribute !== undefined) {
  17946. this.morphTargetInfluences = [];
  17947. this.morphTargetDictionary = {};
  17948. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  17949. name = morphAttribute[m].name || String(m);
  17950. this.morphTargetInfluences.push(0);
  17951. this.morphTargetDictionary[name] = m;
  17952. }
  17953. }
  17954. }
  17955. } else {
  17956. var morphTargets = geometry.morphTargets;
  17957. if (morphTargets !== undefined && morphTargets.length > 0) {
  17958. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17959. }
  17960. }
  17961. },
  17962. clone: function () {
  17963. return new this.constructor(this.geometry, this.material).copy(this);
  17964. }
  17965. });
  17966. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17967. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  17968. if (rayPointDistanceSq < localThresholdSq) {
  17969. var intersectPoint = new Vector3();
  17970. _ray$2.closestPointToPoint(point, intersectPoint);
  17971. intersectPoint.applyMatrix4(matrixWorld);
  17972. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17973. if (distance < raycaster.near || distance > raycaster.far) return;
  17974. intersects.push({
  17975. distance: distance,
  17976. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17977. point: intersectPoint,
  17978. index: index,
  17979. face: null,
  17980. object: object
  17981. });
  17982. }
  17983. }
  17984. /**
  17985. * @author mrdoob / http://mrdoob.com/
  17986. */
  17987. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17988. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17989. this.format = format !== undefined ? format : RGBFormat;
  17990. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17991. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17992. this.generateMipmaps = false;
  17993. }
  17994. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  17995. constructor: VideoTexture,
  17996. isVideoTexture: true,
  17997. update: function () {
  17998. var video = this.image;
  17999. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  18000. this.needsUpdate = true;
  18001. }
  18002. }
  18003. });
  18004. /**
  18005. * @author alteredq / http://alteredqualia.com/
  18006. */
  18007. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  18008. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  18009. this.image = {
  18010. width: width,
  18011. height: height
  18012. };
  18013. this.mipmaps = mipmaps; // no flipping for cube textures
  18014. // (also flipping doesn't work for compressed textures )
  18015. this.flipY = false; // can't generate mipmaps for compressed textures
  18016. // mips must be embedded in DDS files
  18017. this.generateMipmaps = false;
  18018. }
  18019. CompressedTexture.prototype = Object.create(Texture.prototype);
  18020. CompressedTexture.prototype.constructor = CompressedTexture;
  18021. CompressedTexture.prototype.isCompressedTexture = true;
  18022. /**
  18023. * @author mrdoob / http://mrdoob.com/
  18024. */
  18025. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18026. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18027. this.needsUpdate = true;
  18028. }
  18029. CanvasTexture.prototype = Object.create(Texture.prototype);
  18030. CanvasTexture.prototype.constructor = CanvasTexture;
  18031. CanvasTexture.prototype.isCanvasTexture = true;
  18032. /**
  18033. * @author Matt DesLauriers / @mattdesl
  18034. * @author atix / arthursilber.de
  18035. */
  18036. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  18037. format = format !== undefined ? format : DepthFormat;
  18038. if (format !== DepthFormat && format !== DepthStencilFormat) {
  18039. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  18040. }
  18041. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  18042. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  18043. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18044. this.image = {
  18045. width: width,
  18046. height: height
  18047. };
  18048. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18049. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18050. this.flipY = false;
  18051. this.generateMipmaps = false;
  18052. }
  18053. DepthTexture.prototype = Object.create(Texture.prototype);
  18054. DepthTexture.prototype.constructor = DepthTexture;
  18055. DepthTexture.prototype.isDepthTexture = true;
  18056. /**
  18057. * @author mrdoob / http://mrdoob.com/
  18058. * @author Mugen87 / https://github.com/Mugen87
  18059. */
  18060. function WireframeGeometry(geometry) {
  18061. BufferGeometry.call(this);
  18062. this.type = 'WireframeGeometry'; // buffer
  18063. var vertices = []; // helper variables
  18064. var i, j, l, o, ol;
  18065. var edge = [0, 0],
  18066. edges = {},
  18067. e,
  18068. edge1,
  18069. edge2;
  18070. var key,
  18071. keys = ['a', 'b', 'c'];
  18072. var vertex; // different logic for Geometry and BufferGeometry
  18073. if (geometry && geometry.isGeometry) {
  18074. // create a data structure that contains all edges without duplicates
  18075. var faces = geometry.faces;
  18076. for (i = 0, l = faces.length; i < l; i++) {
  18077. var face = faces[i];
  18078. for (j = 0; j < 3; j++) {
  18079. edge1 = face[keys[j]];
  18080. edge2 = face[keys[(j + 1) % 3]];
  18081. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18082. edge[1] = Math.max(edge1, edge2);
  18083. key = edge[0] + ',' + edge[1];
  18084. if (edges[key] === undefined) {
  18085. edges[key] = {
  18086. index1: edge[0],
  18087. index2: edge[1]
  18088. };
  18089. }
  18090. }
  18091. } // generate vertices
  18092. for (key in edges) {
  18093. e = edges[key];
  18094. vertex = geometry.vertices[e.index1];
  18095. vertices.push(vertex.x, vertex.y, vertex.z);
  18096. vertex = geometry.vertices[e.index2];
  18097. vertices.push(vertex.x, vertex.y, vertex.z);
  18098. }
  18099. } else if (geometry && geometry.isBufferGeometry) {
  18100. var position, indices, groups;
  18101. var group, start, count;
  18102. var index1, index2;
  18103. vertex = new Vector3();
  18104. if (geometry.index !== null) {
  18105. // indexed BufferGeometry
  18106. position = geometry.attributes.position;
  18107. indices = geometry.index;
  18108. groups = geometry.groups;
  18109. if (groups.length === 0) {
  18110. groups = [{
  18111. start: 0,
  18112. count: indices.count,
  18113. materialIndex: 0
  18114. }];
  18115. } // create a data structure that contains all eges without duplicates
  18116. for (o = 0, ol = groups.length; o < ol; ++o) {
  18117. group = groups[o];
  18118. start = group.start;
  18119. count = group.count;
  18120. for (i = start, l = start + count; i < l; i += 3) {
  18121. for (j = 0; j < 3; j++) {
  18122. edge1 = indices.getX(i + j);
  18123. edge2 = indices.getX(i + (j + 1) % 3);
  18124. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18125. edge[1] = Math.max(edge1, edge2);
  18126. key = edge[0] + ',' + edge[1];
  18127. if (edges[key] === undefined) {
  18128. edges[key] = {
  18129. index1: edge[0],
  18130. index2: edge[1]
  18131. };
  18132. }
  18133. }
  18134. }
  18135. } // generate vertices
  18136. for (key in edges) {
  18137. e = edges[key];
  18138. vertex.fromBufferAttribute(position, e.index1);
  18139. vertices.push(vertex.x, vertex.y, vertex.z);
  18140. vertex.fromBufferAttribute(position, e.index2);
  18141. vertices.push(vertex.x, vertex.y, vertex.z);
  18142. }
  18143. } else {
  18144. // non-indexed BufferGeometry
  18145. position = geometry.attributes.position;
  18146. for (i = 0, l = position.count / 3; i < l; i++) {
  18147. for (j = 0; j < 3; j++) {
  18148. // three edges per triangle, an edge is represented as (index1, index2)
  18149. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18150. index1 = 3 * i + j;
  18151. vertex.fromBufferAttribute(position, index1);
  18152. vertices.push(vertex.x, vertex.y, vertex.z);
  18153. index2 = 3 * i + (j + 1) % 3;
  18154. vertex.fromBufferAttribute(position, index2);
  18155. vertices.push(vertex.x, vertex.y, vertex.z);
  18156. }
  18157. }
  18158. }
  18159. } // build geometry
  18160. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18161. }
  18162. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  18163. WireframeGeometry.prototype.constructor = WireframeGeometry;
  18164. /**
  18165. * @author zz85 / https://github.com/zz85
  18166. * @author Mugen87 / https://github.com/Mugen87
  18167. *
  18168. * Parametric Surfaces Geometry
  18169. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18170. */
  18171. // ParametricGeometry
  18172. function ParametricGeometry(func, slices, stacks) {
  18173. Geometry.call(this);
  18174. this.type = 'ParametricGeometry';
  18175. this.parameters = {
  18176. func: func,
  18177. slices: slices,
  18178. stacks: stacks
  18179. };
  18180. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  18181. this.mergeVertices();
  18182. }
  18183. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  18184. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  18185. function ParametricBufferGeometry(func, slices, stacks) {
  18186. BufferGeometry.call(this);
  18187. this.type = 'ParametricBufferGeometry';
  18188. this.parameters = {
  18189. func: func,
  18190. slices: slices,
  18191. stacks: stacks
  18192. }; // buffers
  18193. var indices = [];
  18194. var vertices = [];
  18195. var normals = [];
  18196. var uvs = [];
  18197. var EPS = 0.00001;
  18198. var normal = new Vector3();
  18199. var p0 = new Vector3(),
  18200. p1 = new Vector3();
  18201. var pu = new Vector3(),
  18202. pv = new Vector3();
  18203. var i, j;
  18204. if (func.length < 3) {
  18205. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18206. } // generate vertices, normals and uvs
  18207. var sliceCount = slices + 1;
  18208. for (i = 0; i <= stacks; i++) {
  18209. var v = i / stacks;
  18210. for (j = 0; j <= slices; j++) {
  18211. var u = j / slices; // vertex
  18212. func(u, v, p0);
  18213. vertices.push(p0.x, p0.y, p0.z); // normal
  18214. // approximate tangent vectors via finite differences
  18215. if (u - EPS >= 0) {
  18216. func(u - EPS, v, p1);
  18217. pu.subVectors(p0, p1);
  18218. } else {
  18219. func(u + EPS, v, p1);
  18220. pu.subVectors(p1, p0);
  18221. }
  18222. if (v - EPS >= 0) {
  18223. func(u, v - EPS, p1);
  18224. pv.subVectors(p0, p1);
  18225. } else {
  18226. func(u, v + EPS, p1);
  18227. pv.subVectors(p1, p0);
  18228. } // cross product of tangent vectors returns surface normal
  18229. normal.crossVectors(pu, pv).normalize();
  18230. normals.push(normal.x, normal.y, normal.z); // uv
  18231. uvs.push(u, v);
  18232. }
  18233. } // generate indices
  18234. for (i = 0; i < stacks; i++) {
  18235. for (j = 0; j < slices; j++) {
  18236. var a = i * sliceCount + j;
  18237. var b = i * sliceCount + j + 1;
  18238. var c = (i + 1) * sliceCount + j + 1;
  18239. var d = (i + 1) * sliceCount + j; // faces one and two
  18240. indices.push(a, b, d);
  18241. indices.push(b, c, d);
  18242. }
  18243. } // build geometry
  18244. this.setIndex(indices);
  18245. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18246. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18247. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18248. }
  18249. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18250. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  18251. /**
  18252. * @author clockworkgeek / https://github.com/clockworkgeek
  18253. * @author timothypratley / https://github.com/timothypratley
  18254. * @author WestLangley / http://github.com/WestLangley
  18255. * @author Mugen87 / https://github.com/Mugen87
  18256. */
  18257. // PolyhedronGeometry
  18258. function PolyhedronGeometry(vertices, indices, radius, detail) {
  18259. Geometry.call(this);
  18260. this.type = 'PolyhedronGeometry';
  18261. this.parameters = {
  18262. vertices: vertices,
  18263. indices: indices,
  18264. radius: radius,
  18265. detail: detail
  18266. };
  18267. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  18268. this.mergeVertices();
  18269. }
  18270. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  18271. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  18272. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  18273. BufferGeometry.call(this);
  18274. this.type = 'PolyhedronBufferGeometry';
  18275. this.parameters = {
  18276. vertices: vertices,
  18277. indices: indices,
  18278. radius: radius,
  18279. detail: detail
  18280. };
  18281. radius = radius || 1;
  18282. detail = detail || 0; // default buffer data
  18283. var vertexBuffer = [];
  18284. var uvBuffer = []; // the subdivision creates the vertex buffer data
  18285. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  18286. applyRadius(radius); // finally, create the uv data
  18287. generateUVs(); // build non-indexed geometry
  18288. this.addAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  18289. this.addAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  18290. this.addAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  18291. if (detail === 0) {
  18292. this.computeVertexNormals(); // flat normals
  18293. } else {
  18294. this.normalizeNormals(); // smooth normals
  18295. } // helper functions
  18296. function subdivide(detail) {
  18297. var a = new Vector3();
  18298. var b = new Vector3();
  18299. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  18300. for (var i = 0; i < indices.length; i += 3) {
  18301. // get the vertices of the face
  18302. getVertexByIndex(indices[i + 0], a);
  18303. getVertexByIndex(indices[i + 1], b);
  18304. getVertexByIndex(indices[i + 2], c); // perform subdivision
  18305. subdivideFace(a, b, c, detail);
  18306. }
  18307. }
  18308. function subdivideFace(a, b, c, detail) {
  18309. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  18310. var v = [];
  18311. var i, j; // construct all of the vertices for this subdivision
  18312. for (i = 0; i <= cols; i++) {
  18313. v[i] = [];
  18314. var aj = a.clone().lerp(c, i / cols);
  18315. var bj = b.clone().lerp(c, i / cols);
  18316. var rows = cols - i;
  18317. for (j = 0; j <= rows; j++) {
  18318. if (j === 0 && i === cols) {
  18319. v[i][j] = aj;
  18320. } else {
  18321. v[i][j] = aj.clone().lerp(bj, j / rows);
  18322. }
  18323. }
  18324. } // construct all of the faces
  18325. for (i = 0; i < cols; i++) {
  18326. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  18327. var k = Math.floor(j / 2);
  18328. if (j % 2 === 0) {
  18329. pushVertex(v[i][k + 1]);
  18330. pushVertex(v[i + 1][k]);
  18331. pushVertex(v[i][k]);
  18332. } else {
  18333. pushVertex(v[i][k + 1]);
  18334. pushVertex(v[i + 1][k + 1]);
  18335. pushVertex(v[i + 1][k]);
  18336. }
  18337. }
  18338. }
  18339. }
  18340. function applyRadius(radius) {
  18341. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  18342. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18343. vertex.x = vertexBuffer[i + 0];
  18344. vertex.y = vertexBuffer[i + 1];
  18345. vertex.z = vertexBuffer[i + 2];
  18346. vertex.normalize().multiplyScalar(radius);
  18347. vertexBuffer[i + 0] = vertex.x;
  18348. vertexBuffer[i + 1] = vertex.y;
  18349. vertexBuffer[i + 2] = vertex.z;
  18350. }
  18351. }
  18352. function generateUVs() {
  18353. var vertex = new Vector3();
  18354. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18355. vertex.x = vertexBuffer[i + 0];
  18356. vertex.y = vertexBuffer[i + 1];
  18357. vertex.z = vertexBuffer[i + 2];
  18358. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  18359. var v = inclination(vertex) / Math.PI + 0.5;
  18360. uvBuffer.push(u, 1 - v);
  18361. }
  18362. correctUVs();
  18363. correctSeam();
  18364. }
  18365. function correctSeam() {
  18366. // handle case when face straddles the seam, see #3269
  18367. for (var i = 0; i < uvBuffer.length; i += 6) {
  18368. // uv data of a single face
  18369. var x0 = uvBuffer[i + 0];
  18370. var x1 = uvBuffer[i + 2];
  18371. var x2 = uvBuffer[i + 4];
  18372. var max = Math.max(x0, x1, x2);
  18373. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  18374. if (max > 0.9 && min < 0.1) {
  18375. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  18376. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  18377. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  18378. }
  18379. }
  18380. }
  18381. function pushVertex(vertex) {
  18382. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  18383. }
  18384. function getVertexByIndex(index, vertex) {
  18385. var stride = index * 3;
  18386. vertex.x = vertices[stride + 0];
  18387. vertex.y = vertices[stride + 1];
  18388. vertex.z = vertices[stride + 2];
  18389. }
  18390. function correctUVs() {
  18391. var a = new Vector3();
  18392. var b = new Vector3();
  18393. var c = new Vector3();
  18394. var centroid = new Vector3();
  18395. var uvA = new Vector2();
  18396. var uvB = new Vector2();
  18397. var uvC = new Vector2();
  18398. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  18399. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  18400. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  18401. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  18402. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  18403. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  18404. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  18405. centroid.copy(a).add(b).add(c).divideScalar(3);
  18406. var azi = azimuth(centroid);
  18407. correctUV(uvA, j + 0, a, azi);
  18408. correctUV(uvB, j + 2, b, azi);
  18409. correctUV(uvC, j + 4, c, azi);
  18410. }
  18411. }
  18412. function correctUV(uv, stride, vector, azimuth) {
  18413. if (azimuth < 0 && uv.x === 1) {
  18414. uvBuffer[stride] = uv.x - 1;
  18415. }
  18416. if (vector.x === 0 && vector.z === 0) {
  18417. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  18418. }
  18419. } // Angle around the Y axis, counter-clockwise when looking from above.
  18420. function azimuth(vector) {
  18421. return Math.atan2(vector.z, -vector.x);
  18422. } // Angle above the XZ plane.
  18423. function inclination(vector) {
  18424. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  18425. }
  18426. }
  18427. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18428. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  18429. /**
  18430. * @author timothypratley / https://github.com/timothypratley
  18431. * @author Mugen87 / https://github.com/Mugen87
  18432. */
  18433. // TetrahedronGeometry
  18434. function TetrahedronGeometry(radius, detail) {
  18435. Geometry.call(this);
  18436. this.type = 'TetrahedronGeometry';
  18437. this.parameters = {
  18438. radius: radius,
  18439. detail: detail
  18440. };
  18441. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  18442. this.mergeVertices();
  18443. }
  18444. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  18445. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  18446. function TetrahedronBufferGeometry(radius, detail) {
  18447. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18448. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18449. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18450. this.type = 'TetrahedronBufferGeometry';
  18451. this.parameters = {
  18452. radius: radius,
  18453. detail: detail
  18454. };
  18455. }
  18456. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18457. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  18458. /**
  18459. * @author timothypratley / https://github.com/timothypratley
  18460. * @author Mugen87 / https://github.com/Mugen87
  18461. */
  18462. // OctahedronGeometry
  18463. function OctahedronGeometry(radius, detail) {
  18464. Geometry.call(this);
  18465. this.type = 'OctahedronGeometry';
  18466. this.parameters = {
  18467. radius: radius,
  18468. detail: detail
  18469. };
  18470. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  18471. this.mergeVertices();
  18472. }
  18473. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  18474. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  18475. function OctahedronBufferGeometry(radius, detail) {
  18476. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  18477. 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];
  18478. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18479. this.type = 'OctahedronBufferGeometry';
  18480. this.parameters = {
  18481. radius: radius,
  18482. detail: detail
  18483. };
  18484. }
  18485. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18486. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  18487. /**
  18488. * @author timothypratley / https://github.com/timothypratley
  18489. * @author Mugen87 / https://github.com/Mugen87
  18490. */
  18491. // IcosahedronGeometry
  18492. function IcosahedronGeometry(radius, detail) {
  18493. Geometry.call(this);
  18494. this.type = 'IcosahedronGeometry';
  18495. this.parameters = {
  18496. radius: radius,
  18497. detail: detail
  18498. };
  18499. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  18500. this.mergeVertices();
  18501. }
  18502. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  18503. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  18504. function IcosahedronBufferGeometry(radius, detail) {
  18505. var t = (1 + Math.sqrt(5)) / 2;
  18506. 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];
  18507. 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];
  18508. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18509. this.type = 'IcosahedronBufferGeometry';
  18510. this.parameters = {
  18511. radius: radius,
  18512. detail: detail
  18513. };
  18514. }
  18515. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18516. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  18517. /**
  18518. * @author Abe Pazos / https://hamoid.com
  18519. * @author Mugen87 / https://github.com/Mugen87
  18520. */
  18521. // DodecahedronGeometry
  18522. function DodecahedronGeometry(radius, detail) {
  18523. Geometry.call(this);
  18524. this.type = 'DodecahedronGeometry';
  18525. this.parameters = {
  18526. radius: radius,
  18527. detail: detail
  18528. };
  18529. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  18530. this.mergeVertices();
  18531. }
  18532. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  18533. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  18534. function DodecahedronBufferGeometry(radius, detail) {
  18535. var t = (1 + Math.sqrt(5)) / 2;
  18536. var r = 1 / t;
  18537. var vertices = [// (±1, ±1, ±1)
  18538. -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/φ, ±φ)
  18539. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18540. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18541. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18542. 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];
  18543. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18544. this.type = 'DodecahedronBufferGeometry';
  18545. this.parameters = {
  18546. radius: radius,
  18547. detail: detail
  18548. };
  18549. }
  18550. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18551. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  18552. /**
  18553. * @author oosmoxiecode / https://github.com/oosmoxiecode
  18554. * @author WestLangley / https://github.com/WestLangley
  18555. * @author zz85 / https://github.com/zz85
  18556. * @author miningold / https://github.com/miningold
  18557. * @author jonobr1 / https://github.com/jonobr1
  18558. * @author Mugen87 / https://github.com/Mugen87
  18559. *
  18560. */
  18561. // TubeGeometry
  18562. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  18563. Geometry.call(this);
  18564. this.type = 'TubeGeometry';
  18565. this.parameters = {
  18566. path: path,
  18567. tubularSegments: tubularSegments,
  18568. radius: radius,
  18569. radialSegments: radialSegments,
  18570. closed: closed
  18571. };
  18572. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  18573. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  18574. this.tangents = bufferGeometry.tangents;
  18575. this.normals = bufferGeometry.normals;
  18576. this.binormals = bufferGeometry.binormals; // create geometry
  18577. this.fromBufferGeometry(bufferGeometry);
  18578. this.mergeVertices();
  18579. }
  18580. TubeGeometry.prototype = Object.create(Geometry.prototype);
  18581. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  18582. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  18583. BufferGeometry.call(this);
  18584. this.type = 'TubeBufferGeometry';
  18585. this.parameters = {
  18586. path: path,
  18587. tubularSegments: tubularSegments,
  18588. radius: radius,
  18589. radialSegments: radialSegments,
  18590. closed: closed
  18591. };
  18592. tubularSegments = tubularSegments || 64;
  18593. radius = radius || 1;
  18594. radialSegments = radialSegments || 8;
  18595. closed = closed || false;
  18596. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18597. this.tangents = frames.tangents;
  18598. this.normals = frames.normals;
  18599. this.binormals = frames.binormals; // helper variables
  18600. var vertex = new Vector3();
  18601. var normal = new Vector3();
  18602. var uv = new Vector2();
  18603. var P = new Vector3();
  18604. var i, j; // buffer
  18605. var vertices = [];
  18606. var normals = [];
  18607. var uvs = [];
  18608. var indices = []; // create buffer data
  18609. generateBufferData(); // build geometry
  18610. this.setIndex(indices);
  18611. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18612. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18613. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18614. function generateBufferData() {
  18615. for (i = 0; i < tubularSegments; i++) {
  18616. generateSegment(i);
  18617. } // if the geometry is not closed, generate the last row of vertices and normals
  18618. // at the regular position on the given path
  18619. //
  18620. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18621. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18622. // this makes it easy compute correct values for closed geometries
  18623. generateUVs(); // finally create faces
  18624. generateIndices();
  18625. }
  18626. function generateSegment(i) {
  18627. // we use getPointAt to sample evenly distributed points from the given path
  18628. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18629. var N = frames.normals[i];
  18630. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  18631. for (j = 0; j <= radialSegments; j++) {
  18632. var v = j / radialSegments * Math.PI * 2;
  18633. var sin = Math.sin(v);
  18634. var cos = -Math.cos(v); // normal
  18635. normal.x = cos * N.x + sin * B.x;
  18636. normal.y = cos * N.y + sin * B.y;
  18637. normal.z = cos * N.z + sin * B.z;
  18638. normal.normalize();
  18639. normals.push(normal.x, normal.y, normal.z); // vertex
  18640. vertex.x = P.x + radius * normal.x;
  18641. vertex.y = P.y + radius * normal.y;
  18642. vertex.z = P.z + radius * normal.z;
  18643. vertices.push(vertex.x, vertex.y, vertex.z);
  18644. }
  18645. }
  18646. function generateIndices() {
  18647. for (j = 1; j <= tubularSegments; j++) {
  18648. for (i = 1; i <= radialSegments; i++) {
  18649. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18650. var b = (radialSegments + 1) * j + (i - 1);
  18651. var c = (radialSegments + 1) * j + i;
  18652. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18653. indices.push(a, b, d);
  18654. indices.push(b, c, d);
  18655. }
  18656. }
  18657. }
  18658. function generateUVs() {
  18659. for (i = 0; i <= tubularSegments; i++) {
  18660. for (j = 0; j <= radialSegments; j++) {
  18661. uv.x = i / tubularSegments;
  18662. uv.y = j / radialSegments;
  18663. uvs.push(uv.x, uv.y);
  18664. }
  18665. }
  18666. }
  18667. }
  18668. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18669. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  18670. TubeBufferGeometry.prototype.toJSON = function () {
  18671. var data = BufferGeometry.prototype.toJSON.call(this);
  18672. data.path = this.parameters.path.toJSON();
  18673. return data;
  18674. };
  18675. /**
  18676. * @author oosmoxiecode
  18677. * @author Mugen87 / https://github.com/Mugen87
  18678. *
  18679. * based on http://www.blackpawn.com/texts/pqtorus/
  18680. */
  18681. // TorusKnotGeometry
  18682. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  18683. Geometry.call(this);
  18684. this.type = 'TorusKnotGeometry';
  18685. this.parameters = {
  18686. radius: radius,
  18687. tube: tube,
  18688. tubularSegments: tubularSegments,
  18689. radialSegments: radialSegments,
  18690. p: p,
  18691. q: q
  18692. };
  18693. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  18694. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  18695. this.mergeVertices();
  18696. }
  18697. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  18698. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  18699. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  18700. BufferGeometry.call(this);
  18701. this.type = 'TorusKnotBufferGeometry';
  18702. this.parameters = {
  18703. radius: radius,
  18704. tube: tube,
  18705. tubularSegments: tubularSegments,
  18706. radialSegments: radialSegments,
  18707. p: p,
  18708. q: q
  18709. };
  18710. radius = radius || 1;
  18711. tube = tube || 0.4;
  18712. tubularSegments = Math.floor(tubularSegments) || 64;
  18713. radialSegments = Math.floor(radialSegments) || 8;
  18714. p = p || 2;
  18715. q = q || 3; // buffers
  18716. var indices = [];
  18717. var vertices = [];
  18718. var normals = [];
  18719. var uvs = []; // helper variables
  18720. var i, j;
  18721. var vertex = new Vector3();
  18722. var normal = new Vector3();
  18723. var P1 = new Vector3();
  18724. var P2 = new Vector3();
  18725. var B = new Vector3();
  18726. var T = new Vector3();
  18727. var N = new Vector3(); // generate vertices, normals and uvs
  18728. for (i = 0; i <= tubularSegments; ++i) {
  18729. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18730. 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.
  18731. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18732. calculatePositionOnCurve(u, p, q, radius, P1);
  18733. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18734. T.subVectors(P2, P1);
  18735. N.addVectors(P2, P1);
  18736. B.crossVectors(T, N);
  18737. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18738. B.normalize();
  18739. N.normalize();
  18740. for (j = 0; j <= radialSegments; ++j) {
  18741. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18742. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18743. var v = j / radialSegments * Math.PI * 2;
  18744. var cx = -tube * Math.cos(v);
  18745. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  18746. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18747. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18748. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18749. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18750. 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)
  18751. normal.subVectors(vertex, P1).normalize();
  18752. normals.push(normal.x, normal.y, normal.z); // uv
  18753. uvs.push(i / tubularSegments);
  18754. uvs.push(j / radialSegments);
  18755. }
  18756. } // generate indices
  18757. for (j = 1; j <= tubularSegments; j++) {
  18758. for (i = 1; i <= radialSegments; i++) {
  18759. // indices
  18760. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18761. var b = (radialSegments + 1) * j + (i - 1);
  18762. var c = (radialSegments + 1) * j + i;
  18763. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18764. indices.push(a, b, d);
  18765. indices.push(b, c, d);
  18766. }
  18767. } // build geometry
  18768. this.setIndex(indices);
  18769. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18770. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18771. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18772. function calculatePositionOnCurve(u, p, q, radius, position) {
  18773. var cu = Math.cos(u);
  18774. var su = Math.sin(u);
  18775. var quOverP = q / p * u;
  18776. var cs = Math.cos(quOverP);
  18777. position.x = radius * (2 + cs) * 0.5 * cu;
  18778. position.y = radius * (2 + cs) * su * 0.5;
  18779. position.z = radius * Math.sin(quOverP) * 0.5;
  18780. }
  18781. }
  18782. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18783. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  18784. /**
  18785. * @author oosmoxiecode
  18786. * @author mrdoob / http://mrdoob.com/
  18787. * @author Mugen87 / https://github.com/Mugen87
  18788. */
  18789. // TorusGeometry
  18790. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18791. Geometry.call(this);
  18792. this.type = 'TorusGeometry';
  18793. this.parameters = {
  18794. radius: radius,
  18795. tube: tube,
  18796. radialSegments: radialSegments,
  18797. tubularSegments: tubularSegments,
  18798. arc: arc
  18799. };
  18800. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  18801. this.mergeVertices();
  18802. }
  18803. TorusGeometry.prototype = Object.create(Geometry.prototype);
  18804. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  18805. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18806. BufferGeometry.call(this);
  18807. this.type = 'TorusBufferGeometry';
  18808. this.parameters = {
  18809. radius: radius,
  18810. tube: tube,
  18811. radialSegments: radialSegments,
  18812. tubularSegments: tubularSegments,
  18813. arc: arc
  18814. };
  18815. radius = radius || 1;
  18816. tube = tube || 0.4;
  18817. radialSegments = Math.floor(radialSegments) || 8;
  18818. tubularSegments = Math.floor(tubularSegments) || 6;
  18819. arc = arc || Math.PI * 2; // buffers
  18820. var indices = [];
  18821. var vertices = [];
  18822. var normals = [];
  18823. var uvs = []; // helper variables
  18824. var center = new Vector3();
  18825. var vertex = new Vector3();
  18826. var normal = new Vector3();
  18827. var j, i; // generate vertices, normals and uvs
  18828. for (j = 0; j <= radialSegments; j++) {
  18829. for (i = 0; i <= tubularSegments; i++) {
  18830. var u = i / tubularSegments * arc;
  18831. var v = j / radialSegments * Math.PI * 2; // vertex
  18832. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18833. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18834. vertex.z = tube * Math.sin(v);
  18835. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18836. center.x = radius * Math.cos(u);
  18837. center.y = radius * Math.sin(u);
  18838. normal.subVectors(vertex, center).normalize();
  18839. normals.push(normal.x, normal.y, normal.z); // uv
  18840. uvs.push(i / tubularSegments);
  18841. uvs.push(j / radialSegments);
  18842. }
  18843. } // generate indices
  18844. for (j = 1; j <= radialSegments; j++) {
  18845. for (i = 1; i <= tubularSegments; i++) {
  18846. // indices
  18847. var a = (tubularSegments + 1) * j + i - 1;
  18848. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  18849. var c = (tubularSegments + 1) * (j - 1) + i;
  18850. var d = (tubularSegments + 1) * j + i; // faces
  18851. indices.push(a, b, d);
  18852. indices.push(b, c, d);
  18853. }
  18854. } // build geometry
  18855. this.setIndex(indices);
  18856. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18857. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18858. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18859. }
  18860. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18861. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  18862. /**
  18863. * @author Mugen87 / https://github.com/Mugen87
  18864. * Port from https://github.com/mapbox/earcut (v2.1.5)
  18865. */
  18866. var Earcut = {
  18867. triangulate: function (data, holeIndices, dim) {
  18868. dim = dim || 2;
  18869. var hasHoles = holeIndices && holeIndices.length,
  18870. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  18871. outerNode = linkedList(data, 0, outerLen, dim, true),
  18872. triangles = [];
  18873. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18874. var minX, minY, maxX, maxY, x, y, invSize;
  18875. 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
  18876. if (data.length > 80 * dim) {
  18877. minX = maxX = data[0];
  18878. minY = maxY = data[1];
  18879. for (var i = dim; i < outerLen; i += dim) {
  18880. x = data[i];
  18881. y = data[i + 1];
  18882. if (x < minX) minX = x;
  18883. if (y < minY) minY = y;
  18884. if (x > maxX) maxX = x;
  18885. if (y > maxY) maxY = y;
  18886. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18887. invSize = Math.max(maxX - minX, maxY - minY);
  18888. invSize = invSize !== 0 ? 1 / invSize : 0;
  18889. }
  18890. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18891. return triangles;
  18892. }
  18893. }; // create a circular doubly linked list from polygon points in the specified winding order
  18894. function linkedList(data, start, end, dim, clockwise) {
  18895. var i, last;
  18896. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18897. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18898. } else {
  18899. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18900. }
  18901. if (last && equals(last, last.next)) {
  18902. removeNode(last);
  18903. last = last.next;
  18904. }
  18905. return last;
  18906. } // eliminate colinear or duplicate points
  18907. function filterPoints(start, end) {
  18908. if (!start) return start;
  18909. if (!end) end = start;
  18910. var p = start,
  18911. again;
  18912. do {
  18913. again = false;
  18914. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18915. removeNode(p);
  18916. p = end = p.prev;
  18917. if (p === p.next) break;
  18918. again = true;
  18919. } else {
  18920. p = p.next;
  18921. }
  18922. } while (again || p !== end);
  18923. return end;
  18924. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18925. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18926. if (!ear) return; // interlink polygon nodes in z-order
  18927. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18928. var stop = ear,
  18929. prev,
  18930. next; // iterate through ears, slicing them one by one
  18931. while (ear.prev !== ear.next) {
  18932. prev = ear.prev;
  18933. next = ear.next;
  18934. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18935. // cut off the triangle
  18936. triangles.push(prev.i / dim);
  18937. triangles.push(ear.i / dim);
  18938. triangles.push(next.i / dim);
  18939. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18940. ear = next.next;
  18941. stop = next.next;
  18942. continue;
  18943. }
  18944. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18945. if (ear === stop) {
  18946. // try filtering points and slicing again
  18947. if (!pass) {
  18948. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18949. } else if (pass === 1) {
  18950. ear = cureLocalIntersections(ear, triangles, dim);
  18951. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18952. } else if (pass === 2) {
  18953. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18954. }
  18955. break;
  18956. }
  18957. }
  18958. } // check whether a polygon node forms a valid ear with adjacent nodes
  18959. function isEar(ear) {
  18960. var a = ear.prev,
  18961. b = ear,
  18962. c = ear.next;
  18963. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18964. // now make sure we don't have other points inside the potential ear
  18965. var p = ear.next.next;
  18966. while (p !== ear.prev) {
  18967. 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;
  18968. p = p.next;
  18969. }
  18970. return true;
  18971. }
  18972. function isEarHashed(ear, minX, minY, invSize) {
  18973. var a = ear.prev,
  18974. b = ear,
  18975. c = ear.next;
  18976. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18977. // triangle bbox; min & max are calculated like this for speed
  18978. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18979. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18980. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18981. 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;
  18982. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18983. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18984. var p = ear.prevZ,
  18985. n = ear.nextZ; // look for points inside the triangle in both directions
  18986. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18987. 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;
  18988. p = p.prevZ;
  18989. 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;
  18990. n = n.nextZ;
  18991. } // look for remaining points in decreasing z-order
  18992. while (p && p.z >= minZ) {
  18993. 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;
  18994. p = p.prevZ;
  18995. } // look for remaining points in increasing z-order
  18996. while (n && n.z <= maxZ) {
  18997. 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;
  18998. n = n.nextZ;
  18999. }
  19000. return true;
  19001. } // go through all polygon nodes and cure small local self-intersections
  19002. function cureLocalIntersections(start, triangles, dim) {
  19003. var p = start;
  19004. do {
  19005. var a = p.prev,
  19006. b = p.next.next;
  19007. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  19008. triangles.push(a.i / dim);
  19009. triangles.push(p.i / dim);
  19010. triangles.push(b.i / dim); // remove two nodes involved
  19011. removeNode(p);
  19012. removeNode(p.next);
  19013. p = start = b;
  19014. }
  19015. p = p.next;
  19016. } while (p !== start);
  19017. return p;
  19018. } // try splitting polygon into two and triangulate them independently
  19019. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  19020. // look for a valid diagonal that divides the polygon into two
  19021. var a = start;
  19022. do {
  19023. var b = a.next.next;
  19024. while (b !== a.prev) {
  19025. if (a.i !== b.i && isValidDiagonal(a, b)) {
  19026. // split the polygon in two by the diagonal
  19027. var c = splitPolygon(a, b); // filter colinear points around the cuts
  19028. a = filterPoints(a, a.next);
  19029. c = filterPoints(c, c.next); // run earcut on each half
  19030. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19031. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19032. return;
  19033. }
  19034. b = b.next;
  19035. }
  19036. a = a.next;
  19037. } while (a !== start);
  19038. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19039. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19040. var queue = [],
  19041. i,
  19042. len,
  19043. start,
  19044. end,
  19045. list;
  19046. for (i = 0, len = holeIndices.length; i < len; i++) {
  19047. start = holeIndices[i] * dim;
  19048. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19049. list = linkedList(data, start, end, dim, false);
  19050. if (list === list.next) list.steiner = true;
  19051. queue.push(getLeftmost(list));
  19052. }
  19053. queue.sort(compareX); // process holes from left to right
  19054. for (i = 0; i < queue.length; i++) {
  19055. eliminateHole(queue[i], outerNode);
  19056. outerNode = filterPoints(outerNode, outerNode.next);
  19057. }
  19058. return outerNode;
  19059. }
  19060. function compareX(a, b) {
  19061. return a.x - b.x;
  19062. } // find a bridge between vertices that connects hole with an outer ring and and link it
  19063. function eliminateHole(hole, outerNode) {
  19064. outerNode = findHoleBridge(hole, outerNode);
  19065. if (outerNode) {
  19066. var b = splitPolygon(outerNode, hole);
  19067. filterPoints(b, b.next);
  19068. }
  19069. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19070. function findHoleBridge(hole, outerNode) {
  19071. var p = outerNode,
  19072. hx = hole.x,
  19073. hy = hole.y,
  19074. qx = -Infinity,
  19075. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19076. // segment's endpoint with lesser x will be potential connection point
  19077. do {
  19078. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19079. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19080. if (x <= hx && x > qx) {
  19081. qx = x;
  19082. if (x === hx) {
  19083. if (hy === p.y) return p;
  19084. if (hy === p.next.y) return p.next;
  19085. }
  19086. m = p.x < p.next.x ? p : p.next;
  19087. }
  19088. }
  19089. p = p.next;
  19090. } while (p !== outerNode);
  19091. if (!m) return null;
  19092. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  19093. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19094. // if there are no points found, we have a valid connection;
  19095. // otherwise choose the point of the minimum angle with the ray as connection point
  19096. var stop = m,
  19097. mx = m.x,
  19098. my = m.y,
  19099. tanMin = Infinity,
  19100. tan;
  19101. p = m.next;
  19102. while (p !== stop) {
  19103. 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)) {
  19104. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19105. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  19106. m = p;
  19107. tanMin = tan;
  19108. }
  19109. }
  19110. p = p.next;
  19111. }
  19112. return m;
  19113. } // interlink polygon nodes in z-order
  19114. function indexCurve(start, minX, minY, invSize) {
  19115. var p = start;
  19116. do {
  19117. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19118. p.prevZ = p.prev;
  19119. p.nextZ = p.next;
  19120. p = p.next;
  19121. } while (p !== start);
  19122. p.prevZ.nextZ = null;
  19123. p.prevZ = null;
  19124. sortLinked(p);
  19125. } // Simon Tatham's linked list merge sort algorithm
  19126. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19127. function sortLinked(list) {
  19128. var i,
  19129. p,
  19130. q,
  19131. e,
  19132. tail,
  19133. numMerges,
  19134. pSize,
  19135. qSize,
  19136. inSize = 1;
  19137. do {
  19138. p = list;
  19139. list = null;
  19140. tail = null;
  19141. numMerges = 0;
  19142. while (p) {
  19143. numMerges++;
  19144. q = p;
  19145. pSize = 0;
  19146. for (i = 0; i < inSize; i++) {
  19147. pSize++;
  19148. q = q.nextZ;
  19149. if (!q) break;
  19150. }
  19151. qSize = inSize;
  19152. while (pSize > 0 || qSize > 0 && q) {
  19153. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19154. e = p;
  19155. p = p.nextZ;
  19156. pSize--;
  19157. } else {
  19158. e = q;
  19159. q = q.nextZ;
  19160. qSize--;
  19161. }
  19162. if (tail) tail.nextZ = e;else list = e;
  19163. e.prevZ = tail;
  19164. tail = e;
  19165. }
  19166. p = q;
  19167. }
  19168. tail.nextZ = null;
  19169. inSize *= 2;
  19170. } while (numMerges > 1);
  19171. return list;
  19172. } // z-order of a point given coords and inverse of the longer side of data bbox
  19173. function zOrder(x, y, minX, minY, invSize) {
  19174. // coords are transformed into non-negative 15-bit integer range
  19175. x = 32767 * (x - minX) * invSize;
  19176. y = 32767 * (y - minY) * invSize;
  19177. x = (x | x << 8) & 0x00FF00FF;
  19178. x = (x | x << 4) & 0x0F0F0F0F;
  19179. x = (x | x << 2) & 0x33333333;
  19180. x = (x | x << 1) & 0x55555555;
  19181. y = (y | y << 8) & 0x00FF00FF;
  19182. y = (y | y << 4) & 0x0F0F0F0F;
  19183. y = (y | y << 2) & 0x33333333;
  19184. y = (y | y << 1) & 0x55555555;
  19185. return x | y << 1;
  19186. } // find the leftmost node of a polygon ring
  19187. function getLeftmost(start) {
  19188. var p = start,
  19189. leftmost = start;
  19190. do {
  19191. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19192. p = p.next;
  19193. } while (p !== start);
  19194. return leftmost;
  19195. } // check if a point lies within a convex triangle
  19196. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19197. 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;
  19198. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19199. function isValidDiagonal(a, b) {
  19200. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  19201. } // signed area of a triangle
  19202. function area(p, q, r) {
  19203. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19204. } // check if two points are equal
  19205. function equals(p1, p2) {
  19206. return p1.x === p2.x && p1.y === p2.y;
  19207. } // check if two segments intersect
  19208. function intersects(p1, q1, p2, q2) {
  19209. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  19210. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  19211. } // check if a polygon diagonal intersects any polygon segments
  19212. function intersectsPolygon(a, b) {
  19213. var p = a;
  19214. do {
  19215. 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;
  19216. p = p.next;
  19217. } while (p !== a);
  19218. return false;
  19219. } // check if a polygon diagonal is locally inside the polygon
  19220. function locallyInside(a, b) {
  19221. 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;
  19222. } // check if the middle point of a polygon diagonal is inside the polygon
  19223. function middleInside(a, b) {
  19224. var p = a,
  19225. inside = false,
  19226. px = (a.x + b.x) / 2,
  19227. py = (a.y + b.y) / 2;
  19228. do {
  19229. 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;
  19230. p = p.next;
  19231. } while (p !== a);
  19232. return inside;
  19233. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19234. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19235. function splitPolygon(a, b) {
  19236. var a2 = new Node(a.i, a.x, a.y),
  19237. b2 = new Node(b.i, b.x, b.y),
  19238. an = a.next,
  19239. bp = b.prev;
  19240. a.next = b;
  19241. b.prev = a;
  19242. a2.next = an;
  19243. an.prev = a2;
  19244. b2.next = a2;
  19245. a2.prev = b2;
  19246. bp.next = b2;
  19247. b2.prev = bp;
  19248. return b2;
  19249. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19250. function insertNode(i, x, y, last) {
  19251. var p = new Node(i, x, y);
  19252. if (!last) {
  19253. p.prev = p;
  19254. p.next = p;
  19255. } else {
  19256. p.next = last.next;
  19257. p.prev = last;
  19258. last.next.prev = p;
  19259. last.next = p;
  19260. }
  19261. return p;
  19262. }
  19263. function removeNode(p) {
  19264. p.next.prev = p.prev;
  19265. p.prev.next = p.next;
  19266. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19267. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19268. }
  19269. function Node(i, x, y) {
  19270. // vertex index in coordinates array
  19271. this.i = i; // vertex coordinates
  19272. this.x = x;
  19273. this.y = y; // previous and next vertex nodes in a polygon ring
  19274. this.prev = null;
  19275. this.next = null; // z-order curve value
  19276. this.z = null; // previous and next nodes in z-order
  19277. this.prevZ = null;
  19278. this.nextZ = null; // indicates whether this is a steiner point
  19279. this.steiner = false;
  19280. }
  19281. function signedArea(data, start, end, dim) {
  19282. var sum = 0;
  19283. for (var i = start, j = end - dim; i < end; i += dim) {
  19284. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19285. j = i;
  19286. }
  19287. return sum;
  19288. }
  19289. /**
  19290. * @author zz85 / http://www.lab4games.net/zz85/blog
  19291. */
  19292. var ShapeUtils = {
  19293. // calculate area of the contour polygon
  19294. area: function (contour) {
  19295. var n = contour.length;
  19296. var a = 0.0;
  19297. for (var p = n - 1, q = 0; q < n; p = q++) {
  19298. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19299. }
  19300. return a * 0.5;
  19301. },
  19302. isClockWise: function (pts) {
  19303. return ShapeUtils.area(pts) < 0;
  19304. },
  19305. triangulateShape: function (contour, holes) {
  19306. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19307. var holeIndices = []; // array of hole indices
  19308. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19309. removeDupEndPts(contour);
  19310. addContour(vertices, contour); //
  19311. var holeIndex = contour.length;
  19312. holes.forEach(removeDupEndPts);
  19313. for (var i = 0; i < holes.length; i++) {
  19314. holeIndices.push(holeIndex);
  19315. holeIndex += holes[i].length;
  19316. addContour(vertices, holes[i]);
  19317. } //
  19318. var triangles = Earcut.triangulate(vertices, holeIndices); //
  19319. for (var i = 0; i < triangles.length; i += 3) {
  19320. faces.push(triangles.slice(i, i + 3));
  19321. }
  19322. return faces;
  19323. }
  19324. };
  19325. exports.ShapeUtils = ShapeUtils;
  19326. function removeDupEndPts(points) {
  19327. var l = points.length;
  19328. if (l > 2 && points[l - 1].equals(points[0])) {
  19329. points.pop();
  19330. }
  19331. }
  19332. function addContour(vertices, contour) {
  19333. for (var i = 0; i < contour.length; i++) {
  19334. vertices.push(contour[i].x);
  19335. vertices.push(contour[i].y);
  19336. }
  19337. }
  19338. /**
  19339. * @author zz85 / http://www.lab4games.net/zz85/blog
  19340. *
  19341. * Creates extruded geometry from a path shape.
  19342. *
  19343. * parameters = {
  19344. *
  19345. * curveSegments: <int>, // number of points on the curves
  19346. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19347. * depth: <float>, // Depth to extrude the shape
  19348. *
  19349. * bevelEnabled: <bool>, // turn on bevel
  19350. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19351. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19352. * bevelOffset: <float>, // how far from shape outline does bevel start
  19353. * bevelSegments: <int>, // number of bevel layers
  19354. *
  19355. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19356. *
  19357. * UVGenerator: <Object> // object that provides UV generator functions
  19358. *
  19359. * }
  19360. */
  19361. // ExtrudeGeometry
  19362. function ExtrudeGeometry(shapes, options) {
  19363. Geometry.call(this);
  19364. this.type = 'ExtrudeGeometry';
  19365. this.parameters = {
  19366. shapes: shapes,
  19367. options: options
  19368. };
  19369. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  19370. this.mergeVertices();
  19371. }
  19372. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  19373. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  19374. ExtrudeGeometry.prototype.toJSON = function () {
  19375. var data = Geometry.prototype.toJSON.call(this);
  19376. var shapes = this.parameters.shapes;
  19377. var options = this.parameters.options;
  19378. return toJSON(shapes, options, data);
  19379. }; // ExtrudeBufferGeometry
  19380. function ExtrudeBufferGeometry(shapes, options) {
  19381. BufferGeometry.call(this);
  19382. this.type = 'ExtrudeBufferGeometry';
  19383. this.parameters = {
  19384. shapes: shapes,
  19385. options: options
  19386. };
  19387. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19388. var scope = this;
  19389. var verticesArray = [];
  19390. var uvArray = [];
  19391. for (var i = 0, l = shapes.length; i < l; i++) {
  19392. var shape = shapes[i];
  19393. addShape(shape);
  19394. } // build geometry
  19395. this.addAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19396. this.addAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19397. this.computeVertexNormals(); // functions
  19398. function addShape(shape) {
  19399. var placeholder = []; // options
  19400. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19401. var steps = options.steps !== undefined ? options.steps : 1;
  19402. var depth = options.depth !== undefined ? options.depth : 100;
  19403. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19404. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19405. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19406. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19407. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19408. var extrudePath = options.extrudePath;
  19409. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  19410. if (options.amount !== undefined) {
  19411. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  19412. depth = options.amount;
  19413. } //
  19414. var extrudePts,
  19415. extrudeByPath = false;
  19416. var splineTube, binormal, normal, position2;
  19417. if (extrudePath) {
  19418. extrudePts = extrudePath.getSpacedPoints(steps);
  19419. extrudeByPath = true;
  19420. bevelEnabled = false; // bevels not supported for path extrusion
  19421. // SETUP TNB variables
  19422. // TODO1 - have a .isClosed in spline?
  19423. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19424. binormal = new Vector3();
  19425. normal = new Vector3();
  19426. position2 = new Vector3();
  19427. } // Safeguards if bevels are not enabled
  19428. if (!bevelEnabled) {
  19429. bevelSegments = 0;
  19430. bevelThickness = 0;
  19431. bevelSize = 0;
  19432. bevelOffset = 0;
  19433. } // Variables initialization
  19434. var ahole, h, hl; // looping of holes
  19435. var shapePoints = shape.extractPoints(curveSegments);
  19436. var vertices = shapePoints.shape;
  19437. var holes = shapePoints.holes;
  19438. var reverse = !ShapeUtils.isClockWise(vertices);
  19439. if (reverse) {
  19440. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19441. for (h = 0, hl = holes.length; h < hl; h++) {
  19442. ahole = holes[h];
  19443. if (ShapeUtils.isClockWise(ahole)) {
  19444. holes[h] = ahole.reverse();
  19445. }
  19446. }
  19447. }
  19448. var faces = ShapeUtils.triangulateShape(vertices, holes);
  19449. /* Vertices */
  19450. var contour = vertices; // vertices has all points but contour has only points of circumference
  19451. for (h = 0, hl = holes.length; h < hl; h++) {
  19452. ahole = holes[h];
  19453. vertices = vertices.concat(ahole);
  19454. }
  19455. function scalePt2(pt, vec, size) {
  19456. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  19457. return vec.clone().multiplyScalar(size).add(pt);
  19458. }
  19459. var b,
  19460. bs,
  19461. t,
  19462. z,
  19463. vert,
  19464. vlen = vertices.length,
  19465. face,
  19466. flen = faces.length; // Find directions for point movement
  19467. function getBevelVec(inPt, inPrev, inNext) {
  19468. // computes for inPt the corresponding point inPt' on a new contour
  19469. // shifted by 1 unit (length of normalized vector) to the left
  19470. // if we walk along contour clockwise, this new contour is outside the old one
  19471. //
  19472. // inPt' is the intersection of the two lines parallel to the two
  19473. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19474. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19475. // good reading for geometry algorithms (here: line-line intersection)
  19476. // http://geomalgorithms.com/a05-_intersect-1.html
  19477. var v_prev_x = inPt.x - inPrev.x,
  19478. v_prev_y = inPt.y - inPrev.y;
  19479. var v_next_x = inNext.x - inPt.x,
  19480. v_next_y = inNext.y - inPt.y;
  19481. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  19482. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  19483. if (Math.abs(collinear0) > Number.EPSILON) {
  19484. // not collinear
  19485. // length of vectors for normalizing
  19486. var v_prev_len = Math.sqrt(v_prev_lensq);
  19487. 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
  19488. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  19489. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  19490. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  19491. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  19492. 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
  19493. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  19494. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  19495. // but prevent crazy spikes
  19496. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  19497. if (v_trans_lensq <= 2) {
  19498. return new Vector2(v_trans_x, v_trans_y);
  19499. } else {
  19500. shrink_by = Math.sqrt(v_trans_lensq / 2);
  19501. }
  19502. } else {
  19503. // handle special case of collinear edges
  19504. var direction_eq = false; // assumes: opposite
  19505. if (v_prev_x > Number.EPSILON) {
  19506. if (v_next_x > Number.EPSILON) {
  19507. direction_eq = true;
  19508. }
  19509. } else {
  19510. if (v_prev_x < -Number.EPSILON) {
  19511. if (v_next_x < -Number.EPSILON) {
  19512. direction_eq = true;
  19513. }
  19514. } else {
  19515. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  19516. direction_eq = true;
  19517. }
  19518. }
  19519. }
  19520. if (direction_eq) {
  19521. // console.log("Warning: lines are a straight sequence");
  19522. v_trans_x = -v_prev_y;
  19523. v_trans_y = v_prev_x;
  19524. shrink_by = Math.sqrt(v_prev_lensq);
  19525. } else {
  19526. // console.log("Warning: lines are a straight spike");
  19527. v_trans_x = v_prev_x;
  19528. v_trans_y = v_prev_y;
  19529. shrink_by = Math.sqrt(v_prev_lensq / 2);
  19530. }
  19531. }
  19532. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  19533. }
  19534. var contourMovements = [];
  19535. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19536. if (j === il) j = 0;
  19537. if (k === il) k = 0; // (j)---(i)---(k)
  19538. // console.log('i,j,k', i, j , k)
  19539. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  19540. }
  19541. var holesMovements = [],
  19542. oneHoleMovements,
  19543. verticesMovements = contourMovements.concat();
  19544. for (h = 0, hl = holes.length; h < hl; h++) {
  19545. ahole = holes[h];
  19546. oneHoleMovements = [];
  19547. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19548. if (j === il) j = 0;
  19549. if (k === il) k = 0; // (j)---(i)---(k)
  19550. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  19551. }
  19552. holesMovements.push(oneHoleMovements);
  19553. verticesMovements = verticesMovements.concat(oneHoleMovements);
  19554. } // Loop bevelSegments, 1 for the front, 1 for the back
  19555. for (b = 0; b < bevelSegments; b++) {
  19556. //for ( b = bevelSegments; b > 0; b -- ) {
  19557. t = b / bevelSegments;
  19558. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19559. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19560. for (i = 0, il = contour.length; i < il; i++) {
  19561. vert = scalePt2(contour[i], contourMovements[i], bs);
  19562. v(vert.x, vert.y, -z);
  19563. } // expand holes
  19564. for (h = 0, hl = holes.length; h < hl; h++) {
  19565. ahole = holes[h];
  19566. oneHoleMovements = holesMovements[h];
  19567. for (i = 0, il = ahole.length; i < il; i++) {
  19568. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19569. v(vert.x, vert.y, -z);
  19570. }
  19571. }
  19572. }
  19573. bs = bevelSize + bevelOffset; // Back facing vertices
  19574. for (i = 0; i < vlen; i++) {
  19575. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19576. if (!extrudeByPath) {
  19577. v(vert.x, vert.y, 0);
  19578. } else {
  19579. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19580. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  19581. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  19582. position2.copy(extrudePts[0]).add(normal).add(binormal);
  19583. v(position2.x, position2.y, position2.z);
  19584. }
  19585. } // Add stepped vertices...
  19586. // Including front facing vertices
  19587. var s;
  19588. for (s = 1; s <= steps; s++) {
  19589. for (i = 0; i < vlen; i++) {
  19590. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19591. if (!extrudeByPath) {
  19592. v(vert.x, vert.y, depth / steps * s);
  19593. } else {
  19594. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19595. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  19596. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  19597. position2.copy(extrudePts[s]).add(normal).add(binormal);
  19598. v(position2.x, position2.y, position2.z);
  19599. }
  19600. }
  19601. } // Add bevel segments planes
  19602. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19603. for (b = bevelSegments - 1; b >= 0; b--) {
  19604. t = b / bevelSegments;
  19605. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19606. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19607. for (i = 0, il = contour.length; i < il; i++) {
  19608. vert = scalePt2(contour[i], contourMovements[i], bs);
  19609. v(vert.x, vert.y, depth + z);
  19610. } // expand holes
  19611. for (h = 0, hl = holes.length; h < hl; h++) {
  19612. ahole = holes[h];
  19613. oneHoleMovements = holesMovements[h];
  19614. for (i = 0, il = ahole.length; i < il; i++) {
  19615. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19616. if (!extrudeByPath) {
  19617. v(vert.x, vert.y, depth + z);
  19618. } else {
  19619. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  19620. }
  19621. }
  19622. }
  19623. }
  19624. /* Faces */
  19625. // Top and bottom faces
  19626. buildLidFaces(); // Sides faces
  19627. buildSideFaces(); ///// Internal functions
  19628. function buildLidFaces() {
  19629. var start = verticesArray.length / 3;
  19630. if (bevelEnabled) {
  19631. var layer = 0; // steps + 1
  19632. var offset = vlen * layer; // Bottom faces
  19633. for (i = 0; i < flen; i++) {
  19634. face = faces[i];
  19635. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  19636. }
  19637. layer = steps + bevelSegments * 2;
  19638. offset = vlen * layer; // Top faces
  19639. for (i = 0; i < flen; i++) {
  19640. face = faces[i];
  19641. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  19642. }
  19643. } else {
  19644. // Bottom faces
  19645. for (i = 0; i < flen; i++) {
  19646. face = faces[i];
  19647. f3(face[2], face[1], face[0]);
  19648. } // Top faces
  19649. for (i = 0; i < flen; i++) {
  19650. face = faces[i];
  19651. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  19652. }
  19653. }
  19654. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  19655. } // Create faces for the z-sides of the shape
  19656. function buildSideFaces() {
  19657. var start = verticesArray.length / 3;
  19658. var layeroffset = 0;
  19659. sidewalls(contour, layeroffset);
  19660. layeroffset += contour.length;
  19661. for (h = 0, hl = holes.length; h < hl; h++) {
  19662. ahole = holes[h];
  19663. sidewalls(ahole, layeroffset); //, true
  19664. layeroffset += ahole.length;
  19665. }
  19666. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  19667. }
  19668. function sidewalls(contour, layeroffset) {
  19669. var j, k;
  19670. i = contour.length;
  19671. while (--i >= 0) {
  19672. j = i;
  19673. k = i - 1;
  19674. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  19675. var s = 0,
  19676. sl = steps + bevelSegments * 2;
  19677. for (s = 0; s < sl; s++) {
  19678. var slen1 = vlen * s;
  19679. var slen2 = vlen * (s + 1);
  19680. var a = layeroffset + j + slen1,
  19681. b = layeroffset + k + slen1,
  19682. c = layeroffset + k + slen2,
  19683. d = layeroffset + j + slen2;
  19684. f4(a, b, c, d);
  19685. }
  19686. }
  19687. }
  19688. function v(x, y, z) {
  19689. placeholder.push(x);
  19690. placeholder.push(y);
  19691. placeholder.push(z);
  19692. }
  19693. function f3(a, b, c) {
  19694. addVertex(a);
  19695. addVertex(b);
  19696. addVertex(c);
  19697. var nextIndex = verticesArray.length / 3;
  19698. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19699. addUV(uvs[0]);
  19700. addUV(uvs[1]);
  19701. addUV(uvs[2]);
  19702. }
  19703. function f4(a, b, c, d) {
  19704. addVertex(a);
  19705. addVertex(b);
  19706. addVertex(d);
  19707. addVertex(b);
  19708. addVertex(c);
  19709. addVertex(d);
  19710. var nextIndex = verticesArray.length / 3;
  19711. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19712. addUV(uvs[0]);
  19713. addUV(uvs[1]);
  19714. addUV(uvs[3]);
  19715. addUV(uvs[1]);
  19716. addUV(uvs[2]);
  19717. addUV(uvs[3]);
  19718. }
  19719. function addVertex(index) {
  19720. verticesArray.push(placeholder[index * 3 + 0]);
  19721. verticesArray.push(placeholder[index * 3 + 1]);
  19722. verticesArray.push(placeholder[index * 3 + 2]);
  19723. }
  19724. function addUV(vector2) {
  19725. uvArray.push(vector2.x);
  19726. uvArray.push(vector2.y);
  19727. }
  19728. }
  19729. }
  19730. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19731. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  19732. ExtrudeBufferGeometry.prototype.toJSON = function () {
  19733. var data = BufferGeometry.prototype.toJSON.call(this);
  19734. var shapes = this.parameters.shapes;
  19735. var options = this.parameters.options;
  19736. return toJSON(shapes, options, data);
  19737. }; //
  19738. var WorldUVGenerator = {
  19739. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  19740. var a_x = vertices[indexA * 3];
  19741. var a_y = vertices[indexA * 3 + 1];
  19742. var b_x = vertices[indexB * 3];
  19743. var b_y = vertices[indexB * 3 + 1];
  19744. var c_x = vertices[indexC * 3];
  19745. var c_y = vertices[indexC * 3 + 1];
  19746. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  19747. },
  19748. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  19749. var a_x = vertices[indexA * 3];
  19750. var a_y = vertices[indexA * 3 + 1];
  19751. var a_z = vertices[indexA * 3 + 2];
  19752. var b_x = vertices[indexB * 3];
  19753. var b_y = vertices[indexB * 3 + 1];
  19754. var b_z = vertices[indexB * 3 + 2];
  19755. var c_x = vertices[indexC * 3];
  19756. var c_y = vertices[indexC * 3 + 1];
  19757. var c_z = vertices[indexC * 3 + 2];
  19758. var d_x = vertices[indexD * 3];
  19759. var d_y = vertices[indexD * 3 + 1];
  19760. var d_z = vertices[indexD * 3 + 2];
  19761. if (Math.abs(a_y - b_y) < 0.01) {
  19762. 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)];
  19763. } else {
  19764. 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)];
  19765. }
  19766. }
  19767. };
  19768. function toJSON(shapes, options, data) {
  19769. //
  19770. data.shapes = [];
  19771. if (Array.isArray(shapes)) {
  19772. for (var i = 0, l = shapes.length; i < l; i++) {
  19773. var shape = shapes[i];
  19774. data.shapes.push(shape.uuid);
  19775. }
  19776. } else {
  19777. data.shapes.push(shapes.uuid);
  19778. } //
  19779. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19780. return data;
  19781. }
  19782. /**
  19783. * @author zz85 / http://www.lab4games.net/zz85/blog
  19784. * @author alteredq / http://alteredqualia.com/
  19785. *
  19786. * Text = 3D Text
  19787. *
  19788. * parameters = {
  19789. * font: <THREE.Font>, // font
  19790. *
  19791. * size: <float>, // size of the text
  19792. * height: <float>, // thickness to extrude text
  19793. * curveSegments: <int>, // number of points on the curves
  19794. *
  19795. * bevelEnabled: <bool>, // turn on bevel
  19796. * bevelThickness: <float>, // how deep into text bevel goes
  19797. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19798. * bevelOffset: <float> // how far from text outline does bevel start
  19799. * }
  19800. */
  19801. // TextGeometry
  19802. function TextGeometry(text, parameters) {
  19803. Geometry.call(this);
  19804. this.type = 'TextGeometry';
  19805. this.parameters = {
  19806. text: text,
  19807. parameters: parameters
  19808. };
  19809. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  19810. this.mergeVertices();
  19811. }
  19812. TextGeometry.prototype = Object.create(Geometry.prototype);
  19813. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  19814. function TextBufferGeometry(text, parameters) {
  19815. parameters = parameters || {};
  19816. var font = parameters.font;
  19817. if (!(font && font.isFont)) {
  19818. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19819. return new Geometry();
  19820. }
  19821. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19822. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19823. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19824. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19825. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19826. ExtrudeBufferGeometry.call(this, shapes, parameters);
  19827. this.type = 'TextBufferGeometry';
  19828. }
  19829. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  19830. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  19831. /**
  19832. * @author mrdoob / http://mrdoob.com/
  19833. * @author benaadams / https://twitter.com/ben_a_adams
  19834. * @author Mugen87 / https://github.com/Mugen87
  19835. */
  19836. // SphereGeometry
  19837. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19838. Geometry.call(this);
  19839. this.type = 'SphereGeometry';
  19840. this.parameters = {
  19841. radius: radius,
  19842. widthSegments: widthSegments,
  19843. heightSegments: heightSegments,
  19844. phiStart: phiStart,
  19845. phiLength: phiLength,
  19846. thetaStart: thetaStart,
  19847. thetaLength: thetaLength
  19848. };
  19849. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  19850. this.mergeVertices();
  19851. }
  19852. SphereGeometry.prototype = Object.create(Geometry.prototype);
  19853. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  19854. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19855. BufferGeometry.call(this);
  19856. this.type = 'SphereBufferGeometry';
  19857. this.parameters = {
  19858. radius: radius,
  19859. widthSegments: widthSegments,
  19860. heightSegments: heightSegments,
  19861. phiStart: phiStart,
  19862. phiLength: phiLength,
  19863. thetaStart: thetaStart,
  19864. thetaLength: thetaLength
  19865. };
  19866. radius = radius || 1;
  19867. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  19868. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  19869. phiStart = phiStart !== undefined ? phiStart : 0;
  19870. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19871. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19872. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19873. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19874. var ix, iy;
  19875. var index = 0;
  19876. var grid = [];
  19877. var vertex = new Vector3();
  19878. var normal = new Vector3(); // buffers
  19879. var indices = [];
  19880. var vertices = [];
  19881. var normals = [];
  19882. var uvs = []; // generate vertices, normals and uvs
  19883. for (iy = 0; iy <= heightSegments; iy++) {
  19884. var verticesRow = [];
  19885. var v = iy / heightSegments; // special case for the poles
  19886. var uOffset = 0;
  19887. if (iy == 0 && thetaStart == 0) {
  19888. uOffset = 0.5 / widthSegments;
  19889. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19890. uOffset = -0.5 / widthSegments;
  19891. }
  19892. for (ix = 0; ix <= widthSegments; ix++) {
  19893. var u = ix / widthSegments; // vertex
  19894. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19895. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19896. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19897. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19898. normal.copy(vertex).normalize();
  19899. normals.push(normal.x, normal.y, normal.z); // uv
  19900. uvs.push(u + uOffset, 1 - v);
  19901. verticesRow.push(index++);
  19902. }
  19903. grid.push(verticesRow);
  19904. } // indices
  19905. for (iy = 0; iy < heightSegments; iy++) {
  19906. for (ix = 0; ix < widthSegments; ix++) {
  19907. var a = grid[iy][ix + 1];
  19908. var b = grid[iy][ix];
  19909. var c = grid[iy + 1][ix];
  19910. var d = grid[iy + 1][ix + 1];
  19911. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19912. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19913. }
  19914. } // build geometry
  19915. this.setIndex(indices);
  19916. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19917. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19918. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19919. }
  19920. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19921. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  19922. /**
  19923. * @author Kaleb Murphy
  19924. * @author Mugen87 / https://github.com/Mugen87
  19925. */
  19926. // RingGeometry
  19927. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19928. Geometry.call(this);
  19929. this.type = 'RingGeometry';
  19930. this.parameters = {
  19931. innerRadius: innerRadius,
  19932. outerRadius: outerRadius,
  19933. thetaSegments: thetaSegments,
  19934. phiSegments: phiSegments,
  19935. thetaStart: thetaStart,
  19936. thetaLength: thetaLength
  19937. };
  19938. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19939. this.mergeVertices();
  19940. }
  19941. RingGeometry.prototype = Object.create(Geometry.prototype);
  19942. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  19943. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19944. BufferGeometry.call(this);
  19945. this.type = 'RingBufferGeometry';
  19946. this.parameters = {
  19947. innerRadius: innerRadius,
  19948. outerRadius: outerRadius,
  19949. thetaSegments: thetaSegments,
  19950. phiSegments: phiSegments,
  19951. thetaStart: thetaStart,
  19952. thetaLength: thetaLength
  19953. };
  19954. innerRadius = innerRadius || 0.5;
  19955. outerRadius = outerRadius || 1;
  19956. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19957. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19958. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  19959. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  19960. var indices = [];
  19961. var vertices = [];
  19962. var normals = [];
  19963. var uvs = []; // some helper variables
  19964. var segment;
  19965. var radius = innerRadius;
  19966. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  19967. var vertex = new Vector3();
  19968. var uv = new Vector2();
  19969. var j, i; // generate vertices, normals and uvs
  19970. for (j = 0; j <= phiSegments; j++) {
  19971. for (i = 0; i <= thetaSegments; i++) {
  19972. // values are generate from the inside of the ring to the outside
  19973. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19974. vertex.x = radius * Math.cos(segment);
  19975. vertex.y = radius * Math.sin(segment);
  19976. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19977. normals.push(0, 0, 1); // uv
  19978. uv.x = (vertex.x / outerRadius + 1) / 2;
  19979. uv.y = (vertex.y / outerRadius + 1) / 2;
  19980. uvs.push(uv.x, uv.y);
  19981. } // increase the radius for next row of vertices
  19982. radius += radiusStep;
  19983. } // indices
  19984. for (j = 0; j < phiSegments; j++) {
  19985. var thetaSegmentLevel = j * (thetaSegments + 1);
  19986. for (i = 0; i < thetaSegments; i++) {
  19987. segment = i + thetaSegmentLevel;
  19988. var a = segment;
  19989. var b = segment + thetaSegments + 1;
  19990. var c = segment + thetaSegments + 2;
  19991. var d = segment + 1; // faces
  19992. indices.push(a, b, d);
  19993. indices.push(b, c, d);
  19994. }
  19995. } // build geometry
  19996. this.setIndex(indices);
  19997. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19998. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19999. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20000. }
  20001. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20002. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  20003. /**
  20004. * @author zz85 / https://github.com/zz85
  20005. * @author bhouston / http://clara.io
  20006. * @author Mugen87 / https://github.com/Mugen87
  20007. */
  20008. // LatheGeometry
  20009. function LatheGeometry(points, segments, phiStart, phiLength) {
  20010. Geometry.call(this);
  20011. this.type = 'LatheGeometry';
  20012. this.parameters = {
  20013. points: points,
  20014. segments: segments,
  20015. phiStart: phiStart,
  20016. phiLength: phiLength
  20017. };
  20018. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  20019. this.mergeVertices();
  20020. }
  20021. LatheGeometry.prototype = Object.create(Geometry.prototype);
  20022. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  20023. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  20024. BufferGeometry.call(this);
  20025. this.type = 'LatheBufferGeometry';
  20026. this.parameters = {
  20027. points: points,
  20028. segments: segments,
  20029. phiStart: phiStart,
  20030. phiLength: phiLength
  20031. };
  20032. segments = Math.floor(segments) || 12;
  20033. phiStart = phiStart || 0;
  20034. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  20035. phiLength = _Math.clamp(phiLength, 0, Math.PI * 2); // buffers
  20036. var indices = [];
  20037. var vertices = [];
  20038. var uvs = []; // helper variables
  20039. var base;
  20040. var inverseSegments = 1.0 / segments;
  20041. var vertex = new Vector3();
  20042. var uv = new Vector2();
  20043. var i, j; // generate vertices and uvs
  20044. for (i = 0; i <= segments; i++) {
  20045. var phi = phiStart + i * inverseSegments * phiLength;
  20046. var sin = Math.sin(phi);
  20047. var cos = Math.cos(phi);
  20048. for (j = 0; j <= points.length - 1; j++) {
  20049. // vertex
  20050. vertex.x = points[j].x * sin;
  20051. vertex.y = points[j].y;
  20052. vertex.z = points[j].x * cos;
  20053. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  20054. uv.x = i / segments;
  20055. uv.y = j / (points.length - 1);
  20056. uvs.push(uv.x, uv.y);
  20057. }
  20058. } // indices
  20059. for (i = 0; i < segments; i++) {
  20060. for (j = 0; j < points.length - 1; j++) {
  20061. base = j + i * points.length;
  20062. var a = base;
  20063. var b = base + points.length;
  20064. var c = base + points.length + 1;
  20065. var d = base + 1; // faces
  20066. indices.push(a, b, d);
  20067. indices.push(b, c, d);
  20068. }
  20069. } // build geometry
  20070. this.setIndex(indices);
  20071. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20072. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  20073. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  20074. // because the corresponding vertices are identical (but still have different UVs).
  20075. if (phiLength === Math.PI * 2) {
  20076. var normals = this.attributes.normal.array;
  20077. var n1 = new Vector3();
  20078. var n2 = new Vector3();
  20079. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  20080. base = segments * points.length * 3;
  20081. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  20082. // select the normal of the vertex in the first line
  20083. n1.x = normals[j + 0];
  20084. n1.y = normals[j + 1];
  20085. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  20086. n2.x = normals[base + j + 0];
  20087. n2.y = normals[base + j + 1];
  20088. n2.z = normals[base + j + 2]; // average normals
  20089. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  20090. normals[j + 0] = normals[base + j + 0] = n.x;
  20091. normals[j + 1] = normals[base + j + 1] = n.y;
  20092. normals[j + 2] = normals[base + j + 2] = n.z;
  20093. }
  20094. }
  20095. }
  20096. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20097. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  20098. /**
  20099. * @author jonobr1 / http://jonobr1.com
  20100. * @author Mugen87 / https://github.com/Mugen87
  20101. */
  20102. // ShapeGeometry
  20103. function ShapeGeometry(shapes, curveSegments) {
  20104. Geometry.call(this);
  20105. this.type = 'ShapeGeometry';
  20106. if (typeof curveSegments === 'object') {
  20107. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  20108. curveSegments = curveSegments.curveSegments;
  20109. }
  20110. this.parameters = {
  20111. shapes: shapes,
  20112. curveSegments: curveSegments
  20113. };
  20114. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  20115. this.mergeVertices();
  20116. }
  20117. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  20118. ShapeGeometry.prototype.constructor = ShapeGeometry;
  20119. ShapeGeometry.prototype.toJSON = function () {
  20120. var data = Geometry.prototype.toJSON.call(this);
  20121. var shapes = this.parameters.shapes;
  20122. return toJSON$1(shapes, data);
  20123. }; // ShapeBufferGeometry
  20124. function ShapeBufferGeometry(shapes, curveSegments) {
  20125. BufferGeometry.call(this);
  20126. this.type = 'ShapeBufferGeometry';
  20127. this.parameters = {
  20128. shapes: shapes,
  20129. curveSegments: curveSegments
  20130. };
  20131. curveSegments = curveSegments || 12; // buffers
  20132. var indices = [];
  20133. var vertices = [];
  20134. var normals = [];
  20135. var uvs = []; // helper variables
  20136. var groupStart = 0;
  20137. var groupCount = 0; // allow single and array values for "shapes" parameter
  20138. if (Array.isArray(shapes) === false) {
  20139. addShape(shapes);
  20140. } else {
  20141. for (var i = 0; i < shapes.length; i++) {
  20142. addShape(shapes[i]);
  20143. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20144. groupStart += groupCount;
  20145. groupCount = 0;
  20146. }
  20147. } // build geometry
  20148. this.setIndex(indices);
  20149. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20150. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20151. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20152. function addShape(shape) {
  20153. var i, l, shapeHole;
  20154. var indexOffset = vertices.length / 3;
  20155. var points = shape.extractPoints(curveSegments);
  20156. var shapeVertices = points.shape;
  20157. var shapeHoles = points.holes; // check direction of vertices
  20158. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20159. shapeVertices = shapeVertices.reverse();
  20160. }
  20161. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20162. shapeHole = shapeHoles[i];
  20163. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20164. shapeHoles[i] = shapeHole.reverse();
  20165. }
  20166. }
  20167. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20168. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20169. shapeHole = shapeHoles[i];
  20170. shapeVertices = shapeVertices.concat(shapeHole);
  20171. } // vertices, normals, uvs
  20172. for (i = 0, l = shapeVertices.length; i < l; i++) {
  20173. var vertex = shapeVertices[i];
  20174. vertices.push(vertex.x, vertex.y, 0);
  20175. normals.push(0, 0, 1);
  20176. uvs.push(vertex.x, vertex.y); // world uvs
  20177. } // incides
  20178. for (i = 0, l = faces.length; i < l; i++) {
  20179. var face = faces[i];
  20180. var a = face[0] + indexOffset;
  20181. var b = face[1] + indexOffset;
  20182. var c = face[2] + indexOffset;
  20183. indices.push(a, b, c);
  20184. groupCount += 3;
  20185. }
  20186. }
  20187. }
  20188. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20189. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  20190. ShapeBufferGeometry.prototype.toJSON = function () {
  20191. var data = BufferGeometry.prototype.toJSON.call(this);
  20192. var shapes = this.parameters.shapes;
  20193. return toJSON$1(shapes, data);
  20194. }; //
  20195. function toJSON$1(shapes, data) {
  20196. data.shapes = [];
  20197. if (Array.isArray(shapes)) {
  20198. for (var i = 0, l = shapes.length; i < l; i++) {
  20199. var shape = shapes[i];
  20200. data.shapes.push(shape.uuid);
  20201. }
  20202. } else {
  20203. data.shapes.push(shapes.uuid);
  20204. }
  20205. return data;
  20206. }
  20207. /**
  20208. * @author WestLangley / http://github.com/WestLangley
  20209. * @author Mugen87 / https://github.com/Mugen87
  20210. */
  20211. function EdgesGeometry(geometry, thresholdAngle) {
  20212. BufferGeometry.call(this);
  20213. this.type = 'EdgesGeometry';
  20214. this.parameters = {
  20215. thresholdAngle: thresholdAngle
  20216. };
  20217. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  20218. var vertices = []; // helper variables
  20219. var thresholdDot = Math.cos(_Math.DEG2RAD * thresholdAngle);
  20220. var edge = [0, 0],
  20221. edges = {},
  20222. edge1,
  20223. edge2;
  20224. var key,
  20225. keys = ['a', 'b', 'c']; // prepare source geometry
  20226. var geometry2;
  20227. if (geometry.isBufferGeometry) {
  20228. geometry2 = new Geometry();
  20229. geometry2.fromBufferGeometry(geometry);
  20230. } else {
  20231. geometry2 = geometry.clone();
  20232. }
  20233. geometry2.mergeVertices();
  20234. geometry2.computeFaceNormals();
  20235. var sourceVertices = geometry2.vertices;
  20236. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  20237. for (var i = 0, l = faces.length; i < l; i++) {
  20238. var face = faces[i];
  20239. for (var j = 0; j < 3; j++) {
  20240. edge1 = face[keys[j]];
  20241. edge2 = face[keys[(j + 1) % 3]];
  20242. edge[0] = Math.min(edge1, edge2);
  20243. edge[1] = Math.max(edge1, edge2);
  20244. key = edge[0] + ',' + edge[1];
  20245. if (edges[key] === undefined) {
  20246. edges[key] = {
  20247. index1: edge[0],
  20248. index2: edge[1],
  20249. face1: i,
  20250. face2: undefined
  20251. };
  20252. } else {
  20253. edges[key].face2 = i;
  20254. }
  20255. }
  20256. } // generate vertices
  20257. for (key in edges) {
  20258. 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.
  20259. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  20260. var vertex = sourceVertices[e.index1];
  20261. vertices.push(vertex.x, vertex.y, vertex.z);
  20262. vertex = sourceVertices[e.index2];
  20263. vertices.push(vertex.x, vertex.y, vertex.z);
  20264. }
  20265. } // build geometry
  20266. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20267. }
  20268. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  20269. EdgesGeometry.prototype.constructor = EdgesGeometry;
  20270. /**
  20271. * @author mrdoob / http://mrdoob.com/
  20272. * @author Mugen87 / https://github.com/Mugen87
  20273. */
  20274. // CylinderGeometry
  20275. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20276. Geometry.call(this);
  20277. this.type = 'CylinderGeometry';
  20278. this.parameters = {
  20279. radiusTop: radiusTop,
  20280. radiusBottom: radiusBottom,
  20281. height: height,
  20282. radialSegments: radialSegments,
  20283. heightSegments: heightSegments,
  20284. openEnded: openEnded,
  20285. thetaStart: thetaStart,
  20286. thetaLength: thetaLength
  20287. };
  20288. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  20289. this.mergeVertices();
  20290. }
  20291. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  20292. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  20293. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20294. BufferGeometry.call(this);
  20295. this.type = 'CylinderBufferGeometry';
  20296. this.parameters = {
  20297. radiusTop: radiusTop,
  20298. radiusBottom: radiusBottom,
  20299. height: height,
  20300. radialSegments: radialSegments,
  20301. heightSegments: heightSegments,
  20302. openEnded: openEnded,
  20303. thetaStart: thetaStart,
  20304. thetaLength: thetaLength
  20305. };
  20306. var scope = this;
  20307. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  20308. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  20309. height = height || 1;
  20310. radialSegments = Math.floor(radialSegments) || 8;
  20311. heightSegments = Math.floor(heightSegments) || 1;
  20312. openEnded = openEnded !== undefined ? openEnded : false;
  20313. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  20314. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20315. var indices = [];
  20316. var vertices = [];
  20317. var normals = [];
  20318. var uvs = []; // helper variables
  20319. var index = 0;
  20320. var indexArray = [];
  20321. var halfHeight = height / 2;
  20322. var groupStart = 0; // generate geometry
  20323. generateTorso();
  20324. if (openEnded === false) {
  20325. if (radiusTop > 0) generateCap(true);
  20326. if (radiusBottom > 0) generateCap(false);
  20327. } // build geometry
  20328. this.setIndex(indices);
  20329. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20330. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20331. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20332. function generateTorso() {
  20333. var x, y;
  20334. var normal = new Vector3();
  20335. var vertex = new Vector3();
  20336. var groupCount = 0; // this will be used to calculate the normal
  20337. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  20338. for (y = 0; y <= heightSegments; y++) {
  20339. var indexRow = [];
  20340. var v = y / heightSegments; // calculate the radius of the current row
  20341. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  20342. for (x = 0; x <= radialSegments; x++) {
  20343. var u = x / radialSegments;
  20344. var theta = u * thetaLength + thetaStart;
  20345. var sinTheta = Math.sin(theta);
  20346. var cosTheta = Math.cos(theta); // vertex
  20347. vertex.x = radius * sinTheta;
  20348. vertex.y = -v * height + halfHeight;
  20349. vertex.z = radius * cosTheta;
  20350. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20351. normal.set(sinTheta, slope, cosTheta).normalize();
  20352. normals.push(normal.x, normal.y, normal.z); // uv
  20353. uvs.push(u, 1 - v); // save index of vertex in respective row
  20354. indexRow.push(index++);
  20355. } // now save vertices of the row in our index array
  20356. indexArray.push(indexRow);
  20357. } // generate indices
  20358. for (x = 0; x < radialSegments; x++) {
  20359. for (y = 0; y < heightSegments; y++) {
  20360. // we use the index array to access the correct indices
  20361. var a = indexArray[y][x];
  20362. var b = indexArray[y + 1][x];
  20363. var c = indexArray[y + 1][x + 1];
  20364. var d = indexArray[y][x + 1]; // faces
  20365. indices.push(a, b, d);
  20366. indices.push(b, c, d); // update group counter
  20367. groupCount += 6;
  20368. }
  20369. } // add a group to the geometry. this will ensure multi material support
  20370. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  20371. groupStart += groupCount;
  20372. }
  20373. function generateCap(top) {
  20374. var x, centerIndexStart, centerIndexEnd;
  20375. var uv = new Vector2();
  20376. var vertex = new Vector3();
  20377. var groupCount = 0;
  20378. var radius = top === true ? radiusTop : radiusBottom;
  20379. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  20380. centerIndexStart = index; // first we generate the center vertex data of the cap.
  20381. // because the geometry needs one set of uvs per face,
  20382. // we must generate a center vertex per face/segment
  20383. for (x = 1; x <= radialSegments; x++) {
  20384. // vertex
  20385. vertices.push(0, halfHeight * sign, 0); // normal
  20386. normals.push(0, sign, 0); // uv
  20387. uvs.push(0.5, 0.5); // increase index
  20388. index++;
  20389. } // save the index of the last center vertex
  20390. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  20391. for (x = 0; x <= radialSegments; x++) {
  20392. var u = x / radialSegments;
  20393. var theta = u * thetaLength + thetaStart;
  20394. var cosTheta = Math.cos(theta);
  20395. var sinTheta = Math.sin(theta); // vertex
  20396. vertex.x = radius * sinTheta;
  20397. vertex.y = halfHeight * sign;
  20398. vertex.z = radius * cosTheta;
  20399. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20400. normals.push(0, sign, 0); // uv
  20401. uv.x = cosTheta * 0.5 + 0.5;
  20402. uv.y = sinTheta * 0.5 * sign + 0.5;
  20403. uvs.push(uv.x, uv.y); // increase index
  20404. index++;
  20405. } // generate indices
  20406. for (x = 0; x < radialSegments; x++) {
  20407. var c = centerIndexStart + x;
  20408. var i = centerIndexEnd + x;
  20409. if (top === true) {
  20410. // face top
  20411. indices.push(i, i + 1, c);
  20412. } else {
  20413. // face bottom
  20414. indices.push(i + 1, i, c);
  20415. }
  20416. groupCount += 3;
  20417. } // add a group to the geometry. this will ensure multi material support
  20418. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  20419. groupStart += groupCount;
  20420. }
  20421. }
  20422. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20423. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  20424. /**
  20425. * @author abelnation / http://github.com/abelnation
  20426. */
  20427. // ConeGeometry
  20428. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20429. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20430. this.type = 'ConeGeometry';
  20431. this.parameters = {
  20432. radius: radius,
  20433. height: height,
  20434. radialSegments: radialSegments,
  20435. heightSegments: heightSegments,
  20436. openEnded: openEnded,
  20437. thetaStart: thetaStart,
  20438. thetaLength: thetaLength
  20439. };
  20440. }
  20441. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  20442. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  20443. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20444. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20445. this.type = 'ConeBufferGeometry';
  20446. this.parameters = {
  20447. radius: radius,
  20448. height: height,
  20449. radialSegments: radialSegments,
  20450. heightSegments: heightSegments,
  20451. openEnded: openEnded,
  20452. thetaStart: thetaStart,
  20453. thetaLength: thetaLength
  20454. };
  20455. }
  20456. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  20457. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  20458. /**
  20459. * @author benaadams / https://twitter.com/ben_a_adams
  20460. * @author Mugen87 / https://github.com/Mugen87
  20461. * @author hughes
  20462. */
  20463. // CircleGeometry
  20464. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  20465. Geometry.call(this);
  20466. this.type = 'CircleGeometry';
  20467. this.parameters = {
  20468. radius: radius,
  20469. segments: segments,
  20470. thetaStart: thetaStart,
  20471. thetaLength: thetaLength
  20472. };
  20473. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  20474. this.mergeVertices();
  20475. }
  20476. CircleGeometry.prototype = Object.create(Geometry.prototype);
  20477. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  20478. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  20479. BufferGeometry.call(this);
  20480. this.type = 'CircleBufferGeometry';
  20481. this.parameters = {
  20482. radius: radius,
  20483. segments: segments,
  20484. thetaStart: thetaStart,
  20485. thetaLength: thetaLength
  20486. };
  20487. radius = radius || 1;
  20488. segments = segments !== undefined ? Math.max(3, segments) : 8;
  20489. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20490. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20491. var indices = [];
  20492. var vertices = [];
  20493. var normals = [];
  20494. var uvs = []; // helper variables
  20495. var i, s;
  20496. var vertex = new Vector3();
  20497. var uv = new Vector2(); // center point
  20498. vertices.push(0, 0, 0);
  20499. normals.push(0, 0, 1);
  20500. uvs.push(0.5, 0.5);
  20501. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  20502. var segment = thetaStart + s / segments * thetaLength; // vertex
  20503. vertex.x = radius * Math.cos(segment);
  20504. vertex.y = radius * Math.sin(segment);
  20505. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20506. normals.push(0, 0, 1); // uvs
  20507. uv.x = (vertices[i] / radius + 1) / 2;
  20508. uv.y = (vertices[i + 1] / radius + 1) / 2;
  20509. uvs.push(uv.x, uv.y);
  20510. } // indices
  20511. for (i = 1; i <= segments; i++) {
  20512. indices.push(i, i + 1, 0);
  20513. } // build geometry
  20514. this.setIndex(indices);
  20515. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20516. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20517. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20518. }
  20519. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20520. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  20521. var Geometries =
  20522. /*#__PURE__*/
  20523. Object.freeze({
  20524. WireframeGeometry: WireframeGeometry,
  20525. ParametricGeometry: ParametricGeometry,
  20526. ParametricBufferGeometry: ParametricBufferGeometry,
  20527. TetrahedronGeometry: TetrahedronGeometry,
  20528. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20529. OctahedronGeometry: OctahedronGeometry,
  20530. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20531. IcosahedronGeometry: IcosahedronGeometry,
  20532. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20533. DodecahedronGeometry: DodecahedronGeometry,
  20534. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20535. PolyhedronGeometry: PolyhedronGeometry,
  20536. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20537. TubeGeometry: TubeGeometry,
  20538. TubeBufferGeometry: TubeBufferGeometry,
  20539. TorusKnotGeometry: TorusKnotGeometry,
  20540. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20541. TorusGeometry: TorusGeometry,
  20542. TorusBufferGeometry: TorusBufferGeometry,
  20543. TextGeometry: TextGeometry,
  20544. TextBufferGeometry: TextBufferGeometry,
  20545. SphereGeometry: SphereGeometry,
  20546. SphereBufferGeometry: SphereBufferGeometry,
  20547. RingGeometry: RingGeometry,
  20548. RingBufferGeometry: RingBufferGeometry,
  20549. PlaneGeometry: PlaneGeometry,
  20550. PlaneBufferGeometry: PlaneBufferGeometry,
  20551. LatheGeometry: LatheGeometry,
  20552. LatheBufferGeometry: LatheBufferGeometry,
  20553. ShapeGeometry: ShapeGeometry,
  20554. ShapeBufferGeometry: ShapeBufferGeometry,
  20555. ExtrudeGeometry: ExtrudeGeometry,
  20556. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20557. EdgesGeometry: EdgesGeometry,
  20558. ConeGeometry: ConeGeometry,
  20559. ConeBufferGeometry: ConeBufferGeometry,
  20560. CylinderGeometry: CylinderGeometry,
  20561. CylinderBufferGeometry: CylinderBufferGeometry,
  20562. CircleGeometry: CircleGeometry,
  20563. CircleBufferGeometry: CircleBufferGeometry,
  20564. BoxGeometry: BoxGeometry,
  20565. BoxBufferGeometry: BoxBufferGeometry
  20566. });
  20567. /**
  20568. * @author mrdoob / http://mrdoob.com/
  20569. *
  20570. * parameters = {
  20571. * color: <THREE.Color>
  20572. * }
  20573. */
  20574. function ShadowMaterial(parameters) {
  20575. Material.call(this);
  20576. this.type = 'ShadowMaterial';
  20577. this.color = new Color(0x000000);
  20578. this.transparent = true;
  20579. this.setValues(parameters);
  20580. }
  20581. ShadowMaterial.prototype = Object.create(Material.prototype);
  20582. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20583. ShadowMaterial.prototype.isShadowMaterial = true;
  20584. ShadowMaterial.prototype.copy = function (source) {
  20585. Material.prototype.copy.call(this, source);
  20586. this.color.copy(source.color);
  20587. return this;
  20588. };
  20589. /**
  20590. * @author mrdoob / http://mrdoob.com/
  20591. */
  20592. function RawShaderMaterial(parameters) {
  20593. ShaderMaterial.call(this, parameters);
  20594. this.type = 'RawShaderMaterial';
  20595. }
  20596. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  20597. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20598. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20599. /**
  20600. * @author WestLangley / http://github.com/WestLangley
  20601. *
  20602. * parameters = {
  20603. * color: <hex>,
  20604. * roughness: <float>,
  20605. * metalness: <float>,
  20606. * opacity: <float>,
  20607. *
  20608. * map: new THREE.Texture( <Image> ),
  20609. *
  20610. * lightMap: new THREE.Texture( <Image> ),
  20611. * lightMapIntensity: <float>
  20612. *
  20613. * aoMap: new THREE.Texture( <Image> ),
  20614. * aoMapIntensity: <float>
  20615. *
  20616. * emissive: <hex>,
  20617. * emissiveIntensity: <float>
  20618. * emissiveMap: new THREE.Texture( <Image> ),
  20619. *
  20620. * bumpMap: new THREE.Texture( <Image> ),
  20621. * bumpScale: <float>,
  20622. *
  20623. * normalMap: new THREE.Texture( <Image> ),
  20624. * normalMapType: THREE.TangentSpaceNormalMap,
  20625. * normalScale: <Vector2>,
  20626. *
  20627. * displacementMap: new THREE.Texture( <Image> ),
  20628. * displacementScale: <float>,
  20629. * displacementBias: <float>,
  20630. *
  20631. * roughnessMap: new THREE.Texture( <Image> ),
  20632. *
  20633. * metalnessMap: new THREE.Texture( <Image> ),
  20634. *
  20635. * alphaMap: new THREE.Texture( <Image> ),
  20636. *
  20637. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20638. * envMapIntensity: <float>
  20639. *
  20640. * refractionRatio: <float>,
  20641. *
  20642. * wireframe: <boolean>,
  20643. * wireframeLinewidth: <float>,
  20644. *
  20645. * skinning: <bool>,
  20646. * morphTargets: <bool>,
  20647. * morphNormals: <bool>
  20648. * }
  20649. */
  20650. function MeshStandardMaterial(parameters) {
  20651. Material.call(this);
  20652. this.defines = {
  20653. 'STANDARD': ''
  20654. };
  20655. this.type = 'MeshStandardMaterial';
  20656. this.color = new Color(0xffffff); // diffuse
  20657. this.roughness = 0.5;
  20658. this.metalness = 0.5;
  20659. this.map = null;
  20660. this.lightMap = null;
  20661. this.lightMapIntensity = 1.0;
  20662. this.aoMap = null;
  20663. this.aoMapIntensity = 1.0;
  20664. this.emissive = new Color(0x000000);
  20665. this.emissiveIntensity = 1.0;
  20666. this.emissiveMap = null;
  20667. this.bumpMap = null;
  20668. this.bumpScale = 1;
  20669. this.normalMap = null;
  20670. this.normalMapType = TangentSpaceNormalMap;
  20671. this.normalScale = new Vector2(1, 1);
  20672. this.displacementMap = null;
  20673. this.displacementScale = 1;
  20674. this.displacementBias = 0;
  20675. this.roughnessMap = null;
  20676. this.metalnessMap = null;
  20677. this.alphaMap = null;
  20678. this.envMap = null;
  20679. this.envMapIntensity = 1.0;
  20680. this.refractionRatio = 0.98;
  20681. this.wireframe = false;
  20682. this.wireframeLinewidth = 1;
  20683. this.wireframeLinecap = 'round';
  20684. this.wireframeLinejoin = 'round';
  20685. this.skinning = false;
  20686. this.morphTargets = false;
  20687. this.morphNormals = false;
  20688. this.setValues(parameters);
  20689. }
  20690. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  20691. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20692. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20693. MeshStandardMaterial.prototype.copy = function (source) {
  20694. Material.prototype.copy.call(this, source);
  20695. this.defines = {
  20696. 'STANDARD': ''
  20697. };
  20698. this.color.copy(source.color);
  20699. this.roughness = source.roughness;
  20700. this.metalness = source.metalness;
  20701. this.map = source.map;
  20702. this.lightMap = source.lightMap;
  20703. this.lightMapIntensity = source.lightMapIntensity;
  20704. this.aoMap = source.aoMap;
  20705. this.aoMapIntensity = source.aoMapIntensity;
  20706. this.emissive.copy(source.emissive);
  20707. this.emissiveMap = source.emissiveMap;
  20708. this.emissiveIntensity = source.emissiveIntensity;
  20709. this.bumpMap = source.bumpMap;
  20710. this.bumpScale = source.bumpScale;
  20711. this.normalMap = source.normalMap;
  20712. this.normalMapType = source.normalMapType;
  20713. this.normalScale.copy(source.normalScale);
  20714. this.displacementMap = source.displacementMap;
  20715. this.displacementScale = source.displacementScale;
  20716. this.displacementBias = source.displacementBias;
  20717. this.roughnessMap = source.roughnessMap;
  20718. this.metalnessMap = source.metalnessMap;
  20719. this.alphaMap = source.alphaMap;
  20720. this.envMap = source.envMap;
  20721. this.envMapIntensity = source.envMapIntensity;
  20722. this.refractionRatio = source.refractionRatio;
  20723. this.wireframe = source.wireframe;
  20724. this.wireframeLinewidth = source.wireframeLinewidth;
  20725. this.wireframeLinecap = source.wireframeLinecap;
  20726. this.wireframeLinejoin = source.wireframeLinejoin;
  20727. this.skinning = source.skinning;
  20728. this.morphTargets = source.morphTargets;
  20729. this.morphNormals = source.morphNormals;
  20730. return this;
  20731. };
  20732. /**
  20733. * @author WestLangley / http://github.com/WestLangley
  20734. *
  20735. * parameters = {
  20736. * reflectivity: <float>
  20737. * clearcoat: <float>
  20738. * clearcoatRoughness: <float>
  20739. *
  20740. * sheen: <Color>
  20741. *
  20742. * clearcoatNormalScale: <Vector2>,
  20743. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20744. * }
  20745. */
  20746. function MeshPhysicalMaterial(parameters) {
  20747. MeshStandardMaterial.call(this);
  20748. this.defines = {
  20749. 'STANDARD': '',
  20750. 'PHYSICAL': ''
  20751. };
  20752. this.type = 'MeshPhysicalMaterial';
  20753. this.reflectivity = 0.5; // maps to F0 = 0.04
  20754. this.clearcoat = 0.0;
  20755. this.clearcoatRoughness = 0.0;
  20756. this.sheen = null; // null will disable sheen bsdf
  20757. this.clearcoatNormalScale = new Vector2(1, 1);
  20758. this.clearcoatNormalMap = null;
  20759. this.transparency = 0.0;
  20760. this.setValues(parameters);
  20761. }
  20762. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  20763. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20764. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20765. MeshPhysicalMaterial.prototype.copy = function (source) {
  20766. MeshStandardMaterial.prototype.copy.call(this, source);
  20767. this.defines = {
  20768. 'STANDARD': '',
  20769. 'PHYSICAL': ''
  20770. };
  20771. this.reflectivity = source.reflectivity;
  20772. this.clearcoat = source.clearcoat;
  20773. this.clearcoatRoughness = source.clearcoatRoughness;
  20774. if (source.sheen) this.sheen = (this.sheen || new Color()).copy(source.sheen);else this.sheen = null;
  20775. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20776. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20777. this.transparency = source.transparency;
  20778. return this;
  20779. };
  20780. /**
  20781. * @author mrdoob / http://mrdoob.com/
  20782. * @author alteredq / http://alteredqualia.com/
  20783. *
  20784. * parameters = {
  20785. * color: <hex>,
  20786. * specular: <hex>,
  20787. * shininess: <float>,
  20788. * opacity: <float>,
  20789. *
  20790. * map: new THREE.Texture( <Image> ),
  20791. *
  20792. * lightMap: new THREE.Texture( <Image> ),
  20793. * lightMapIntensity: <float>
  20794. *
  20795. * aoMap: new THREE.Texture( <Image> ),
  20796. * aoMapIntensity: <float>
  20797. *
  20798. * emissive: <hex>,
  20799. * emissiveIntensity: <float>
  20800. * emissiveMap: new THREE.Texture( <Image> ),
  20801. *
  20802. * bumpMap: new THREE.Texture( <Image> ),
  20803. * bumpScale: <float>,
  20804. *
  20805. * normalMap: new THREE.Texture( <Image> ),
  20806. * normalMapType: THREE.TangentSpaceNormalMap,
  20807. * normalScale: <Vector2>,
  20808. *
  20809. * displacementMap: new THREE.Texture( <Image> ),
  20810. * displacementScale: <float>,
  20811. * displacementBias: <float>,
  20812. *
  20813. * specularMap: new THREE.Texture( <Image> ),
  20814. *
  20815. * alphaMap: new THREE.Texture( <Image> ),
  20816. *
  20817. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20818. * combine: THREE.Multiply,
  20819. * reflectivity: <float>,
  20820. * refractionRatio: <float>,
  20821. *
  20822. * wireframe: <boolean>,
  20823. * wireframeLinewidth: <float>,
  20824. *
  20825. * skinning: <bool>,
  20826. * morphTargets: <bool>,
  20827. * morphNormals: <bool>
  20828. * }
  20829. */
  20830. function MeshPhongMaterial(parameters) {
  20831. Material.call(this);
  20832. this.type = 'MeshPhongMaterial';
  20833. this.color = new Color(0xffffff); // diffuse
  20834. this.specular = new Color(0x111111);
  20835. this.shininess = 30;
  20836. this.map = null;
  20837. this.lightMap = null;
  20838. this.lightMapIntensity = 1.0;
  20839. this.aoMap = null;
  20840. this.aoMapIntensity = 1.0;
  20841. this.emissive = new Color(0x000000);
  20842. this.emissiveIntensity = 1.0;
  20843. this.emissiveMap = null;
  20844. this.bumpMap = null;
  20845. this.bumpScale = 1;
  20846. this.normalMap = null;
  20847. this.normalMapType = TangentSpaceNormalMap;
  20848. this.normalScale = new Vector2(1, 1);
  20849. this.displacementMap = null;
  20850. this.displacementScale = 1;
  20851. this.displacementBias = 0;
  20852. this.specularMap = null;
  20853. this.alphaMap = null;
  20854. this.envMap = null;
  20855. this.combine = MultiplyOperation;
  20856. this.reflectivity = 1;
  20857. this.refractionRatio = 0.98;
  20858. this.wireframe = false;
  20859. this.wireframeLinewidth = 1;
  20860. this.wireframeLinecap = 'round';
  20861. this.wireframeLinejoin = 'round';
  20862. this.skinning = false;
  20863. this.morphTargets = false;
  20864. this.morphNormals = false;
  20865. this.setValues(parameters);
  20866. }
  20867. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  20868. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20869. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20870. MeshPhongMaterial.prototype.copy = function (source) {
  20871. Material.prototype.copy.call(this, source);
  20872. this.color.copy(source.color);
  20873. this.specular.copy(source.specular);
  20874. this.shininess = source.shininess;
  20875. this.map = source.map;
  20876. this.lightMap = source.lightMap;
  20877. this.lightMapIntensity = source.lightMapIntensity;
  20878. this.aoMap = source.aoMap;
  20879. this.aoMapIntensity = source.aoMapIntensity;
  20880. this.emissive.copy(source.emissive);
  20881. this.emissiveMap = source.emissiveMap;
  20882. this.emissiveIntensity = source.emissiveIntensity;
  20883. this.bumpMap = source.bumpMap;
  20884. this.bumpScale = source.bumpScale;
  20885. this.normalMap = source.normalMap;
  20886. this.normalMapType = source.normalMapType;
  20887. this.normalScale.copy(source.normalScale);
  20888. this.displacementMap = source.displacementMap;
  20889. this.displacementScale = source.displacementScale;
  20890. this.displacementBias = source.displacementBias;
  20891. this.specularMap = source.specularMap;
  20892. this.alphaMap = source.alphaMap;
  20893. this.envMap = source.envMap;
  20894. this.combine = source.combine;
  20895. this.reflectivity = source.reflectivity;
  20896. this.refractionRatio = source.refractionRatio;
  20897. this.wireframe = source.wireframe;
  20898. this.wireframeLinewidth = source.wireframeLinewidth;
  20899. this.wireframeLinecap = source.wireframeLinecap;
  20900. this.wireframeLinejoin = source.wireframeLinejoin;
  20901. this.skinning = source.skinning;
  20902. this.morphTargets = source.morphTargets;
  20903. this.morphNormals = source.morphNormals;
  20904. return this;
  20905. };
  20906. /**
  20907. * @author takahirox / http://github.com/takahirox
  20908. *
  20909. * parameters = {
  20910. * gradientMap: new THREE.Texture( <Image> )
  20911. * }
  20912. */
  20913. function MeshToonMaterial(parameters) {
  20914. MeshPhongMaterial.call(this);
  20915. this.defines = {
  20916. 'TOON': ''
  20917. };
  20918. this.type = 'MeshToonMaterial';
  20919. this.gradientMap = null;
  20920. this.setValues(parameters);
  20921. }
  20922. MeshToonMaterial.prototype = Object.create(MeshPhongMaterial.prototype);
  20923. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20924. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20925. MeshToonMaterial.prototype.copy = function (source) {
  20926. MeshPhongMaterial.prototype.copy.call(this, source);
  20927. this.gradientMap = source.gradientMap;
  20928. return this;
  20929. };
  20930. /**
  20931. * @author mrdoob / http://mrdoob.com/
  20932. * @author WestLangley / http://github.com/WestLangley
  20933. *
  20934. * parameters = {
  20935. * opacity: <float>,
  20936. *
  20937. * bumpMap: new THREE.Texture( <Image> ),
  20938. * bumpScale: <float>,
  20939. *
  20940. * normalMap: new THREE.Texture( <Image> ),
  20941. * normalMapType: THREE.TangentSpaceNormalMap,
  20942. * normalScale: <Vector2>,
  20943. *
  20944. * displacementMap: new THREE.Texture( <Image> ),
  20945. * displacementScale: <float>,
  20946. * displacementBias: <float>,
  20947. *
  20948. * wireframe: <boolean>,
  20949. * wireframeLinewidth: <float>
  20950. *
  20951. * skinning: <bool>,
  20952. * morphTargets: <bool>,
  20953. * morphNormals: <bool>
  20954. * }
  20955. */
  20956. function MeshNormalMaterial(parameters) {
  20957. Material.call(this);
  20958. this.type = 'MeshNormalMaterial';
  20959. this.bumpMap = null;
  20960. this.bumpScale = 1;
  20961. this.normalMap = null;
  20962. this.normalMapType = TangentSpaceNormalMap;
  20963. this.normalScale = new Vector2(1, 1);
  20964. this.displacementMap = null;
  20965. this.displacementScale = 1;
  20966. this.displacementBias = 0;
  20967. this.wireframe = false;
  20968. this.wireframeLinewidth = 1;
  20969. this.fog = false;
  20970. this.skinning = false;
  20971. this.morphTargets = false;
  20972. this.morphNormals = false;
  20973. this.setValues(parameters);
  20974. }
  20975. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20976. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20977. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20978. MeshNormalMaterial.prototype.copy = function (source) {
  20979. Material.prototype.copy.call(this, source);
  20980. this.bumpMap = source.bumpMap;
  20981. this.bumpScale = source.bumpScale;
  20982. this.normalMap = source.normalMap;
  20983. this.normalMapType = source.normalMapType;
  20984. this.normalScale.copy(source.normalScale);
  20985. this.displacementMap = source.displacementMap;
  20986. this.displacementScale = source.displacementScale;
  20987. this.displacementBias = source.displacementBias;
  20988. this.wireframe = source.wireframe;
  20989. this.wireframeLinewidth = source.wireframeLinewidth;
  20990. this.skinning = source.skinning;
  20991. this.morphTargets = source.morphTargets;
  20992. this.morphNormals = source.morphNormals;
  20993. return this;
  20994. };
  20995. /**
  20996. * @author mrdoob / http://mrdoob.com/
  20997. * @author alteredq / http://alteredqualia.com/
  20998. *
  20999. * parameters = {
  21000. * color: <hex>,
  21001. * opacity: <float>,
  21002. *
  21003. * map: new THREE.Texture( <Image> ),
  21004. *
  21005. * lightMap: new THREE.Texture( <Image> ),
  21006. * lightMapIntensity: <float>
  21007. *
  21008. * aoMap: new THREE.Texture( <Image> ),
  21009. * aoMapIntensity: <float>
  21010. *
  21011. * emissive: <hex>,
  21012. * emissiveIntensity: <float>
  21013. * emissiveMap: new THREE.Texture( <Image> ),
  21014. *
  21015. * specularMap: new THREE.Texture( <Image> ),
  21016. *
  21017. * alphaMap: new THREE.Texture( <Image> ),
  21018. *
  21019. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21020. * combine: THREE.Multiply,
  21021. * reflectivity: <float>,
  21022. * refractionRatio: <float>,
  21023. *
  21024. * wireframe: <boolean>,
  21025. * wireframeLinewidth: <float>,
  21026. *
  21027. * skinning: <bool>,
  21028. * morphTargets: <bool>,
  21029. * morphNormals: <bool>
  21030. * }
  21031. */
  21032. function MeshLambertMaterial(parameters) {
  21033. Material.call(this);
  21034. this.type = 'MeshLambertMaterial';
  21035. this.color = new Color(0xffffff); // diffuse
  21036. this.map = null;
  21037. this.lightMap = null;
  21038. this.lightMapIntensity = 1.0;
  21039. this.aoMap = null;
  21040. this.aoMapIntensity = 1.0;
  21041. this.emissive = new Color(0x000000);
  21042. this.emissiveIntensity = 1.0;
  21043. this.emissiveMap = null;
  21044. this.specularMap = null;
  21045. this.alphaMap = null;
  21046. this.envMap = null;
  21047. this.combine = MultiplyOperation;
  21048. this.reflectivity = 1;
  21049. this.refractionRatio = 0.98;
  21050. this.wireframe = false;
  21051. this.wireframeLinewidth = 1;
  21052. this.wireframeLinecap = 'round';
  21053. this.wireframeLinejoin = 'round';
  21054. this.skinning = false;
  21055. this.morphTargets = false;
  21056. this.morphNormals = false;
  21057. this.setValues(parameters);
  21058. }
  21059. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  21060. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21061. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21062. MeshLambertMaterial.prototype.copy = function (source) {
  21063. Material.prototype.copy.call(this, source);
  21064. this.color.copy(source.color);
  21065. this.map = source.map;
  21066. this.lightMap = source.lightMap;
  21067. this.lightMapIntensity = source.lightMapIntensity;
  21068. this.aoMap = source.aoMap;
  21069. this.aoMapIntensity = source.aoMapIntensity;
  21070. this.emissive.copy(source.emissive);
  21071. this.emissiveMap = source.emissiveMap;
  21072. this.emissiveIntensity = source.emissiveIntensity;
  21073. this.specularMap = source.specularMap;
  21074. this.alphaMap = source.alphaMap;
  21075. this.envMap = source.envMap;
  21076. this.combine = source.combine;
  21077. this.reflectivity = source.reflectivity;
  21078. this.refractionRatio = source.refractionRatio;
  21079. this.wireframe = source.wireframe;
  21080. this.wireframeLinewidth = source.wireframeLinewidth;
  21081. this.wireframeLinecap = source.wireframeLinecap;
  21082. this.wireframeLinejoin = source.wireframeLinejoin;
  21083. this.skinning = source.skinning;
  21084. this.morphTargets = source.morphTargets;
  21085. this.morphNormals = source.morphNormals;
  21086. return this;
  21087. };
  21088. /**
  21089. * @author WestLangley / http://github.com/WestLangley
  21090. *
  21091. * parameters = {
  21092. * color: <hex>,
  21093. * opacity: <float>,
  21094. *
  21095. * matcap: new THREE.Texture( <Image> ),
  21096. *
  21097. * map: new THREE.Texture( <Image> ),
  21098. *
  21099. * bumpMap: new THREE.Texture( <Image> ),
  21100. * bumpScale: <float>,
  21101. *
  21102. * normalMap: new THREE.Texture( <Image> ),
  21103. * normalMapType: THREE.TangentSpaceNormalMap,
  21104. * normalScale: <Vector2>,
  21105. *
  21106. * displacementMap: new THREE.Texture( <Image> ),
  21107. * displacementScale: <float>,
  21108. * displacementBias: <float>,
  21109. *
  21110. * alphaMap: new THREE.Texture( <Image> ),
  21111. *
  21112. * skinning: <bool>,
  21113. * morphTargets: <bool>,
  21114. * morphNormals: <bool>
  21115. * }
  21116. */
  21117. function MeshMatcapMaterial(parameters) {
  21118. Material.call(this);
  21119. this.defines = {
  21120. 'MATCAP': ''
  21121. };
  21122. this.type = 'MeshMatcapMaterial';
  21123. this.color = new Color(0xffffff); // diffuse
  21124. this.matcap = null;
  21125. this.map = null;
  21126. this.bumpMap = null;
  21127. this.bumpScale = 1;
  21128. this.normalMap = null;
  21129. this.normalMapType = TangentSpaceNormalMap;
  21130. this.normalScale = new Vector2(1, 1);
  21131. this.displacementMap = null;
  21132. this.displacementScale = 1;
  21133. this.displacementBias = 0;
  21134. this.alphaMap = null;
  21135. this.skinning = false;
  21136. this.morphTargets = false;
  21137. this.morphNormals = false;
  21138. this.setValues(parameters);
  21139. }
  21140. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  21141. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  21142. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21143. MeshMatcapMaterial.prototype.copy = function (source) {
  21144. Material.prototype.copy.call(this, source);
  21145. this.defines = {
  21146. 'MATCAP': ''
  21147. };
  21148. this.color.copy(source.color);
  21149. this.matcap = source.matcap;
  21150. this.map = source.map;
  21151. this.bumpMap = source.bumpMap;
  21152. this.bumpScale = source.bumpScale;
  21153. this.normalMap = source.normalMap;
  21154. this.normalMapType = source.normalMapType;
  21155. this.normalScale.copy(source.normalScale);
  21156. this.displacementMap = source.displacementMap;
  21157. this.displacementScale = source.displacementScale;
  21158. this.displacementBias = source.displacementBias;
  21159. this.alphaMap = source.alphaMap;
  21160. this.skinning = source.skinning;
  21161. this.morphTargets = source.morphTargets;
  21162. this.morphNormals = source.morphNormals;
  21163. return this;
  21164. };
  21165. /**
  21166. * @author alteredq / http://alteredqualia.com/
  21167. *
  21168. * parameters = {
  21169. * color: <hex>,
  21170. * opacity: <float>,
  21171. *
  21172. * linewidth: <float>,
  21173. *
  21174. * scale: <float>,
  21175. * dashSize: <float>,
  21176. * gapSize: <float>
  21177. * }
  21178. */
  21179. function LineDashedMaterial(parameters) {
  21180. LineBasicMaterial.call(this);
  21181. this.type = 'LineDashedMaterial';
  21182. this.scale = 1;
  21183. this.dashSize = 3;
  21184. this.gapSize = 1;
  21185. this.setValues(parameters);
  21186. }
  21187. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  21188. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21189. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21190. LineDashedMaterial.prototype.copy = function (source) {
  21191. LineBasicMaterial.prototype.copy.call(this, source);
  21192. this.scale = source.scale;
  21193. this.dashSize = source.dashSize;
  21194. this.gapSize = source.gapSize;
  21195. return this;
  21196. };
  21197. var Materials =
  21198. /*#__PURE__*/
  21199. Object.freeze({
  21200. ShadowMaterial: ShadowMaterial,
  21201. SpriteMaterial: SpriteMaterial,
  21202. RawShaderMaterial: RawShaderMaterial,
  21203. ShaderMaterial: ShaderMaterial,
  21204. PointsMaterial: PointsMaterial,
  21205. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21206. MeshStandardMaterial: MeshStandardMaterial,
  21207. MeshPhongMaterial: MeshPhongMaterial,
  21208. MeshToonMaterial: MeshToonMaterial,
  21209. MeshNormalMaterial: MeshNormalMaterial,
  21210. MeshLambertMaterial: MeshLambertMaterial,
  21211. MeshDepthMaterial: MeshDepthMaterial,
  21212. MeshDistanceMaterial: MeshDistanceMaterial,
  21213. MeshBasicMaterial: MeshBasicMaterial,
  21214. MeshMatcapMaterial: MeshMatcapMaterial,
  21215. LineDashedMaterial: LineDashedMaterial,
  21216. LineBasicMaterial: LineBasicMaterial,
  21217. Material: Material
  21218. });
  21219. /**
  21220. * @author tschw
  21221. * @author Ben Houston / http://clara.io/
  21222. * @author David Sarno / http://lighthaus.us/
  21223. */
  21224. var AnimationUtils = {
  21225. // same as Array.prototype.slice, but also works on typed arrays
  21226. arraySlice: function (array, from, to) {
  21227. if (AnimationUtils.isTypedArray(array)) {
  21228. // in ios9 array.subarray(from, undefined) will return empty array
  21229. // but array.subarray(from) or array.subarray(from, len) is correct
  21230. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21231. }
  21232. return array.slice(from, to);
  21233. },
  21234. // converts an array to a specific type
  21235. convertArray: function (array, type, forceClone) {
  21236. if (!array || // let 'undefined' and 'null' pass
  21237. !forceClone && array.constructor === type) return array;
  21238. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21239. return new type(array); // create typed array
  21240. }
  21241. return Array.prototype.slice.call(array); // create Array
  21242. },
  21243. isTypedArray: function (object) {
  21244. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21245. },
  21246. // returns an array by which times and values can be sorted
  21247. getKeyframeOrder: function (times) {
  21248. function compareTime(i, j) {
  21249. return times[i] - times[j];
  21250. }
  21251. var n = times.length;
  21252. var result = new Array(n);
  21253. for (var i = 0; i !== n; ++i) result[i] = i;
  21254. result.sort(compareTime);
  21255. return result;
  21256. },
  21257. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21258. sortedArray: function (values, stride, order) {
  21259. var nValues = values.length;
  21260. var result = new values.constructor(nValues);
  21261. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21262. var srcOffset = order[i] * stride;
  21263. for (var j = 0; j !== stride; ++j) {
  21264. result[dstOffset++] = values[srcOffset + j];
  21265. }
  21266. }
  21267. return result;
  21268. },
  21269. // function for parsing AOS keyframe formats
  21270. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21271. var i = 1,
  21272. key = jsonKeys[0];
  21273. while (key !== undefined && key[valuePropertyName] === undefined) {
  21274. key = jsonKeys[i++];
  21275. }
  21276. if (key === undefined) return; // no data
  21277. var value = key[valuePropertyName];
  21278. if (value === undefined) return; // no data
  21279. if (Array.isArray(value)) {
  21280. do {
  21281. value = key[valuePropertyName];
  21282. if (value !== undefined) {
  21283. times.push(key.time);
  21284. values.push.apply(values, value); // push all elements
  21285. }
  21286. key = jsonKeys[i++];
  21287. } while (key !== undefined);
  21288. } else if (value.toArray !== undefined) {
  21289. // ...assume THREE.Math-ish
  21290. do {
  21291. value = key[valuePropertyName];
  21292. if (value !== undefined) {
  21293. times.push(key.time);
  21294. value.toArray(values, values.length);
  21295. }
  21296. key = jsonKeys[i++];
  21297. } while (key !== undefined);
  21298. } else {
  21299. // otherwise push as-is
  21300. do {
  21301. value = key[valuePropertyName];
  21302. if (value !== undefined) {
  21303. times.push(key.time);
  21304. values.push(value);
  21305. }
  21306. key = jsonKeys[i++];
  21307. } while (key !== undefined);
  21308. }
  21309. }
  21310. };
  21311. /**
  21312. * Abstract base class of interpolants over parametric samples.
  21313. *
  21314. * The parameter domain is one dimensional, typically the time or a path
  21315. * along a curve defined by the data.
  21316. *
  21317. * The sample values can have any dimensionality and derived classes may
  21318. * apply special interpretations to the data.
  21319. *
  21320. * This class provides the interval seek in a Template Method, deferring
  21321. * the actual interpolation to derived classes.
  21322. *
  21323. * Time complexity is O(1) for linear access crossing at most two points
  21324. * and O(log N) for random access, where N is the number of positions.
  21325. *
  21326. * References:
  21327. *
  21328. * http://www.oodesign.com/template-method-pattern.html
  21329. *
  21330. * @author tschw
  21331. */
  21332. exports.AnimationUtils = AnimationUtils;
  21333. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21334. this.parameterPositions = parameterPositions;
  21335. this._cachedIndex = 0;
  21336. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21337. this.sampleValues = sampleValues;
  21338. this.valueSize = sampleSize;
  21339. }
  21340. Object.assign(Interpolant.prototype, {
  21341. evaluate: function (t) {
  21342. var pp = this.parameterPositions,
  21343. i1 = this._cachedIndex,
  21344. t1 = pp[i1],
  21345. t0 = pp[i1 - 1];
  21346. validate_interval: {
  21347. seek: {
  21348. var right;
  21349. linear_scan: {
  21350. //- See http://jsperf.com/comparison-to-undefined/3
  21351. //- slower code:
  21352. //-
  21353. //- if ( t >= t1 || t1 === undefined ) {
  21354. forward_scan: if (!(t < t1)) {
  21355. for (var giveUpAt = i1 + 2;;) {
  21356. if (t1 === undefined) {
  21357. if (t < t0) break forward_scan; // after end
  21358. i1 = pp.length;
  21359. this._cachedIndex = i1;
  21360. return this.afterEnd_(i1 - 1, t, t0);
  21361. }
  21362. if (i1 === giveUpAt) break; // this loop
  21363. t0 = t1;
  21364. t1 = pp[++i1];
  21365. if (t < t1) {
  21366. // we have arrived at the sought interval
  21367. break seek;
  21368. }
  21369. } // prepare binary search on the right side of the index
  21370. right = pp.length;
  21371. break linear_scan;
  21372. } //- slower code:
  21373. //- if ( t < t0 || t0 === undefined ) {
  21374. if (!(t >= t0)) {
  21375. // looping?
  21376. var t1global = pp[1];
  21377. if (t < t1global) {
  21378. i1 = 2; // + 1, using the scan for the details
  21379. t0 = t1global;
  21380. } // linear reverse scan
  21381. for (var giveUpAt = i1 - 2;;) {
  21382. if (t0 === undefined) {
  21383. // before start
  21384. this._cachedIndex = 0;
  21385. return this.beforeStart_(0, t, t1);
  21386. }
  21387. if (i1 === giveUpAt) break; // this loop
  21388. t1 = t0;
  21389. t0 = pp[--i1 - 1];
  21390. if (t >= t0) {
  21391. // we have arrived at the sought interval
  21392. break seek;
  21393. }
  21394. } // prepare binary search on the left side of the index
  21395. right = i1;
  21396. i1 = 0;
  21397. break linear_scan;
  21398. } // the interval is valid
  21399. break validate_interval;
  21400. } // linear scan
  21401. // binary search
  21402. while (i1 < right) {
  21403. var mid = i1 + right >>> 1;
  21404. if (t < pp[mid]) {
  21405. right = mid;
  21406. } else {
  21407. i1 = mid + 1;
  21408. }
  21409. }
  21410. t1 = pp[i1];
  21411. t0 = pp[i1 - 1]; // check boundary cases, again
  21412. if (t0 === undefined) {
  21413. this._cachedIndex = 0;
  21414. return this.beforeStart_(0, t, t1);
  21415. }
  21416. if (t1 === undefined) {
  21417. i1 = pp.length;
  21418. this._cachedIndex = i1;
  21419. return this.afterEnd_(i1 - 1, t0, t);
  21420. }
  21421. } // seek
  21422. this._cachedIndex = i1;
  21423. this.intervalChanged_(i1, t0, t1);
  21424. } // validate_interval
  21425. return this.interpolate_(i1, t0, t, t1);
  21426. },
  21427. settings: null,
  21428. // optional, subclass-specific settings structure
  21429. // Note: The indirection allows central control of many interpolants.
  21430. // --- Protected interface
  21431. DefaultSettings_: {},
  21432. getSettings_: function () {
  21433. return this.settings || this.DefaultSettings_;
  21434. },
  21435. copySampleValue_: function (index) {
  21436. // copies a sample value to the result buffer
  21437. var result = this.resultBuffer,
  21438. values = this.sampleValues,
  21439. stride = this.valueSize,
  21440. offset = index * stride;
  21441. for (var i = 0; i !== stride; ++i) {
  21442. result[i] = values[offset + i];
  21443. }
  21444. return result;
  21445. },
  21446. // Template methods for derived classes:
  21447. interpolate_: function ()
  21448. /* i1, t0, t, t1 */
  21449. {
  21450. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21451. },
  21452. intervalChanged_: function ()
  21453. /* i1, t0, t1 */
  21454. {// empty
  21455. }
  21456. }); //!\ DECLARE ALIAS AFTER assign prototype !
  21457. Object.assign(Interpolant.prototype, {
  21458. //( 0, t, t0 ), returns this.resultBuffer
  21459. beforeStart_: Interpolant.prototype.copySampleValue_,
  21460. //( N-1, tN-1, t ), returns this.resultBuffer
  21461. afterEnd_: Interpolant.prototype.copySampleValue_
  21462. });
  21463. /**
  21464. * Fast and simple cubic spline interpolant.
  21465. *
  21466. * It was derived from a Hermitian construction setting the first derivative
  21467. * at each sample position to the linear slope between neighboring positions
  21468. * over their parameter interval.
  21469. *
  21470. * @author tschw
  21471. */
  21472. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21473. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21474. this._weightPrev = -0;
  21475. this._offsetPrev = -0;
  21476. this._weightNext = -0;
  21477. this._offsetNext = -0;
  21478. }
  21479. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21480. constructor: CubicInterpolant,
  21481. DefaultSettings_: {
  21482. endingStart: ZeroCurvatureEnding,
  21483. endingEnd: ZeroCurvatureEnding
  21484. },
  21485. intervalChanged_: function (i1, t0, t1) {
  21486. var pp = this.parameterPositions,
  21487. iPrev = i1 - 2,
  21488. iNext = i1 + 1,
  21489. tPrev = pp[iPrev],
  21490. tNext = pp[iNext];
  21491. if (tPrev === undefined) {
  21492. switch (this.getSettings_().endingStart) {
  21493. case ZeroSlopeEnding:
  21494. // f'(t0) = 0
  21495. iPrev = i1;
  21496. tPrev = 2 * t0 - t1;
  21497. break;
  21498. case WrapAroundEnding:
  21499. // use the other end of the curve
  21500. iPrev = pp.length - 2;
  21501. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21502. break;
  21503. default:
  21504. // ZeroCurvatureEnding
  21505. // f''(t0) = 0 a.k.a. Natural Spline
  21506. iPrev = i1;
  21507. tPrev = t1;
  21508. }
  21509. }
  21510. if (tNext === undefined) {
  21511. switch (this.getSettings_().endingEnd) {
  21512. case ZeroSlopeEnding:
  21513. // f'(tN) = 0
  21514. iNext = i1;
  21515. tNext = 2 * t1 - t0;
  21516. break;
  21517. case WrapAroundEnding:
  21518. // use the other end of the curve
  21519. iNext = 1;
  21520. tNext = t1 + pp[1] - pp[0];
  21521. break;
  21522. default:
  21523. // ZeroCurvatureEnding
  21524. // f''(tN) = 0, a.k.a. Natural Spline
  21525. iNext = i1 - 1;
  21526. tNext = t0;
  21527. }
  21528. }
  21529. var halfDt = (t1 - t0) * 0.5,
  21530. stride = this.valueSize;
  21531. this._weightPrev = halfDt / (t0 - tPrev);
  21532. this._weightNext = halfDt / (tNext - t1);
  21533. this._offsetPrev = iPrev * stride;
  21534. this._offsetNext = iNext * stride;
  21535. },
  21536. interpolate_: function (i1, t0, t, t1) {
  21537. var result = this.resultBuffer,
  21538. values = this.sampleValues,
  21539. stride = this.valueSize,
  21540. o1 = i1 * stride,
  21541. o0 = o1 - stride,
  21542. oP = this._offsetPrev,
  21543. oN = this._offsetNext,
  21544. wP = this._weightPrev,
  21545. wN = this._weightNext,
  21546. p = (t - t0) / (t1 - t0),
  21547. pp = p * p,
  21548. ppp = pp * p; // evaluate polynomials
  21549. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  21550. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21551. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21552. var sN = wN * ppp - wN * pp; // combine data linearly
  21553. for (var i = 0; i !== stride; ++i) {
  21554. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21555. }
  21556. return result;
  21557. }
  21558. });
  21559. /**
  21560. * @author tschw
  21561. */
  21562. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21563. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21564. }
  21565. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21566. constructor: LinearInterpolant,
  21567. interpolate_: function (i1, t0, t, t1) {
  21568. var result = this.resultBuffer,
  21569. values = this.sampleValues,
  21570. stride = this.valueSize,
  21571. offset1 = i1 * stride,
  21572. offset0 = offset1 - stride,
  21573. weight1 = (t - t0) / (t1 - t0),
  21574. weight0 = 1 - weight1;
  21575. for (var i = 0; i !== stride; ++i) {
  21576. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21577. }
  21578. return result;
  21579. }
  21580. });
  21581. /**
  21582. *
  21583. * Interpolant that evaluates to the sample value at the position preceeding
  21584. * the parameter.
  21585. *
  21586. * @author tschw
  21587. */
  21588. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21589. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21590. }
  21591. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21592. constructor: DiscreteInterpolant,
  21593. interpolate_: function (i1
  21594. /*, t0, t, t1 */
  21595. ) {
  21596. return this.copySampleValue_(i1 - 1);
  21597. }
  21598. });
  21599. /**
  21600. *
  21601. * A timed sequence of keyframes for a specific property.
  21602. *
  21603. *
  21604. * @author Ben Houston / http://clara.io/
  21605. * @author David Sarno / http://lighthaus.us/
  21606. * @author tschw
  21607. */
  21608. function KeyframeTrack(name, times, values, interpolation) {
  21609. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21610. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21611. this.name = name;
  21612. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21613. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21614. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21615. } // Static methods
  21616. Object.assign(KeyframeTrack, {
  21617. // Serialization (in static context, because of constructor invocation
  21618. // and automatic invocation of .toJSON):
  21619. toJSON: function (track) {
  21620. var trackType = track.constructor;
  21621. var json; // derived classes can define a static toJSON method
  21622. if (trackType.toJSON !== undefined) {
  21623. json = trackType.toJSON(track);
  21624. } else {
  21625. // by default, we assume the data can be serialized as-is
  21626. json = {
  21627. 'name': track.name,
  21628. 'times': AnimationUtils.convertArray(track.times, Array),
  21629. 'values': AnimationUtils.convertArray(track.values, Array)
  21630. };
  21631. var interpolation = track.getInterpolation();
  21632. if (interpolation !== track.DefaultInterpolation) {
  21633. json.interpolation = interpolation;
  21634. }
  21635. }
  21636. json.type = track.ValueTypeName; // mandatory
  21637. return json;
  21638. }
  21639. });
  21640. Object.assign(KeyframeTrack.prototype, {
  21641. constructor: KeyframeTrack,
  21642. TimeBufferType: Float32Array,
  21643. ValueBufferType: Float32Array,
  21644. DefaultInterpolation: InterpolateLinear,
  21645. InterpolantFactoryMethodDiscrete: function (result) {
  21646. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21647. },
  21648. InterpolantFactoryMethodLinear: function (result) {
  21649. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21650. },
  21651. InterpolantFactoryMethodSmooth: function (result) {
  21652. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21653. },
  21654. setInterpolation: function (interpolation) {
  21655. var factoryMethod;
  21656. switch (interpolation) {
  21657. case InterpolateDiscrete:
  21658. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21659. break;
  21660. case InterpolateLinear:
  21661. factoryMethod = this.InterpolantFactoryMethodLinear;
  21662. break;
  21663. case InterpolateSmooth:
  21664. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21665. break;
  21666. }
  21667. if (factoryMethod === undefined) {
  21668. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  21669. if (this.createInterpolant === undefined) {
  21670. // fall back to default, unless the default itself is messed up
  21671. if (interpolation !== this.DefaultInterpolation) {
  21672. this.setInterpolation(this.DefaultInterpolation);
  21673. } else {
  21674. throw new Error(message); // fatal, in this case
  21675. }
  21676. }
  21677. console.warn('THREE.KeyframeTrack:', message);
  21678. return this;
  21679. }
  21680. this.createInterpolant = factoryMethod;
  21681. return this;
  21682. },
  21683. getInterpolation: function () {
  21684. switch (this.createInterpolant) {
  21685. case this.InterpolantFactoryMethodDiscrete:
  21686. return InterpolateDiscrete;
  21687. case this.InterpolantFactoryMethodLinear:
  21688. return InterpolateLinear;
  21689. case this.InterpolantFactoryMethodSmooth:
  21690. return InterpolateSmooth;
  21691. }
  21692. },
  21693. getValueSize: function () {
  21694. return this.values.length / this.times.length;
  21695. },
  21696. // move all keyframes either forwards or backwards in time
  21697. shift: function (timeOffset) {
  21698. if (timeOffset !== 0.0) {
  21699. var times = this.times;
  21700. for (var i = 0, n = times.length; i !== n; ++i) {
  21701. times[i] += timeOffset;
  21702. }
  21703. }
  21704. return this;
  21705. },
  21706. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21707. scale: function (timeScale) {
  21708. if (timeScale !== 1.0) {
  21709. var times = this.times;
  21710. for (var i = 0, n = times.length; i !== n; ++i) {
  21711. times[i] *= timeScale;
  21712. }
  21713. }
  21714. return this;
  21715. },
  21716. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21717. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21718. trim: function (startTime, endTime) {
  21719. var times = this.times,
  21720. nKeys = times.length,
  21721. from = 0,
  21722. to = nKeys - 1;
  21723. while (from !== nKeys && times[from] < startTime) {
  21724. ++from;
  21725. }
  21726. while (to !== -1 && times[to] > endTime) {
  21727. --to;
  21728. }
  21729. ++to; // inclusive -> exclusive bound
  21730. if (from !== 0 || to !== nKeys) {
  21731. // empty tracks are forbidden, so keep at least one keyframe
  21732. if (from >= to) to = Math.max(to, 1), from = to - 1;
  21733. var stride = this.getValueSize();
  21734. this.times = AnimationUtils.arraySlice(times, from, to);
  21735. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21736. }
  21737. return this;
  21738. },
  21739. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21740. validate: function () {
  21741. var valid = true;
  21742. var valueSize = this.getValueSize();
  21743. if (valueSize - Math.floor(valueSize) !== 0) {
  21744. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21745. valid = false;
  21746. }
  21747. var times = this.times,
  21748. values = this.values,
  21749. nKeys = times.length;
  21750. if (nKeys === 0) {
  21751. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21752. valid = false;
  21753. }
  21754. var prevTime = null;
  21755. for (var i = 0; i !== nKeys; i++) {
  21756. var currTime = times[i];
  21757. if (typeof currTime === 'number' && isNaN(currTime)) {
  21758. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21759. valid = false;
  21760. break;
  21761. }
  21762. if (prevTime !== null && prevTime > currTime) {
  21763. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21764. valid = false;
  21765. break;
  21766. }
  21767. prevTime = currTime;
  21768. }
  21769. if (values !== undefined) {
  21770. if (AnimationUtils.isTypedArray(values)) {
  21771. for (var i = 0, n = values.length; i !== n; ++i) {
  21772. var value = values[i];
  21773. if (isNaN(value)) {
  21774. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21775. valid = false;
  21776. break;
  21777. }
  21778. }
  21779. }
  21780. }
  21781. return valid;
  21782. },
  21783. // removes equivalent sequential keys as common in morph target sequences
  21784. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21785. optimize: function () {
  21786. var times = this.times,
  21787. values = this.values,
  21788. stride = this.getValueSize(),
  21789. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21790. writeIndex = 1,
  21791. lastIndex = times.length - 1;
  21792. for (var i = 1; i < lastIndex; ++i) {
  21793. var keep = false;
  21794. var time = times[i];
  21795. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21796. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21797. if (!smoothInterpolation) {
  21798. // remove unnecessary keyframes same as their neighbors
  21799. var offset = i * stride,
  21800. offsetP = offset - stride,
  21801. offsetN = offset + stride;
  21802. for (var j = 0; j !== stride; ++j) {
  21803. var value = values[offset + j];
  21804. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21805. keep = true;
  21806. break;
  21807. }
  21808. }
  21809. } else {
  21810. keep = true;
  21811. }
  21812. } // in-place compaction
  21813. if (keep) {
  21814. if (i !== writeIndex) {
  21815. times[writeIndex] = times[i];
  21816. var readOffset = i * stride,
  21817. writeOffset = writeIndex * stride;
  21818. for (var j = 0; j !== stride; ++j) {
  21819. values[writeOffset + j] = values[readOffset + j];
  21820. }
  21821. }
  21822. ++writeIndex;
  21823. }
  21824. } // flush last keyframe (compaction looks ahead)
  21825. if (lastIndex > 0) {
  21826. times[writeIndex] = times[lastIndex];
  21827. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21828. values[writeOffset + j] = values[readOffset + j];
  21829. }
  21830. ++writeIndex;
  21831. }
  21832. if (writeIndex !== times.length) {
  21833. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21834. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21835. }
  21836. return this;
  21837. },
  21838. clone: function () {
  21839. var times = AnimationUtils.arraySlice(this.times, 0);
  21840. var values = AnimationUtils.arraySlice(this.values, 0);
  21841. var TypedKeyframeTrack = this.constructor;
  21842. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21843. track.createInterpolant = this.createInterpolant;
  21844. return track;
  21845. }
  21846. });
  21847. /**
  21848. *
  21849. * A Track of Boolean keyframe values.
  21850. *
  21851. *
  21852. * @author Ben Houston / http://clara.io/
  21853. * @author David Sarno / http://lighthaus.us/
  21854. * @author tschw
  21855. */
  21856. function BooleanKeyframeTrack(name, times, values) {
  21857. KeyframeTrack.call(this, name, times, values);
  21858. }
  21859. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21860. constructor: BooleanKeyframeTrack,
  21861. ValueTypeName: 'bool',
  21862. ValueBufferType: Array,
  21863. DefaultInterpolation: InterpolateDiscrete,
  21864. InterpolantFactoryMethodLinear: undefined,
  21865. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21866. // representation of a single value and a custom interpolant that
  21867. // computes "firstValue ^ isOdd( index )".
  21868. });
  21869. /**
  21870. *
  21871. * A Track of keyframe values that represent color.
  21872. *
  21873. *
  21874. * @author Ben Houston / http://clara.io/
  21875. * @author David Sarno / http://lighthaus.us/
  21876. * @author tschw
  21877. */
  21878. function ColorKeyframeTrack(name, times, values, interpolation) {
  21879. KeyframeTrack.call(this, name, times, values, interpolation);
  21880. }
  21881. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21882. constructor: ColorKeyframeTrack,
  21883. ValueTypeName: 'color' // ValueBufferType is inherited
  21884. // DefaultInterpolation is inherited
  21885. // Note: Very basic implementation and nothing special yet.
  21886. // However, this is the place for color space parameterization.
  21887. });
  21888. /**
  21889. *
  21890. * A Track of numeric keyframe values.
  21891. *
  21892. * @author Ben Houston / http://clara.io/
  21893. * @author David Sarno / http://lighthaus.us/
  21894. * @author tschw
  21895. */
  21896. function NumberKeyframeTrack(name, times, values, interpolation) {
  21897. KeyframeTrack.call(this, name, times, values, interpolation);
  21898. }
  21899. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21900. constructor: NumberKeyframeTrack,
  21901. ValueTypeName: 'number' // ValueBufferType is inherited
  21902. // DefaultInterpolation is inherited
  21903. });
  21904. /**
  21905. * Spherical linear unit quaternion interpolant.
  21906. *
  21907. * @author tschw
  21908. */
  21909. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21910. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21911. }
  21912. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21913. constructor: QuaternionLinearInterpolant,
  21914. interpolate_: function (i1, t0, t, t1) {
  21915. var result = this.resultBuffer,
  21916. values = this.sampleValues,
  21917. stride = this.valueSize,
  21918. offset = i1 * stride,
  21919. alpha = (t - t0) / (t1 - t0);
  21920. for (var end = offset + stride; offset !== end; offset += 4) {
  21921. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21922. }
  21923. return result;
  21924. }
  21925. });
  21926. /**
  21927. *
  21928. * A Track of quaternion keyframe values.
  21929. *
  21930. * @author Ben Houston / http://clara.io/
  21931. * @author David Sarno / http://lighthaus.us/
  21932. * @author tschw
  21933. */
  21934. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21935. KeyframeTrack.call(this, name, times, values, interpolation);
  21936. }
  21937. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21938. constructor: QuaternionKeyframeTrack,
  21939. ValueTypeName: 'quaternion',
  21940. // ValueBufferType is inherited
  21941. DefaultInterpolation: InterpolateLinear,
  21942. InterpolantFactoryMethodLinear: function (result) {
  21943. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21944. },
  21945. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21946. });
  21947. /**
  21948. *
  21949. * A Track that interpolates Strings
  21950. *
  21951. *
  21952. * @author Ben Houston / http://clara.io/
  21953. * @author David Sarno / http://lighthaus.us/
  21954. * @author tschw
  21955. */
  21956. function StringKeyframeTrack(name, times, values, interpolation) {
  21957. KeyframeTrack.call(this, name, times, values, interpolation);
  21958. }
  21959. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21960. constructor: StringKeyframeTrack,
  21961. ValueTypeName: 'string',
  21962. ValueBufferType: Array,
  21963. DefaultInterpolation: InterpolateDiscrete,
  21964. InterpolantFactoryMethodLinear: undefined,
  21965. InterpolantFactoryMethodSmooth: undefined
  21966. });
  21967. /**
  21968. *
  21969. * A Track of vectored keyframe values.
  21970. *
  21971. *
  21972. * @author Ben Houston / http://clara.io/
  21973. * @author David Sarno / http://lighthaus.us/
  21974. * @author tschw
  21975. */
  21976. function VectorKeyframeTrack(name, times, values, interpolation) {
  21977. KeyframeTrack.call(this, name, times, values, interpolation);
  21978. }
  21979. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21980. constructor: VectorKeyframeTrack,
  21981. ValueTypeName: 'vector' // ValueBufferType is inherited
  21982. // DefaultInterpolation is inherited
  21983. });
  21984. /**
  21985. *
  21986. * Reusable set of Tracks that represent an animation.
  21987. *
  21988. * @author Ben Houston / http://clara.io/
  21989. * @author David Sarno / http://lighthaus.us/
  21990. */
  21991. function AnimationClip(name, duration, tracks) {
  21992. this.name = name;
  21993. this.tracks = tracks;
  21994. this.duration = duration !== undefined ? duration : -1;
  21995. this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21996. if (this.duration < 0) {
  21997. this.resetDuration();
  21998. }
  21999. }
  22000. function getTrackTypeForValueTypeName(typeName) {
  22001. switch (typeName.toLowerCase()) {
  22002. case 'scalar':
  22003. case 'double':
  22004. case 'float':
  22005. case 'number':
  22006. case 'integer':
  22007. return NumberKeyframeTrack;
  22008. case 'vector':
  22009. case 'vector2':
  22010. case 'vector3':
  22011. case 'vector4':
  22012. return VectorKeyframeTrack;
  22013. case 'color':
  22014. return ColorKeyframeTrack;
  22015. case 'quaternion':
  22016. return QuaternionKeyframeTrack;
  22017. case 'bool':
  22018. case 'boolean':
  22019. return BooleanKeyframeTrack;
  22020. case 'string':
  22021. return StringKeyframeTrack;
  22022. }
  22023. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22024. }
  22025. function parseKeyframeTrack(json) {
  22026. if (json.type === undefined) {
  22027. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22028. }
  22029. var trackType = getTrackTypeForValueTypeName(json.type);
  22030. if (json.times === undefined) {
  22031. var times = [],
  22032. values = [];
  22033. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22034. json.times = times;
  22035. json.values = values;
  22036. } // derived classes can define a static parse method
  22037. if (trackType.parse !== undefined) {
  22038. return trackType.parse(json);
  22039. } else {
  22040. // by default, we assume a constructor compatible with the base
  22041. return new trackType(json.name, json.times, json.values, json.interpolation);
  22042. }
  22043. }
  22044. Object.assign(AnimationClip, {
  22045. parse: function (json) {
  22046. var tracks = [],
  22047. jsonTracks = json.tracks,
  22048. frameTime = 1.0 / (json.fps || 1.0);
  22049. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  22050. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22051. }
  22052. return new AnimationClip(json.name, json.duration, tracks);
  22053. },
  22054. toJSON: function (clip) {
  22055. var tracks = [],
  22056. clipTracks = clip.tracks;
  22057. var json = {
  22058. 'name': clip.name,
  22059. 'duration': clip.duration,
  22060. 'tracks': tracks,
  22061. 'uuid': clip.uuid
  22062. };
  22063. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  22064. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22065. }
  22066. return json;
  22067. },
  22068. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  22069. var numMorphTargets = morphTargetSequence.length;
  22070. var tracks = [];
  22071. for (var i = 0; i < numMorphTargets; i++) {
  22072. var times = [];
  22073. var values = [];
  22074. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22075. values.push(0, 1, 0);
  22076. var order = AnimationUtils.getKeyframeOrder(times);
  22077. times = AnimationUtils.sortedArray(times, 1, order);
  22078. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22079. // last frame as well for perfect loop.
  22080. if (!noLoop && times[0] === 0) {
  22081. times.push(numMorphTargets);
  22082. values.push(values[0]);
  22083. }
  22084. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22085. }
  22086. return new AnimationClip(name, -1, tracks);
  22087. },
  22088. findByName: function (objectOrClipArray, name) {
  22089. var clipArray = objectOrClipArray;
  22090. if (!Array.isArray(objectOrClipArray)) {
  22091. var o = objectOrClipArray;
  22092. clipArray = o.geometry && o.geometry.animations || o.animations;
  22093. }
  22094. for (var i = 0; i < clipArray.length; i++) {
  22095. if (clipArray[i].name === name) {
  22096. return clipArray[i];
  22097. }
  22098. }
  22099. return null;
  22100. },
  22101. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  22102. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22103. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22104. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22105. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22106. for (var i = 0, il = morphTargets.length; i < il; i++) {
  22107. var morphTarget = morphTargets[i];
  22108. var parts = morphTarget.name.match(pattern);
  22109. if (parts && parts.length > 1) {
  22110. var name = parts[1];
  22111. var animationMorphTargets = animationToMorphTargets[name];
  22112. if (!animationMorphTargets) {
  22113. animationToMorphTargets[name] = animationMorphTargets = [];
  22114. }
  22115. animationMorphTargets.push(morphTarget);
  22116. }
  22117. }
  22118. var clips = [];
  22119. for (var name in animationToMorphTargets) {
  22120. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22121. }
  22122. return clips;
  22123. },
  22124. // parse the animation.hierarchy format
  22125. parseAnimation: function (animation, bones) {
  22126. if (!animation) {
  22127. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22128. return null;
  22129. }
  22130. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22131. // only return track if there are actually keys.
  22132. if (animationKeys.length !== 0) {
  22133. var times = [];
  22134. var values = [];
  22135. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22136. if (times.length !== 0) {
  22137. destTracks.push(new trackType(trackName, times, values));
  22138. }
  22139. }
  22140. };
  22141. var tracks = [];
  22142. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  22143. var duration = animation.length || -1;
  22144. var fps = animation.fps || 30;
  22145. var hierarchyTracks = animation.hierarchy || [];
  22146. for (var h = 0; h < hierarchyTracks.length; h++) {
  22147. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22148. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22149. if (animationKeys[0].morphTargets) {
  22150. // figure out all morph targets used in this track
  22151. var morphTargetNames = {};
  22152. for (var k = 0; k < animationKeys.length; k++) {
  22153. if (animationKeys[k].morphTargets) {
  22154. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22155. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22156. }
  22157. }
  22158. } // create a track for each morph target with all zero
  22159. // morphTargetInfluences except for the keys in which
  22160. // the morphTarget is named.
  22161. for (var morphTargetName in morphTargetNames) {
  22162. var times = [];
  22163. var values = [];
  22164. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22165. var animationKey = animationKeys[k];
  22166. times.push(animationKey.time);
  22167. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22168. }
  22169. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22170. }
  22171. duration = morphTargetNames.length * (fps || 1.0);
  22172. } else {
  22173. // ...assume skeletal animation
  22174. var boneName = '.bones[' + bones[h].name + ']';
  22175. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22176. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22177. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22178. }
  22179. }
  22180. if (tracks.length === 0) {
  22181. return null;
  22182. }
  22183. var clip = new AnimationClip(clipName, duration, tracks);
  22184. return clip;
  22185. }
  22186. });
  22187. Object.assign(AnimationClip.prototype, {
  22188. resetDuration: function () {
  22189. var tracks = this.tracks,
  22190. duration = 0;
  22191. for (var i = 0, n = tracks.length; i !== n; ++i) {
  22192. var track = this.tracks[i];
  22193. duration = Math.max(duration, track.times[track.times.length - 1]);
  22194. }
  22195. this.duration = duration;
  22196. return this;
  22197. },
  22198. trim: function () {
  22199. for (var i = 0; i < this.tracks.length; i++) {
  22200. this.tracks[i].trim(0, this.duration);
  22201. }
  22202. return this;
  22203. },
  22204. validate: function () {
  22205. var valid = true;
  22206. for (var i = 0; i < this.tracks.length; i++) {
  22207. valid = valid && this.tracks[i].validate();
  22208. }
  22209. return valid;
  22210. },
  22211. optimize: function () {
  22212. for (var i = 0; i < this.tracks.length; i++) {
  22213. this.tracks[i].optimize();
  22214. }
  22215. return this;
  22216. },
  22217. clone: function () {
  22218. var tracks = [];
  22219. for (var i = 0; i < this.tracks.length; i++) {
  22220. tracks.push(this.tracks[i].clone());
  22221. }
  22222. return new AnimationClip(this.name, this.duration, tracks);
  22223. }
  22224. });
  22225. /**
  22226. * @author mrdoob / http://mrdoob.com/
  22227. */
  22228. var Cache = {
  22229. enabled: false,
  22230. files: {},
  22231. add: function (key, file) {
  22232. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22233. this.files[key] = file;
  22234. },
  22235. get: function (key) {
  22236. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22237. return this.files[key];
  22238. },
  22239. remove: function (key) {
  22240. delete this.files[key];
  22241. },
  22242. clear: function () {
  22243. this.files = {};
  22244. }
  22245. };
  22246. /**
  22247. * @author mrdoob / http://mrdoob.com/
  22248. */
  22249. exports.Cache = Cache;
  22250. function LoadingManager(onLoad, onProgress, onError) {
  22251. var scope = this;
  22252. var isLoading = false;
  22253. var itemsLoaded = 0;
  22254. var itemsTotal = 0;
  22255. var urlModifier = undefined;
  22256. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22257. // in the constructor
  22258. this.onStart = undefined;
  22259. this.onLoad = onLoad;
  22260. this.onProgress = onProgress;
  22261. this.onError = onError;
  22262. this.itemStart = function (url) {
  22263. itemsTotal++;
  22264. if (isLoading === false) {
  22265. if (scope.onStart !== undefined) {
  22266. scope.onStart(url, itemsLoaded, itemsTotal);
  22267. }
  22268. }
  22269. isLoading = true;
  22270. };
  22271. this.itemEnd = function (url) {
  22272. itemsLoaded++;
  22273. if (scope.onProgress !== undefined) {
  22274. scope.onProgress(url, itemsLoaded, itemsTotal);
  22275. }
  22276. if (itemsLoaded === itemsTotal) {
  22277. isLoading = false;
  22278. if (scope.onLoad !== undefined) {
  22279. scope.onLoad();
  22280. }
  22281. }
  22282. };
  22283. this.itemError = function (url) {
  22284. if (scope.onError !== undefined) {
  22285. scope.onError(url);
  22286. }
  22287. };
  22288. this.resolveURL = function (url) {
  22289. if (urlModifier) {
  22290. return urlModifier(url);
  22291. }
  22292. return url;
  22293. };
  22294. this.setURLModifier = function (transform) {
  22295. urlModifier = transform;
  22296. return this;
  22297. };
  22298. this.addHandler = function (regex, loader) {
  22299. handlers.push(regex, loader);
  22300. return this;
  22301. };
  22302. this.removeHandler = function (regex) {
  22303. var index = handlers.indexOf(regex);
  22304. if (index !== -1) {
  22305. handlers.splice(index, 2);
  22306. }
  22307. return this;
  22308. };
  22309. this.getHandler = function (file) {
  22310. for (var i = 0, l = handlers.length; i < l; i += 2) {
  22311. var regex = handlers[i];
  22312. var loader = handlers[i + 1];
  22313. if (regex.test(file)) {
  22314. return loader;
  22315. }
  22316. }
  22317. return null;
  22318. };
  22319. }
  22320. var DefaultLoadingManager = new LoadingManager();
  22321. /**
  22322. * @author alteredq / http://alteredqualia.com/
  22323. */
  22324. exports.DefaultLoadingManager = DefaultLoadingManager;
  22325. function Loader(manager) {
  22326. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22327. this.crossOrigin = 'anonymous';
  22328. this.path = '';
  22329. this.resourcePath = '';
  22330. }
  22331. Object.assign(Loader.prototype, {
  22332. load: function ()
  22333. /* url, onLoad, onProgress, onError */
  22334. {},
  22335. parse: function ()
  22336. /* data */
  22337. {},
  22338. setCrossOrigin: function (crossOrigin) {
  22339. this.crossOrigin = crossOrigin;
  22340. return this;
  22341. },
  22342. setPath: function (path) {
  22343. this.path = path;
  22344. return this;
  22345. },
  22346. setResourcePath: function (resourcePath) {
  22347. this.resourcePath = resourcePath;
  22348. return this;
  22349. }
  22350. });
  22351. /**
  22352. * @author mrdoob / http://mrdoob.com/
  22353. */
  22354. var loading = {};
  22355. function FileLoader(manager) {
  22356. Loader.call(this, manager);
  22357. }
  22358. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22359. constructor: FileLoader,
  22360. load: function (url, onLoad, onProgress, onError) {
  22361. if (url === undefined) url = '';
  22362. if (this.path !== undefined) url = this.path + url;
  22363. url = this.manager.resolveURL(url);
  22364. var scope = this;
  22365. var cached = Cache.get(url);
  22366. if (cached !== undefined) {
  22367. scope.manager.itemStart(url);
  22368. setTimeout(function () {
  22369. if (onLoad) onLoad(cached);
  22370. scope.manager.itemEnd(url);
  22371. }, 0);
  22372. return cached;
  22373. } // Check if request is duplicate
  22374. if (loading[url] !== undefined) {
  22375. loading[url].push({
  22376. onLoad: onLoad,
  22377. onProgress: onProgress,
  22378. onError: onError
  22379. });
  22380. return;
  22381. } // Check for data: URI
  22382. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22383. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22384. if (dataUriRegexResult) {
  22385. var mimeType = dataUriRegexResult[1];
  22386. var isBase64 = !!dataUriRegexResult[2];
  22387. var data = dataUriRegexResult[3];
  22388. data = decodeURIComponent(data);
  22389. if (isBase64) data = atob(data);
  22390. try {
  22391. var response;
  22392. var responseType = (this.responseType || '').toLowerCase();
  22393. switch (responseType) {
  22394. case 'arraybuffer':
  22395. case 'blob':
  22396. var view = new Uint8Array(data.length);
  22397. for (var i = 0; i < data.length; i++) {
  22398. view[i] = data.charCodeAt(i);
  22399. }
  22400. if (responseType === 'blob') {
  22401. response = new Blob([view.buffer], {
  22402. type: mimeType
  22403. });
  22404. } else {
  22405. response = view.buffer;
  22406. }
  22407. break;
  22408. case 'document':
  22409. var parser = new DOMParser();
  22410. response = parser.parseFromString(data, mimeType);
  22411. break;
  22412. case 'json':
  22413. response = JSON.parse(data);
  22414. break;
  22415. default:
  22416. // 'text' or other
  22417. response = data;
  22418. break;
  22419. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22420. setTimeout(function () {
  22421. if (onLoad) onLoad(response);
  22422. scope.manager.itemEnd(url);
  22423. }, 0);
  22424. } catch (error) {
  22425. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22426. setTimeout(function () {
  22427. if (onError) onError(error);
  22428. scope.manager.itemError(url);
  22429. scope.manager.itemEnd(url);
  22430. }, 0);
  22431. }
  22432. } else {
  22433. // Initialise array for duplicate requests
  22434. loading[url] = [];
  22435. loading[url].push({
  22436. onLoad: onLoad,
  22437. onProgress: onProgress,
  22438. onError: onError
  22439. });
  22440. var request = new XMLHttpRequest();
  22441. request.open('GET', url, true);
  22442. request.addEventListener('load', function (event) {
  22443. var response = this.response;
  22444. Cache.add(url, response);
  22445. var callbacks = loading[url];
  22446. delete loading[url];
  22447. if (this.status === 200 || this.status === 0) {
  22448. // Some browsers return HTTP Status 0 when using non-http protocol
  22449. // e.g. 'file://' or 'data://'. Handle as success.
  22450. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.');
  22451. for (var i = 0, il = callbacks.length; i < il; i++) {
  22452. var callback = callbacks[i];
  22453. if (callback.onLoad) callback.onLoad(response);
  22454. }
  22455. scope.manager.itemEnd(url);
  22456. } else {
  22457. for (var i = 0, il = callbacks.length; i < il; i++) {
  22458. var callback = callbacks[i];
  22459. if (callback.onError) callback.onError(event);
  22460. }
  22461. scope.manager.itemError(url);
  22462. scope.manager.itemEnd(url);
  22463. }
  22464. }, false);
  22465. request.addEventListener('progress', function (event) {
  22466. var callbacks = loading[url];
  22467. for (var i = 0, il = callbacks.length; i < il; i++) {
  22468. var callback = callbacks[i];
  22469. if (callback.onProgress) callback.onProgress(event);
  22470. }
  22471. }, false);
  22472. request.addEventListener('error', function (event) {
  22473. var callbacks = loading[url];
  22474. delete loading[url];
  22475. for (var i = 0, il = callbacks.length; i < il; i++) {
  22476. var callback = callbacks[i];
  22477. if (callback.onError) callback.onError(event);
  22478. }
  22479. scope.manager.itemError(url);
  22480. scope.manager.itemEnd(url);
  22481. }, false);
  22482. request.addEventListener('abort', function (event) {
  22483. var callbacks = loading[url];
  22484. delete loading[url];
  22485. for (var i = 0, il = callbacks.length; i < il; i++) {
  22486. var callback = callbacks[i];
  22487. if (callback.onError) callback.onError(event);
  22488. }
  22489. scope.manager.itemError(url);
  22490. scope.manager.itemEnd(url);
  22491. }, false);
  22492. if (this.responseType !== undefined) request.responseType = this.responseType;
  22493. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22494. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22495. for (var header in this.requestHeader) {
  22496. request.setRequestHeader(header, this.requestHeader[header]);
  22497. }
  22498. request.send(null);
  22499. }
  22500. scope.manager.itemStart(url);
  22501. return request;
  22502. },
  22503. setResponseType: function (value) {
  22504. this.responseType = value;
  22505. return this;
  22506. },
  22507. setWithCredentials: function (value) {
  22508. this.withCredentials = value;
  22509. return this;
  22510. },
  22511. setMimeType: function (value) {
  22512. this.mimeType = value;
  22513. return this;
  22514. },
  22515. setRequestHeader: function (value) {
  22516. this.requestHeader = value;
  22517. return this;
  22518. }
  22519. });
  22520. /**
  22521. * @author bhouston / http://clara.io/
  22522. */
  22523. function AnimationLoader(manager) {
  22524. Loader.call(this, manager);
  22525. }
  22526. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22527. constructor: AnimationLoader,
  22528. load: function (url, onLoad, onProgress, onError) {
  22529. var scope = this;
  22530. var loader = new FileLoader(scope.manager);
  22531. loader.setPath(scope.path);
  22532. loader.load(url, function (text) {
  22533. onLoad(scope.parse(JSON.parse(text)));
  22534. }, onProgress, onError);
  22535. },
  22536. parse: function (json) {
  22537. var animations = [];
  22538. for (var i = 0; i < json.length; i++) {
  22539. var clip = AnimationClip.parse(json[i]);
  22540. animations.push(clip);
  22541. }
  22542. return animations;
  22543. }
  22544. });
  22545. /**
  22546. * @author mrdoob / http://mrdoob.com/
  22547. *
  22548. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22549. *
  22550. * Sub classes have to implement the parse() method which will be used in load().
  22551. */
  22552. function CompressedTextureLoader(manager) {
  22553. Loader.call(this, manager);
  22554. }
  22555. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22556. constructor: CompressedTextureLoader,
  22557. load: function (url, onLoad, onProgress, onError) {
  22558. var scope = this;
  22559. var images = [];
  22560. var texture = new CompressedTexture();
  22561. texture.image = images;
  22562. var loader = new FileLoader(this.manager);
  22563. loader.setPath(this.path);
  22564. loader.setResponseType('arraybuffer');
  22565. function loadTexture(i) {
  22566. loader.load(url[i], function (buffer) {
  22567. var texDatas = scope.parse(buffer, true);
  22568. images[i] = {
  22569. width: texDatas.width,
  22570. height: texDatas.height,
  22571. format: texDatas.format,
  22572. mipmaps: texDatas.mipmaps
  22573. };
  22574. loaded += 1;
  22575. if (loaded === 6) {
  22576. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22577. texture.format = texDatas.format;
  22578. texture.needsUpdate = true;
  22579. if (onLoad) onLoad(texture);
  22580. }
  22581. }, onProgress, onError);
  22582. }
  22583. if (Array.isArray(url)) {
  22584. var loaded = 0;
  22585. for (var i = 0, il = url.length; i < il; ++i) {
  22586. loadTexture(i);
  22587. }
  22588. } else {
  22589. // compressed cubemap texture stored in a single DDS file
  22590. loader.load(url, function (buffer) {
  22591. var texDatas = scope.parse(buffer, true);
  22592. if (texDatas.isCubemap) {
  22593. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22594. for (var f = 0; f < faces; f++) {
  22595. images[f] = {
  22596. mipmaps: []
  22597. };
  22598. for (var i = 0; i < texDatas.mipmapCount; i++) {
  22599. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22600. images[f].format = texDatas.format;
  22601. images[f].width = texDatas.width;
  22602. images[f].height = texDatas.height;
  22603. }
  22604. }
  22605. } else {
  22606. texture.image.width = texDatas.width;
  22607. texture.image.height = texDatas.height;
  22608. texture.mipmaps = texDatas.mipmaps;
  22609. }
  22610. if (texDatas.mipmapCount === 1) {
  22611. texture.minFilter = LinearFilter;
  22612. }
  22613. texture.format = texDatas.format;
  22614. texture.needsUpdate = true;
  22615. if (onLoad) onLoad(texture);
  22616. }, onProgress, onError);
  22617. }
  22618. return texture;
  22619. }
  22620. });
  22621. /**
  22622. * @author Nikos M. / https://github.com/foo123/
  22623. *
  22624. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22625. *
  22626. * Sub classes have to implement the parse() method which will be used in load().
  22627. */
  22628. function DataTextureLoader(manager) {
  22629. Loader.call(this, manager);
  22630. }
  22631. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22632. constructor: DataTextureLoader,
  22633. load: function (url, onLoad, onProgress, onError) {
  22634. var scope = this;
  22635. var texture = new DataTexture();
  22636. var loader = new FileLoader(this.manager);
  22637. loader.setResponseType('arraybuffer');
  22638. loader.setPath(this.path);
  22639. loader.load(url, function (buffer) {
  22640. var texData = scope.parse(buffer);
  22641. if (!texData) return;
  22642. if (texData.image !== undefined) {
  22643. texture.image = texData.image;
  22644. } else if (texData.data !== undefined) {
  22645. texture.image.width = texData.width;
  22646. texture.image.height = texData.height;
  22647. texture.image.data = texData.data;
  22648. }
  22649. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22650. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22651. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22652. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipmapLinearFilter;
  22653. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22654. if (texData.format !== undefined) {
  22655. texture.format = texData.format;
  22656. }
  22657. if (texData.type !== undefined) {
  22658. texture.type = texData.type;
  22659. }
  22660. if (texData.mipmaps !== undefined) {
  22661. texture.mipmaps = texData.mipmaps;
  22662. }
  22663. if (texData.mipmapCount === 1) {
  22664. texture.minFilter = LinearFilter;
  22665. }
  22666. texture.needsUpdate = true;
  22667. if (onLoad) onLoad(texture, texData);
  22668. }, onProgress, onError);
  22669. return texture;
  22670. }
  22671. });
  22672. /**
  22673. * @author mrdoob / http://mrdoob.com/
  22674. */
  22675. function ImageLoader(manager) {
  22676. Loader.call(this, manager);
  22677. }
  22678. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22679. constructor: ImageLoader,
  22680. load: function (url, onLoad, onProgress, onError) {
  22681. if (this.path !== undefined) url = this.path + url;
  22682. url = this.manager.resolveURL(url);
  22683. var scope = this;
  22684. var cached = Cache.get(url);
  22685. if (cached !== undefined) {
  22686. scope.manager.itemStart(url);
  22687. setTimeout(function () {
  22688. if (onLoad) onLoad(cached);
  22689. scope.manager.itemEnd(url);
  22690. }, 0);
  22691. return cached;
  22692. }
  22693. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22694. function onImageLoad() {
  22695. image.removeEventListener('load', onImageLoad, false);
  22696. image.removeEventListener('error', onImageError, false);
  22697. Cache.add(url, this);
  22698. if (onLoad) onLoad(this);
  22699. scope.manager.itemEnd(url);
  22700. }
  22701. function onImageError(event) {
  22702. image.removeEventListener('load', onImageLoad, false);
  22703. image.removeEventListener('error', onImageError, false);
  22704. if (onError) onError(event);
  22705. scope.manager.itemError(url);
  22706. scope.manager.itemEnd(url);
  22707. }
  22708. image.addEventListener('load', onImageLoad, false);
  22709. image.addEventListener('error', onImageError, false);
  22710. if (url.substr(0, 5) !== 'data:') {
  22711. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22712. }
  22713. scope.manager.itemStart(url);
  22714. image.src = url;
  22715. return image;
  22716. }
  22717. });
  22718. /**
  22719. * @author mrdoob / http://mrdoob.com/
  22720. */
  22721. function CubeTextureLoader(manager) {
  22722. Loader.call(this, manager);
  22723. }
  22724. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22725. constructor: CubeTextureLoader,
  22726. load: function (urls, onLoad, onProgress, onError) {
  22727. var texture = new CubeTexture();
  22728. var loader = new ImageLoader(this.manager);
  22729. loader.setCrossOrigin(this.crossOrigin);
  22730. loader.setPath(this.path);
  22731. var loaded = 0;
  22732. function loadTexture(i) {
  22733. loader.load(urls[i], function (image) {
  22734. texture.images[i] = image;
  22735. loaded++;
  22736. if (loaded === 6) {
  22737. texture.needsUpdate = true;
  22738. if (onLoad) onLoad(texture);
  22739. }
  22740. }, undefined, onError);
  22741. }
  22742. for (var i = 0; i < urls.length; ++i) {
  22743. loadTexture(i);
  22744. }
  22745. return texture;
  22746. }
  22747. });
  22748. /**
  22749. * @author mrdoob / http://mrdoob.com/
  22750. */
  22751. function TextureLoader(manager) {
  22752. Loader.call(this, manager);
  22753. }
  22754. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22755. constructor: TextureLoader,
  22756. load: function (url, onLoad, onProgress, onError) {
  22757. var texture = new Texture();
  22758. var loader = new ImageLoader(this.manager);
  22759. loader.setCrossOrigin(this.crossOrigin);
  22760. loader.setPath(this.path);
  22761. loader.load(url, function (image) {
  22762. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22763. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22764. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22765. texture.needsUpdate = true;
  22766. if (onLoad !== undefined) {
  22767. onLoad(texture);
  22768. }
  22769. }, onProgress, onError);
  22770. return texture;
  22771. }
  22772. });
  22773. /**
  22774. * @author zz85 / http://www.lab4games.net/zz85/blog
  22775. * Extensible curve object
  22776. *
  22777. * Some common of curve methods:
  22778. * .getPoint( t, optionalTarget ), .getTangent( t )
  22779. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  22780. * .getPoints(), .getSpacedPoints()
  22781. * .getLength()
  22782. * .updateArcLengths()
  22783. *
  22784. * This following curves inherit from THREE.Curve:
  22785. *
  22786. * -- 2D curves --
  22787. * THREE.ArcCurve
  22788. * THREE.CubicBezierCurve
  22789. * THREE.EllipseCurve
  22790. * THREE.LineCurve
  22791. * THREE.QuadraticBezierCurve
  22792. * THREE.SplineCurve
  22793. *
  22794. * -- 3D curves --
  22795. * THREE.CatmullRomCurve3
  22796. * THREE.CubicBezierCurve3
  22797. * THREE.LineCurve3
  22798. * THREE.QuadraticBezierCurve3
  22799. *
  22800. * A series of curves can be represented as a THREE.CurvePath.
  22801. *
  22802. **/
  22803. /**************************************************************
  22804. * Abstract Curve base class
  22805. **************************************************************/
  22806. function Curve() {
  22807. this.type = 'Curve';
  22808. this.arcLengthDivisions = 200;
  22809. }
  22810. Object.assign(Curve.prototype, {
  22811. // Virtual base class method to overwrite and implement in subclasses
  22812. // - t [0 .. 1]
  22813. getPoint: function ()
  22814. /* t, optionalTarget */
  22815. {
  22816. console.warn('THREE.Curve: .getPoint() not implemented.');
  22817. return null;
  22818. },
  22819. // Get point at relative position in curve according to arc length
  22820. // - u [0 .. 1]
  22821. getPointAt: function (u, optionalTarget) {
  22822. var t = this.getUtoTmapping(u);
  22823. return this.getPoint(t, optionalTarget);
  22824. },
  22825. // Get sequence of points using getPoint( t )
  22826. getPoints: function (divisions) {
  22827. if (divisions === undefined) divisions = 5;
  22828. var points = [];
  22829. for (var d = 0; d <= divisions; d++) {
  22830. points.push(this.getPoint(d / divisions));
  22831. }
  22832. return points;
  22833. },
  22834. // Get sequence of points using getPointAt( u )
  22835. getSpacedPoints: function (divisions) {
  22836. if (divisions === undefined) divisions = 5;
  22837. var points = [];
  22838. for (var d = 0; d <= divisions; d++) {
  22839. points.push(this.getPointAt(d / divisions));
  22840. }
  22841. return points;
  22842. },
  22843. // Get total curve arc length
  22844. getLength: function () {
  22845. var lengths = this.getLengths();
  22846. return lengths[lengths.length - 1];
  22847. },
  22848. // Get list of cumulative segment lengths
  22849. getLengths: function (divisions) {
  22850. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22851. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22852. return this.cacheArcLengths;
  22853. }
  22854. this.needsUpdate = false;
  22855. var cache = [];
  22856. var current,
  22857. last = this.getPoint(0);
  22858. var p,
  22859. sum = 0;
  22860. cache.push(0);
  22861. for (p = 1; p <= divisions; p++) {
  22862. current = this.getPoint(p / divisions);
  22863. sum += current.distanceTo(last);
  22864. cache.push(sum);
  22865. last = current;
  22866. }
  22867. this.cacheArcLengths = cache;
  22868. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22869. },
  22870. updateArcLengths: function () {
  22871. this.needsUpdate = true;
  22872. this.getLengths();
  22873. },
  22874. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22875. getUtoTmapping: function (u, distance) {
  22876. var arcLengths = this.getLengths();
  22877. var i = 0,
  22878. il = arcLengths.length;
  22879. var targetArcLength; // The targeted u distance value to get
  22880. if (distance) {
  22881. targetArcLength = distance;
  22882. } else {
  22883. targetArcLength = u * arcLengths[il - 1];
  22884. } // binary search for the index with largest value smaller than target u distance
  22885. var low = 0,
  22886. high = il - 1,
  22887. comparison;
  22888. while (low <= high) {
  22889. 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
  22890. comparison = arcLengths[i] - targetArcLength;
  22891. if (comparison < 0) {
  22892. low = i + 1;
  22893. } else if (comparison > 0) {
  22894. high = i - 1;
  22895. } else {
  22896. high = i;
  22897. break; // DONE
  22898. }
  22899. }
  22900. i = high;
  22901. if (arcLengths[i] === targetArcLength) {
  22902. return i / (il - 1);
  22903. } // we could get finer grain at lengths, or use simple interpolation between two points
  22904. var lengthBefore = arcLengths[i];
  22905. var lengthAfter = arcLengths[i + 1];
  22906. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22907. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22908. var t = (i + segmentFraction) / (il - 1);
  22909. return t;
  22910. },
  22911. // Returns a unit vector tangent at t
  22912. // In case any sub curve does not implement its tangent derivation,
  22913. // 2 points a small delta apart will be used to find its gradient
  22914. // which seems to give a reasonable approximation
  22915. getTangent: function (t) {
  22916. var delta = 0.0001;
  22917. var t1 = t - delta;
  22918. var t2 = t + delta; // Capping in case of danger
  22919. if (t1 < 0) t1 = 0;
  22920. if (t2 > 1) t2 = 1;
  22921. var pt1 = this.getPoint(t1);
  22922. var pt2 = this.getPoint(t2);
  22923. var vec = pt2.clone().sub(pt1);
  22924. return vec.normalize();
  22925. },
  22926. getTangentAt: function (u) {
  22927. var t = this.getUtoTmapping(u);
  22928. return this.getTangent(t);
  22929. },
  22930. computeFrenetFrames: function (segments, closed) {
  22931. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22932. var normal = new Vector3();
  22933. var tangents = [];
  22934. var normals = [];
  22935. var binormals = [];
  22936. var vec = new Vector3();
  22937. var mat = new Matrix4();
  22938. var i, u, theta; // compute the tangent vectors for each segment on the curve
  22939. for (i = 0; i <= segments; i++) {
  22940. u = i / segments;
  22941. tangents[i] = this.getTangentAt(u);
  22942. tangents[i].normalize();
  22943. } // select an initial normal vector perpendicular to the first tangent vector,
  22944. // and in the direction of the minimum tangent xyz component
  22945. normals[0] = new Vector3();
  22946. binormals[0] = new Vector3();
  22947. var min = Number.MAX_VALUE;
  22948. var tx = Math.abs(tangents[0].x);
  22949. var ty = Math.abs(tangents[0].y);
  22950. var tz = Math.abs(tangents[0].z);
  22951. if (tx <= min) {
  22952. min = tx;
  22953. normal.set(1, 0, 0);
  22954. }
  22955. if (ty <= min) {
  22956. min = ty;
  22957. normal.set(0, 1, 0);
  22958. }
  22959. if (tz <= min) {
  22960. normal.set(0, 0, 1);
  22961. }
  22962. vec.crossVectors(tangents[0], normal).normalize();
  22963. normals[0].crossVectors(tangents[0], vec);
  22964. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22965. for (i = 1; i <= segments; i++) {
  22966. normals[i] = normals[i - 1].clone();
  22967. binormals[i] = binormals[i - 1].clone();
  22968. vec.crossVectors(tangents[i - 1], tangents[i]);
  22969. if (vec.length() > Number.EPSILON) {
  22970. vec.normalize();
  22971. theta = Math.acos(_Math.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22972. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22973. }
  22974. binormals[i].crossVectors(tangents[i], normals[i]);
  22975. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22976. if (closed === true) {
  22977. theta = Math.acos(_Math.clamp(normals[0].dot(normals[segments]), -1, 1));
  22978. theta /= segments;
  22979. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22980. theta = -theta;
  22981. }
  22982. for (i = 1; i <= segments; i++) {
  22983. // twist a little...
  22984. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22985. binormals[i].crossVectors(tangents[i], normals[i]);
  22986. }
  22987. }
  22988. return {
  22989. tangents: tangents,
  22990. normals: normals,
  22991. binormals: binormals
  22992. };
  22993. },
  22994. clone: function () {
  22995. return new this.constructor().copy(this);
  22996. },
  22997. copy: function (source) {
  22998. this.arcLengthDivisions = source.arcLengthDivisions;
  22999. return this;
  23000. },
  23001. toJSON: function () {
  23002. var data = {
  23003. metadata: {
  23004. version: 4.5,
  23005. type: 'Curve',
  23006. generator: 'Curve.toJSON'
  23007. }
  23008. };
  23009. data.arcLengthDivisions = this.arcLengthDivisions;
  23010. data.type = this.type;
  23011. return data;
  23012. },
  23013. fromJSON: function (json) {
  23014. this.arcLengthDivisions = json.arcLengthDivisions;
  23015. return this;
  23016. }
  23017. });
  23018. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23019. Curve.call(this);
  23020. this.type = 'EllipseCurve';
  23021. this.aX = aX || 0;
  23022. this.aY = aY || 0;
  23023. this.xRadius = xRadius || 1;
  23024. this.yRadius = yRadius || 1;
  23025. this.aStartAngle = aStartAngle || 0;
  23026. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23027. this.aClockwise = aClockwise || false;
  23028. this.aRotation = aRotation || 0;
  23029. }
  23030. EllipseCurve.prototype = Object.create(Curve.prototype);
  23031. EllipseCurve.prototype.constructor = EllipseCurve;
  23032. EllipseCurve.prototype.isEllipseCurve = true;
  23033. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  23034. var point = optionalTarget || new Vector2();
  23035. var twoPi = Math.PI * 2;
  23036. var deltaAngle = this.aEndAngle - this.aStartAngle;
  23037. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  23038. while (deltaAngle < 0) deltaAngle += twoPi;
  23039. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  23040. if (deltaAngle < Number.EPSILON) {
  23041. if (samePoints) {
  23042. deltaAngle = 0;
  23043. } else {
  23044. deltaAngle = twoPi;
  23045. }
  23046. }
  23047. if (this.aClockwise === true && !samePoints) {
  23048. if (deltaAngle === twoPi) {
  23049. deltaAngle = -twoPi;
  23050. } else {
  23051. deltaAngle = deltaAngle - twoPi;
  23052. }
  23053. }
  23054. var angle = this.aStartAngle + t * deltaAngle;
  23055. var x = this.aX + this.xRadius * Math.cos(angle);
  23056. var y = this.aY + this.yRadius * Math.sin(angle);
  23057. if (this.aRotation !== 0) {
  23058. var cos = Math.cos(this.aRotation);
  23059. var sin = Math.sin(this.aRotation);
  23060. var tx = x - this.aX;
  23061. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  23062. x = tx * cos - ty * sin + this.aX;
  23063. y = tx * sin + ty * cos + this.aY;
  23064. }
  23065. return point.set(x, y);
  23066. };
  23067. EllipseCurve.prototype.copy = function (source) {
  23068. Curve.prototype.copy.call(this, source);
  23069. this.aX = source.aX;
  23070. this.aY = source.aY;
  23071. this.xRadius = source.xRadius;
  23072. this.yRadius = source.yRadius;
  23073. this.aStartAngle = source.aStartAngle;
  23074. this.aEndAngle = source.aEndAngle;
  23075. this.aClockwise = source.aClockwise;
  23076. this.aRotation = source.aRotation;
  23077. return this;
  23078. };
  23079. EllipseCurve.prototype.toJSON = function () {
  23080. var data = Curve.prototype.toJSON.call(this);
  23081. data.aX = this.aX;
  23082. data.aY = this.aY;
  23083. data.xRadius = this.xRadius;
  23084. data.yRadius = this.yRadius;
  23085. data.aStartAngle = this.aStartAngle;
  23086. data.aEndAngle = this.aEndAngle;
  23087. data.aClockwise = this.aClockwise;
  23088. data.aRotation = this.aRotation;
  23089. return data;
  23090. };
  23091. EllipseCurve.prototype.fromJSON = function (json) {
  23092. Curve.prototype.fromJSON.call(this, json);
  23093. this.aX = json.aX;
  23094. this.aY = json.aY;
  23095. this.xRadius = json.xRadius;
  23096. this.yRadius = json.yRadius;
  23097. this.aStartAngle = json.aStartAngle;
  23098. this.aEndAngle = json.aEndAngle;
  23099. this.aClockwise = json.aClockwise;
  23100. this.aRotation = json.aRotation;
  23101. return this;
  23102. };
  23103. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23104. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23105. this.type = 'ArcCurve';
  23106. }
  23107. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  23108. ArcCurve.prototype.constructor = ArcCurve;
  23109. ArcCurve.prototype.isArcCurve = true;
  23110. /**
  23111. * @author zz85 https://github.com/zz85
  23112. *
  23113. * Centripetal CatmullRom Curve - which is useful for avoiding
  23114. * cusps and self-intersections in non-uniform catmull rom curves.
  23115. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23116. *
  23117. * curve.type accepts centripetal(default), chordal and catmullrom
  23118. * curve.tension is used for catmullrom which defaults to 0.5
  23119. */
  23120. /*
  23121. Based on an optimized c++ solution in
  23122. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23123. - http://ideone.com/NoEbVM
  23124. This CubicPoly class could be used for reusing some variables and calculations,
  23125. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23126. which can be placed in CurveUtils.
  23127. */
  23128. function CubicPoly() {
  23129. var c0 = 0,
  23130. c1 = 0,
  23131. c2 = 0,
  23132. c3 = 0;
  23133. /*
  23134. * Compute coefficients for a cubic polynomial
  23135. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23136. * such that
  23137. * p(0) = x0, p(1) = x1
  23138. * and
  23139. * p'(0) = t0, p'(1) = t1.
  23140. */
  23141. function init(x0, x1, t0, t1) {
  23142. c0 = x0;
  23143. c1 = t0;
  23144. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23145. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23146. }
  23147. return {
  23148. initCatmullRom: function (x0, x1, x2, x3, tension) {
  23149. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  23150. },
  23151. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  23152. // compute tangents when parameterized in [t1,t2]
  23153. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  23154. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  23155. t1 *= dt1;
  23156. t2 *= dt1;
  23157. init(x1, x2, t1, t2);
  23158. },
  23159. calc: function (t) {
  23160. var t2 = t * t;
  23161. var t3 = t2 * t;
  23162. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23163. }
  23164. };
  23165. } //
  23166. var tmp = new Vector3();
  23167. var px = new CubicPoly(),
  23168. py = new CubicPoly(),
  23169. pz = new CubicPoly();
  23170. function CatmullRomCurve3(points, closed, curveType, tension) {
  23171. Curve.call(this);
  23172. this.type = 'CatmullRomCurve3';
  23173. this.points = points || [];
  23174. this.closed = closed || false;
  23175. this.curveType = curveType || 'centripetal';
  23176. this.tension = tension || 0.5;
  23177. }
  23178. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  23179. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23180. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23181. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  23182. var point = optionalTarget || new Vector3();
  23183. var points = this.points;
  23184. var l = points.length;
  23185. var p = (l - (this.closed ? 0 : 1)) * t;
  23186. var intPoint = Math.floor(p);
  23187. var weight = p - intPoint;
  23188. if (this.closed) {
  23189. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  23190. } else if (weight === 0 && intPoint === l - 1) {
  23191. intPoint = l - 2;
  23192. weight = 1;
  23193. }
  23194. var p0, p1, p2, p3; // 4 points
  23195. if (this.closed || intPoint > 0) {
  23196. p0 = points[(intPoint - 1) % l];
  23197. } else {
  23198. // extrapolate first point
  23199. tmp.subVectors(points[0], points[1]).add(points[0]);
  23200. p0 = tmp;
  23201. }
  23202. p1 = points[intPoint % l];
  23203. p2 = points[(intPoint + 1) % l];
  23204. if (this.closed || intPoint + 2 < l) {
  23205. p3 = points[(intPoint + 2) % l];
  23206. } else {
  23207. // extrapolate last point
  23208. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  23209. p3 = tmp;
  23210. }
  23211. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  23212. // init Centripetal / Chordal Catmull-Rom
  23213. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23214. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  23215. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  23216. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  23217. if (dt1 < 1e-4) dt1 = 1.0;
  23218. if (dt0 < 1e-4) dt0 = dt1;
  23219. if (dt2 < 1e-4) dt2 = dt1;
  23220. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  23221. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  23222. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  23223. } else if (this.curveType === 'catmullrom') {
  23224. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  23225. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  23226. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  23227. }
  23228. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  23229. return point;
  23230. };
  23231. CatmullRomCurve3.prototype.copy = function (source) {
  23232. Curve.prototype.copy.call(this, source);
  23233. this.points = [];
  23234. for (var i = 0, l = source.points.length; i < l; i++) {
  23235. var point = source.points[i];
  23236. this.points.push(point.clone());
  23237. }
  23238. this.closed = source.closed;
  23239. this.curveType = source.curveType;
  23240. this.tension = source.tension;
  23241. return this;
  23242. };
  23243. CatmullRomCurve3.prototype.toJSON = function () {
  23244. var data = Curve.prototype.toJSON.call(this);
  23245. data.points = [];
  23246. for (var i = 0, l = this.points.length; i < l; i++) {
  23247. var point = this.points[i];
  23248. data.points.push(point.toArray());
  23249. }
  23250. data.closed = this.closed;
  23251. data.curveType = this.curveType;
  23252. data.tension = this.tension;
  23253. return data;
  23254. };
  23255. CatmullRomCurve3.prototype.fromJSON = function (json) {
  23256. Curve.prototype.fromJSON.call(this, json);
  23257. this.points = [];
  23258. for (var i = 0, l = json.points.length; i < l; i++) {
  23259. var point = json.points[i];
  23260. this.points.push(new Vector3().fromArray(point));
  23261. }
  23262. this.closed = json.closed;
  23263. this.curveType = json.curveType;
  23264. this.tension = json.tension;
  23265. return this;
  23266. };
  23267. /**
  23268. * @author zz85 / http://www.lab4games.net/zz85/blog
  23269. *
  23270. * Bezier Curves formulas obtained from
  23271. * http://en.wikipedia.org/wiki/Bézier_curve
  23272. */
  23273. function CatmullRom(t, p0, p1, p2, p3) {
  23274. var v0 = (p2 - p0) * 0.5;
  23275. var v1 = (p3 - p1) * 0.5;
  23276. var t2 = t * t;
  23277. var t3 = t * t2;
  23278. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  23279. } //
  23280. function QuadraticBezierP0(t, p) {
  23281. var k = 1 - t;
  23282. return k * k * p;
  23283. }
  23284. function QuadraticBezierP1(t, p) {
  23285. return 2 * (1 - t) * t * p;
  23286. }
  23287. function QuadraticBezierP2(t, p) {
  23288. return t * t * p;
  23289. }
  23290. function QuadraticBezier(t, p0, p1, p2) {
  23291. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  23292. } //
  23293. function CubicBezierP0(t, p) {
  23294. var k = 1 - t;
  23295. return k * k * k * p;
  23296. }
  23297. function CubicBezierP1(t, p) {
  23298. var k = 1 - t;
  23299. return 3 * k * k * t * p;
  23300. }
  23301. function CubicBezierP2(t, p) {
  23302. return 3 * (1 - t) * t * t * p;
  23303. }
  23304. function CubicBezierP3(t, p) {
  23305. return t * t * t * p;
  23306. }
  23307. function CubicBezier(t, p0, p1, p2, p3) {
  23308. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  23309. }
  23310. function CubicBezierCurve(v0, v1, v2, v3) {
  23311. Curve.call(this);
  23312. this.type = 'CubicBezierCurve';
  23313. this.v0 = v0 || new Vector2();
  23314. this.v1 = v1 || new Vector2();
  23315. this.v2 = v2 || new Vector2();
  23316. this.v3 = v3 || new Vector2();
  23317. }
  23318. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  23319. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23320. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23321. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23322. var point = optionalTarget || new Vector2();
  23323. var v0 = this.v0,
  23324. v1 = this.v1,
  23325. v2 = this.v2,
  23326. v3 = this.v3;
  23327. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  23328. return point;
  23329. };
  23330. CubicBezierCurve.prototype.copy = function (source) {
  23331. Curve.prototype.copy.call(this, source);
  23332. this.v0.copy(source.v0);
  23333. this.v1.copy(source.v1);
  23334. this.v2.copy(source.v2);
  23335. this.v3.copy(source.v3);
  23336. return this;
  23337. };
  23338. CubicBezierCurve.prototype.toJSON = function () {
  23339. var data = Curve.prototype.toJSON.call(this);
  23340. data.v0 = this.v0.toArray();
  23341. data.v1 = this.v1.toArray();
  23342. data.v2 = this.v2.toArray();
  23343. data.v3 = this.v3.toArray();
  23344. return data;
  23345. };
  23346. CubicBezierCurve.prototype.fromJSON = function (json) {
  23347. Curve.prototype.fromJSON.call(this, json);
  23348. this.v0.fromArray(json.v0);
  23349. this.v1.fromArray(json.v1);
  23350. this.v2.fromArray(json.v2);
  23351. this.v3.fromArray(json.v3);
  23352. return this;
  23353. };
  23354. function CubicBezierCurve3(v0, v1, v2, v3) {
  23355. Curve.call(this);
  23356. this.type = 'CubicBezierCurve3';
  23357. this.v0 = v0 || new Vector3();
  23358. this.v1 = v1 || new Vector3();
  23359. this.v2 = v2 || new Vector3();
  23360. this.v3 = v3 || new Vector3();
  23361. }
  23362. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  23363. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23364. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23365. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23366. var point = optionalTarget || new Vector3();
  23367. var v0 = this.v0,
  23368. v1 = this.v1,
  23369. v2 = this.v2,
  23370. v3 = this.v3;
  23371. 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));
  23372. return point;
  23373. };
  23374. CubicBezierCurve3.prototype.copy = function (source) {
  23375. Curve.prototype.copy.call(this, source);
  23376. this.v0.copy(source.v0);
  23377. this.v1.copy(source.v1);
  23378. this.v2.copy(source.v2);
  23379. this.v3.copy(source.v3);
  23380. return this;
  23381. };
  23382. CubicBezierCurve3.prototype.toJSON = function () {
  23383. var data = Curve.prototype.toJSON.call(this);
  23384. data.v0 = this.v0.toArray();
  23385. data.v1 = this.v1.toArray();
  23386. data.v2 = this.v2.toArray();
  23387. data.v3 = this.v3.toArray();
  23388. return data;
  23389. };
  23390. CubicBezierCurve3.prototype.fromJSON = function (json) {
  23391. Curve.prototype.fromJSON.call(this, json);
  23392. this.v0.fromArray(json.v0);
  23393. this.v1.fromArray(json.v1);
  23394. this.v2.fromArray(json.v2);
  23395. this.v3.fromArray(json.v3);
  23396. return this;
  23397. };
  23398. function LineCurve(v1, v2) {
  23399. Curve.call(this);
  23400. this.type = 'LineCurve';
  23401. this.v1 = v1 || new Vector2();
  23402. this.v2 = v2 || new Vector2();
  23403. }
  23404. LineCurve.prototype = Object.create(Curve.prototype);
  23405. LineCurve.prototype.constructor = LineCurve;
  23406. LineCurve.prototype.isLineCurve = true;
  23407. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  23408. var point = optionalTarget || new Vector2();
  23409. if (t === 1) {
  23410. point.copy(this.v2);
  23411. } else {
  23412. point.copy(this.v2).sub(this.v1);
  23413. point.multiplyScalar(t).add(this.v1);
  23414. }
  23415. return point;
  23416. }; // Line curve is linear, so we can overwrite default getPointAt
  23417. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  23418. return this.getPoint(u, optionalTarget);
  23419. };
  23420. LineCurve.prototype.getTangent = function ()
  23421. /* t */
  23422. {
  23423. var tangent = this.v2.clone().sub(this.v1);
  23424. return tangent.normalize();
  23425. };
  23426. LineCurve.prototype.copy = function (source) {
  23427. Curve.prototype.copy.call(this, source);
  23428. this.v1.copy(source.v1);
  23429. this.v2.copy(source.v2);
  23430. return this;
  23431. };
  23432. LineCurve.prototype.toJSON = function () {
  23433. var data = Curve.prototype.toJSON.call(this);
  23434. data.v1 = this.v1.toArray();
  23435. data.v2 = this.v2.toArray();
  23436. return data;
  23437. };
  23438. LineCurve.prototype.fromJSON = function (json) {
  23439. Curve.prototype.fromJSON.call(this, json);
  23440. this.v1.fromArray(json.v1);
  23441. this.v2.fromArray(json.v2);
  23442. return this;
  23443. };
  23444. function LineCurve3(v1, v2) {
  23445. Curve.call(this);
  23446. this.type = 'LineCurve3';
  23447. this.v1 = v1 || new Vector3();
  23448. this.v2 = v2 || new Vector3();
  23449. }
  23450. LineCurve3.prototype = Object.create(Curve.prototype);
  23451. LineCurve3.prototype.constructor = LineCurve3;
  23452. LineCurve3.prototype.isLineCurve3 = true;
  23453. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  23454. var point = optionalTarget || new Vector3();
  23455. if (t === 1) {
  23456. point.copy(this.v2);
  23457. } else {
  23458. point.copy(this.v2).sub(this.v1);
  23459. point.multiplyScalar(t).add(this.v1);
  23460. }
  23461. return point;
  23462. }; // Line curve is linear, so we can overwrite default getPointAt
  23463. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  23464. return this.getPoint(u, optionalTarget);
  23465. };
  23466. LineCurve3.prototype.copy = function (source) {
  23467. Curve.prototype.copy.call(this, source);
  23468. this.v1.copy(source.v1);
  23469. this.v2.copy(source.v2);
  23470. return this;
  23471. };
  23472. LineCurve3.prototype.toJSON = function () {
  23473. var data = Curve.prototype.toJSON.call(this);
  23474. data.v1 = this.v1.toArray();
  23475. data.v2 = this.v2.toArray();
  23476. return data;
  23477. };
  23478. LineCurve3.prototype.fromJSON = function (json) {
  23479. Curve.prototype.fromJSON.call(this, json);
  23480. this.v1.fromArray(json.v1);
  23481. this.v2.fromArray(json.v2);
  23482. return this;
  23483. };
  23484. function QuadraticBezierCurve(v0, v1, v2) {
  23485. Curve.call(this);
  23486. this.type = 'QuadraticBezierCurve';
  23487. this.v0 = v0 || new Vector2();
  23488. this.v1 = v1 || new Vector2();
  23489. this.v2 = v2 || new Vector2();
  23490. }
  23491. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  23492. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23493. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23494. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23495. var point = optionalTarget || new Vector2();
  23496. var v0 = this.v0,
  23497. v1 = this.v1,
  23498. v2 = this.v2;
  23499. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  23500. return point;
  23501. };
  23502. QuadraticBezierCurve.prototype.copy = function (source) {
  23503. Curve.prototype.copy.call(this, source);
  23504. this.v0.copy(source.v0);
  23505. this.v1.copy(source.v1);
  23506. this.v2.copy(source.v2);
  23507. return this;
  23508. };
  23509. QuadraticBezierCurve.prototype.toJSON = function () {
  23510. var data = Curve.prototype.toJSON.call(this);
  23511. data.v0 = this.v0.toArray();
  23512. data.v1 = this.v1.toArray();
  23513. data.v2 = this.v2.toArray();
  23514. return data;
  23515. };
  23516. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  23517. Curve.prototype.fromJSON.call(this, json);
  23518. this.v0.fromArray(json.v0);
  23519. this.v1.fromArray(json.v1);
  23520. this.v2.fromArray(json.v2);
  23521. return this;
  23522. };
  23523. function QuadraticBezierCurve3(v0, v1, v2) {
  23524. Curve.call(this);
  23525. this.type = 'QuadraticBezierCurve3';
  23526. this.v0 = v0 || new Vector3();
  23527. this.v1 = v1 || new Vector3();
  23528. this.v2 = v2 || new Vector3();
  23529. }
  23530. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  23531. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23532. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23533. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23534. var point = optionalTarget || new Vector3();
  23535. var v0 = this.v0,
  23536. v1 = this.v1,
  23537. v2 = this.v2;
  23538. 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));
  23539. return point;
  23540. };
  23541. QuadraticBezierCurve3.prototype.copy = function (source) {
  23542. Curve.prototype.copy.call(this, source);
  23543. this.v0.copy(source.v0);
  23544. this.v1.copy(source.v1);
  23545. this.v2.copy(source.v2);
  23546. return this;
  23547. };
  23548. QuadraticBezierCurve3.prototype.toJSON = function () {
  23549. var data = Curve.prototype.toJSON.call(this);
  23550. data.v0 = this.v0.toArray();
  23551. data.v1 = this.v1.toArray();
  23552. data.v2 = this.v2.toArray();
  23553. return data;
  23554. };
  23555. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  23556. Curve.prototype.fromJSON.call(this, json);
  23557. this.v0.fromArray(json.v0);
  23558. this.v1.fromArray(json.v1);
  23559. this.v2.fromArray(json.v2);
  23560. return this;
  23561. };
  23562. function SplineCurve(points
  23563. /* array of Vector2 */
  23564. ) {
  23565. Curve.call(this);
  23566. this.type = 'SplineCurve';
  23567. this.points = points || [];
  23568. }
  23569. SplineCurve.prototype = Object.create(Curve.prototype);
  23570. SplineCurve.prototype.constructor = SplineCurve;
  23571. SplineCurve.prototype.isSplineCurve = true;
  23572. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  23573. var point = optionalTarget || new Vector2();
  23574. var points = this.points;
  23575. var p = (points.length - 1) * t;
  23576. var intPoint = Math.floor(p);
  23577. var weight = p - intPoint;
  23578. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  23579. var p1 = points[intPoint];
  23580. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  23581. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  23582. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  23583. return point;
  23584. };
  23585. SplineCurve.prototype.copy = function (source) {
  23586. Curve.prototype.copy.call(this, source);
  23587. this.points = [];
  23588. for (var i = 0, l = source.points.length; i < l; i++) {
  23589. var point = source.points[i];
  23590. this.points.push(point.clone());
  23591. }
  23592. return this;
  23593. };
  23594. SplineCurve.prototype.toJSON = function () {
  23595. var data = Curve.prototype.toJSON.call(this);
  23596. data.points = [];
  23597. for (var i = 0, l = this.points.length; i < l; i++) {
  23598. var point = this.points[i];
  23599. data.points.push(point.toArray());
  23600. }
  23601. return data;
  23602. };
  23603. SplineCurve.prototype.fromJSON = function (json) {
  23604. Curve.prototype.fromJSON.call(this, json);
  23605. this.points = [];
  23606. for (var i = 0, l = json.points.length; i < l; i++) {
  23607. var point = json.points[i];
  23608. this.points.push(new Vector2().fromArray(point));
  23609. }
  23610. return this;
  23611. };
  23612. var Curves =
  23613. /*#__PURE__*/
  23614. Object.freeze({
  23615. ArcCurve: ArcCurve,
  23616. CatmullRomCurve3: CatmullRomCurve3,
  23617. CubicBezierCurve: CubicBezierCurve,
  23618. CubicBezierCurve3: CubicBezierCurve3,
  23619. EllipseCurve: EllipseCurve,
  23620. LineCurve: LineCurve,
  23621. LineCurve3: LineCurve3,
  23622. QuadraticBezierCurve: QuadraticBezierCurve,
  23623. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23624. SplineCurve: SplineCurve
  23625. });
  23626. /**
  23627. * @author zz85 / http://www.lab4games.net/zz85/blog
  23628. *
  23629. **/
  23630. /**************************************************************
  23631. * Curved Path - a curve path is simply a array of connected
  23632. * curves, but retains the api of a curve
  23633. **************************************************************/
  23634. function CurvePath() {
  23635. Curve.call(this);
  23636. this.type = 'CurvePath';
  23637. this.curves = [];
  23638. this.autoClose = false; // Automatically closes the path
  23639. }
  23640. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  23641. constructor: CurvePath,
  23642. add: function (curve) {
  23643. this.curves.push(curve);
  23644. },
  23645. closePath: function () {
  23646. // Add a line curve if start and end of lines are not connected
  23647. var startPoint = this.curves[0].getPoint(0);
  23648. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  23649. if (!startPoint.equals(endPoint)) {
  23650. this.curves.push(new LineCurve(endPoint, startPoint));
  23651. }
  23652. },
  23653. // To get accurate point with reference to
  23654. // entire path distance at time t,
  23655. // following has to be done:
  23656. // 1. Length of each sub path have to be known
  23657. // 2. Locate and identify type of curve
  23658. // 3. Get t for the curve
  23659. // 4. Return curve.getPointAt(t')
  23660. getPoint: function (t) {
  23661. var d = t * this.getLength();
  23662. var curveLengths = this.getCurveLengths();
  23663. var i = 0; // To think about boundaries points.
  23664. while (i < curveLengths.length) {
  23665. if (curveLengths[i] >= d) {
  23666. var diff = curveLengths[i] - d;
  23667. var curve = this.curves[i];
  23668. var segmentLength = curve.getLength();
  23669. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23670. return curve.getPointAt(u);
  23671. }
  23672. i++;
  23673. }
  23674. return null; // loop where sum != 0, sum > d , sum+1 <d
  23675. },
  23676. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23677. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23678. // getPoint() depends on getLength
  23679. getLength: function () {
  23680. var lens = this.getCurveLengths();
  23681. return lens[lens.length - 1];
  23682. },
  23683. // cacheLengths must be recalculated.
  23684. updateArcLengths: function () {
  23685. this.needsUpdate = true;
  23686. this.cacheLengths = null;
  23687. this.getCurveLengths();
  23688. },
  23689. // Compute lengths and cache them
  23690. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23691. getCurveLengths: function () {
  23692. // We use cache values if curves and cache array are same length
  23693. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  23694. return this.cacheLengths;
  23695. } // Get length of sub-curve
  23696. // Push sums into cached array
  23697. var lengths = [],
  23698. sums = 0;
  23699. for (var i = 0, l = this.curves.length; i < l; i++) {
  23700. sums += this.curves[i].getLength();
  23701. lengths.push(sums);
  23702. }
  23703. this.cacheLengths = lengths;
  23704. return lengths;
  23705. },
  23706. getSpacedPoints: function (divisions) {
  23707. if (divisions === undefined) divisions = 40;
  23708. var points = [];
  23709. for (var i = 0; i <= divisions; i++) {
  23710. points.push(this.getPoint(i / divisions));
  23711. }
  23712. if (this.autoClose) {
  23713. points.push(points[0]);
  23714. }
  23715. return points;
  23716. },
  23717. getPoints: function (divisions) {
  23718. divisions = divisions || 12;
  23719. var points = [],
  23720. last;
  23721. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  23722. var curve = curves[i];
  23723. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  23724. var pts = curve.getPoints(resolution);
  23725. for (var j = 0; j < pts.length; j++) {
  23726. var point = pts[j];
  23727. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  23728. points.push(point);
  23729. last = point;
  23730. }
  23731. }
  23732. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  23733. points.push(points[0]);
  23734. }
  23735. return points;
  23736. },
  23737. copy: function (source) {
  23738. Curve.prototype.copy.call(this, source);
  23739. this.curves = [];
  23740. for (var i = 0, l = source.curves.length; i < l; i++) {
  23741. var curve = source.curves[i];
  23742. this.curves.push(curve.clone());
  23743. }
  23744. this.autoClose = source.autoClose;
  23745. return this;
  23746. },
  23747. toJSON: function () {
  23748. var data = Curve.prototype.toJSON.call(this);
  23749. data.autoClose = this.autoClose;
  23750. data.curves = [];
  23751. for (var i = 0, l = this.curves.length; i < l; i++) {
  23752. var curve = this.curves[i];
  23753. data.curves.push(curve.toJSON());
  23754. }
  23755. return data;
  23756. },
  23757. fromJSON: function (json) {
  23758. Curve.prototype.fromJSON.call(this, json);
  23759. this.autoClose = json.autoClose;
  23760. this.curves = [];
  23761. for (var i = 0, l = json.curves.length; i < l; i++) {
  23762. var curve = json.curves[i];
  23763. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23764. }
  23765. return this;
  23766. }
  23767. });
  23768. /**
  23769. * @author zz85 / http://www.lab4games.net/zz85/blog
  23770. * Creates free form 2d path using series of points, lines or curves.
  23771. **/
  23772. function Path(points) {
  23773. CurvePath.call(this);
  23774. this.type = 'Path';
  23775. this.currentPoint = new Vector2();
  23776. if (points) {
  23777. this.setFromPoints(points);
  23778. }
  23779. }
  23780. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23781. constructor: Path,
  23782. setFromPoints: function (points) {
  23783. this.moveTo(points[0].x, points[0].y);
  23784. for (var i = 1, l = points.length; i < l; i++) {
  23785. this.lineTo(points[i].x, points[i].y);
  23786. }
  23787. },
  23788. moveTo: function (x, y) {
  23789. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23790. },
  23791. lineTo: function (x, y) {
  23792. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23793. this.curves.push(curve);
  23794. this.currentPoint.set(x, y);
  23795. },
  23796. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23797. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23798. this.curves.push(curve);
  23799. this.currentPoint.set(aX, aY);
  23800. },
  23801. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23802. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23803. this.curves.push(curve);
  23804. this.currentPoint.set(aX, aY);
  23805. },
  23806. splineThru: function (pts
  23807. /*Array of Vector*/
  23808. ) {
  23809. var npts = [this.currentPoint.clone()].concat(pts);
  23810. var curve = new SplineCurve(npts);
  23811. this.curves.push(curve);
  23812. this.currentPoint.copy(pts[pts.length - 1]);
  23813. },
  23814. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23815. var x0 = this.currentPoint.x;
  23816. var y0 = this.currentPoint.y;
  23817. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23818. },
  23819. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23820. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23821. },
  23822. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23823. var x0 = this.currentPoint.x;
  23824. var y0 = this.currentPoint.y;
  23825. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23826. },
  23827. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23828. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23829. if (this.curves.length > 0) {
  23830. // if a previous curve is present, attempt to join
  23831. var firstPoint = curve.getPoint(0);
  23832. if (!firstPoint.equals(this.currentPoint)) {
  23833. this.lineTo(firstPoint.x, firstPoint.y);
  23834. }
  23835. }
  23836. this.curves.push(curve);
  23837. var lastPoint = curve.getPoint(1);
  23838. this.currentPoint.copy(lastPoint);
  23839. },
  23840. copy: function (source) {
  23841. CurvePath.prototype.copy.call(this, source);
  23842. this.currentPoint.copy(source.currentPoint);
  23843. return this;
  23844. },
  23845. toJSON: function () {
  23846. var data = CurvePath.prototype.toJSON.call(this);
  23847. data.currentPoint = this.currentPoint.toArray();
  23848. return data;
  23849. },
  23850. fromJSON: function (json) {
  23851. CurvePath.prototype.fromJSON.call(this, json);
  23852. this.currentPoint.fromArray(json.currentPoint);
  23853. return this;
  23854. }
  23855. });
  23856. /**
  23857. * @author zz85 / http://www.lab4games.net/zz85/blog
  23858. * Defines a 2d shape plane using paths.
  23859. **/
  23860. // STEP 1 Create a path.
  23861. // STEP 2 Turn path into shape.
  23862. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  23863. // STEP 3a - Extract points from each shape, turn to vertices
  23864. // STEP 3b - Triangulate each shape, add faces.
  23865. function Shape(points) {
  23866. Path.call(this, points);
  23867. this.uuid = _Math.generateUUID();
  23868. this.type = 'Shape';
  23869. this.holes = [];
  23870. }
  23871. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23872. constructor: Shape,
  23873. getPointsHoles: function (divisions) {
  23874. var holesPts = [];
  23875. for (var i = 0, l = this.holes.length; i < l; i++) {
  23876. holesPts[i] = this.holes[i].getPoints(divisions);
  23877. }
  23878. return holesPts;
  23879. },
  23880. // get points of shape and holes (keypoints based on segments parameter)
  23881. extractPoints: function (divisions) {
  23882. return {
  23883. shape: this.getPoints(divisions),
  23884. holes: this.getPointsHoles(divisions)
  23885. };
  23886. },
  23887. copy: function (source) {
  23888. Path.prototype.copy.call(this, source);
  23889. this.holes = [];
  23890. for (var i = 0, l = source.holes.length; i < l; i++) {
  23891. var hole = source.holes[i];
  23892. this.holes.push(hole.clone());
  23893. }
  23894. return this;
  23895. },
  23896. toJSON: function () {
  23897. var data = Path.prototype.toJSON.call(this);
  23898. data.uuid = this.uuid;
  23899. data.holes = [];
  23900. for (var i = 0, l = this.holes.length; i < l; i++) {
  23901. var hole = this.holes[i];
  23902. data.holes.push(hole.toJSON());
  23903. }
  23904. return data;
  23905. },
  23906. fromJSON: function (json) {
  23907. Path.prototype.fromJSON.call(this, json);
  23908. this.uuid = json.uuid;
  23909. this.holes = [];
  23910. for (var i = 0, l = json.holes.length; i < l; i++) {
  23911. var hole = json.holes[i];
  23912. this.holes.push(new Path().fromJSON(hole));
  23913. }
  23914. return this;
  23915. }
  23916. });
  23917. /**
  23918. * @author mrdoob / http://mrdoob.com/
  23919. * @author alteredq / http://alteredqualia.com/
  23920. */
  23921. function Light(color, intensity) {
  23922. Object3D.call(this);
  23923. this.type = 'Light';
  23924. this.color = new Color(color);
  23925. this.intensity = intensity !== undefined ? intensity : 1;
  23926. this.receiveShadow = undefined;
  23927. }
  23928. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23929. constructor: Light,
  23930. isLight: true,
  23931. copy: function (source) {
  23932. Object3D.prototype.copy.call(this, source);
  23933. this.color.copy(source.color);
  23934. this.intensity = source.intensity;
  23935. return this;
  23936. },
  23937. toJSON: function (meta) {
  23938. var data = Object3D.prototype.toJSON.call(this, meta);
  23939. data.object.color = this.color.getHex();
  23940. data.object.intensity = this.intensity;
  23941. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23942. if (this.distance !== undefined) data.object.distance = this.distance;
  23943. if (this.angle !== undefined) data.object.angle = this.angle;
  23944. if (this.decay !== undefined) data.object.decay = this.decay;
  23945. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23946. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23947. return data;
  23948. }
  23949. });
  23950. /**
  23951. * @author alteredq / http://alteredqualia.com/
  23952. */
  23953. function HemisphereLight(skyColor, groundColor, intensity) {
  23954. Light.call(this, skyColor, intensity);
  23955. this.type = 'HemisphereLight';
  23956. this.castShadow = undefined;
  23957. this.position.copy(Object3D.DefaultUp);
  23958. this.updateMatrix();
  23959. this.groundColor = new Color(groundColor);
  23960. }
  23961. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23962. constructor: HemisphereLight,
  23963. isHemisphereLight: true,
  23964. copy: function (source) {
  23965. Light.prototype.copy.call(this, source);
  23966. this.groundColor.copy(source.groundColor);
  23967. return this;
  23968. }
  23969. });
  23970. /**
  23971. * @author mrdoob / http://mrdoob.com/
  23972. */
  23973. function LightShadow(camera) {
  23974. this.camera = camera;
  23975. this.bias = 0;
  23976. this.radius = 1;
  23977. this.mapSize = new Vector2(512, 512);
  23978. this.map = null;
  23979. this.mapPass = null;
  23980. this.matrix = new Matrix4();
  23981. this._frustum = new Frustum();
  23982. this._frameExtents = new Vector2(1, 1);
  23983. this._viewportCount = 1;
  23984. this._viewports = [new Vector4(0, 0, 1, 1)];
  23985. }
  23986. Object.assign(LightShadow.prototype, {
  23987. _projScreenMatrix: new Matrix4(),
  23988. _lightPositionWorld: new Vector3(),
  23989. _lookTarget: new Vector3(),
  23990. getViewportCount: function () {
  23991. return this._viewportCount;
  23992. },
  23993. getFrustum: function () {
  23994. return this._frustum;
  23995. },
  23996. updateMatrices: function (light) {
  23997. var shadowCamera = this.camera,
  23998. shadowMatrix = this.matrix,
  23999. projScreenMatrix = this._projScreenMatrix,
  24000. lookTarget = this._lookTarget,
  24001. lightPositionWorld = this._lightPositionWorld;
  24002. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  24003. shadowCamera.position.copy(lightPositionWorld);
  24004. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  24005. shadowCamera.lookAt(lookTarget);
  24006. shadowCamera.updateMatrixWorld();
  24007. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  24008. this._frustum.setFromMatrix(projScreenMatrix);
  24009. 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);
  24010. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  24011. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  24012. },
  24013. getViewport: function (viewportIndex) {
  24014. return this._viewports[viewportIndex];
  24015. },
  24016. getFrameExtents: function () {
  24017. return this._frameExtents;
  24018. },
  24019. copy: function (source) {
  24020. this.camera = source.camera.clone();
  24021. this.bias = source.bias;
  24022. this.radius = source.radius;
  24023. this.mapSize.copy(source.mapSize);
  24024. return this;
  24025. },
  24026. clone: function () {
  24027. return new this.constructor().copy(this);
  24028. },
  24029. toJSON: function () {
  24030. var object = {};
  24031. if (this.bias !== 0) object.bias = this.bias;
  24032. if (this.radius !== 1) object.radius = this.radius;
  24033. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  24034. object.camera = this.camera.toJSON(false).object;
  24035. delete object.camera.matrix;
  24036. return object;
  24037. }
  24038. });
  24039. /**
  24040. * @author mrdoob / http://mrdoob.com/
  24041. */
  24042. function SpotLightShadow() {
  24043. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  24044. }
  24045. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24046. constructor: SpotLightShadow,
  24047. isSpotLightShadow: true,
  24048. updateMatrices: function (light, viewCamera, viewportIndex) {
  24049. var camera = this.camera;
  24050. var fov = _Math.RAD2DEG * 2 * light.angle;
  24051. var aspect = this.mapSize.width / this.mapSize.height;
  24052. var far = light.distance || camera.far;
  24053. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  24054. camera.fov = fov;
  24055. camera.aspect = aspect;
  24056. camera.far = far;
  24057. camera.updateProjectionMatrix();
  24058. }
  24059. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24060. }
  24061. });
  24062. /**
  24063. * @author alteredq / http://alteredqualia.com/
  24064. */
  24065. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  24066. Light.call(this, color, intensity);
  24067. this.type = 'SpotLight';
  24068. this.position.copy(Object3D.DefaultUp);
  24069. this.updateMatrix();
  24070. this.target = new Object3D();
  24071. Object.defineProperty(this, 'power', {
  24072. get: function () {
  24073. // intensity = power per solid angle.
  24074. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24075. return this.intensity * Math.PI;
  24076. },
  24077. set: function (power) {
  24078. // intensity = power per solid angle.
  24079. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24080. this.intensity = power / Math.PI;
  24081. }
  24082. });
  24083. this.distance = distance !== undefined ? distance : 0;
  24084. this.angle = angle !== undefined ? angle : Math.PI / 3;
  24085. this.penumbra = penumbra !== undefined ? penumbra : 0;
  24086. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24087. this.shadow = new SpotLightShadow();
  24088. }
  24089. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  24090. constructor: SpotLight,
  24091. isSpotLight: true,
  24092. copy: function (source) {
  24093. Light.prototype.copy.call(this, source);
  24094. this.distance = source.distance;
  24095. this.angle = source.angle;
  24096. this.penumbra = source.penumbra;
  24097. this.decay = source.decay;
  24098. this.target = source.target.clone();
  24099. this.shadow = source.shadow.clone();
  24100. return this;
  24101. }
  24102. });
  24103. function PointLightShadow() {
  24104. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  24105. this._frameExtents = new Vector2(4, 2);
  24106. this._viewportCount = 6;
  24107. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  24108. // following orientation:
  24109. //
  24110. // xzXZ
  24111. // y Y
  24112. //
  24113. // X - Positive x direction
  24114. // x - Negative x direction
  24115. // Y - Positive y direction
  24116. // y - Negative y direction
  24117. // Z - Positive z direction
  24118. // z - Negative z direction
  24119. // positive X
  24120. new Vector4(2, 1, 1, 1), // negative X
  24121. new Vector4(0, 1, 1, 1), // positive Z
  24122. new Vector4(3, 1, 1, 1), // negative Z
  24123. new Vector4(1, 1, 1, 1), // positive Y
  24124. new Vector4(3, 0, 1, 1), // negative Y
  24125. new Vector4(1, 0, 1, 1)];
  24126. 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)];
  24127. 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)];
  24128. }
  24129. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24130. constructor: PointLightShadow,
  24131. isPointLightShadow: true,
  24132. updateMatrices: function (light, viewCamera, viewportIndex) {
  24133. var camera = this.camera,
  24134. shadowMatrix = this.matrix,
  24135. lightPositionWorld = this._lightPositionWorld,
  24136. lookTarget = this._lookTarget,
  24137. projScreenMatrix = this._projScreenMatrix;
  24138. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  24139. camera.position.copy(lightPositionWorld);
  24140. lookTarget.copy(camera.position);
  24141. lookTarget.add(this._cubeDirections[viewportIndex]);
  24142. camera.up.copy(this._cubeUps[viewportIndex]);
  24143. camera.lookAt(lookTarget);
  24144. camera.updateMatrixWorld();
  24145. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  24146. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  24147. this._frustum.setFromMatrix(projScreenMatrix);
  24148. }
  24149. });
  24150. /**
  24151. * @author mrdoob / http://mrdoob.com/
  24152. */
  24153. function PointLight(color, intensity, distance, decay) {
  24154. Light.call(this, color, intensity);
  24155. this.type = 'PointLight';
  24156. Object.defineProperty(this, 'power', {
  24157. get: function () {
  24158. // intensity = power per solid angle.
  24159. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24160. return this.intensity * 4 * Math.PI;
  24161. },
  24162. set: function (power) {
  24163. // intensity = power per solid angle.
  24164. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24165. this.intensity = power / (4 * Math.PI);
  24166. }
  24167. });
  24168. this.distance = distance !== undefined ? distance : 0;
  24169. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24170. this.shadow = new PointLightShadow();
  24171. }
  24172. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  24173. constructor: PointLight,
  24174. isPointLight: true,
  24175. copy: function (source) {
  24176. Light.prototype.copy.call(this, source);
  24177. this.distance = source.distance;
  24178. this.decay = source.decay;
  24179. this.shadow = source.shadow.clone();
  24180. return this;
  24181. }
  24182. });
  24183. /**
  24184. * @author alteredq / http://alteredqualia.com/
  24185. * @author arose / http://github.com/arose
  24186. */
  24187. function OrthographicCamera(left, right, top, bottom, near, far) {
  24188. Camera.call(this);
  24189. this.type = 'OrthographicCamera';
  24190. this.zoom = 1;
  24191. this.view = null;
  24192. this.left = left !== undefined ? left : -1;
  24193. this.right = right !== undefined ? right : 1;
  24194. this.top = top !== undefined ? top : 1;
  24195. this.bottom = bottom !== undefined ? bottom : -1;
  24196. this.near = near !== undefined ? near : 0.1;
  24197. this.far = far !== undefined ? far : 2000;
  24198. this.updateProjectionMatrix();
  24199. }
  24200. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  24201. constructor: OrthographicCamera,
  24202. isOrthographicCamera: true,
  24203. copy: function (source, recursive) {
  24204. Camera.prototype.copy.call(this, source, recursive);
  24205. this.left = source.left;
  24206. this.right = source.right;
  24207. this.top = source.top;
  24208. this.bottom = source.bottom;
  24209. this.near = source.near;
  24210. this.far = source.far;
  24211. this.zoom = source.zoom;
  24212. this.view = source.view === null ? null : Object.assign({}, source.view);
  24213. return this;
  24214. },
  24215. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  24216. if (this.view === null) {
  24217. this.view = {
  24218. enabled: true,
  24219. fullWidth: 1,
  24220. fullHeight: 1,
  24221. offsetX: 0,
  24222. offsetY: 0,
  24223. width: 1,
  24224. height: 1
  24225. };
  24226. }
  24227. this.view.enabled = true;
  24228. this.view.fullWidth = fullWidth;
  24229. this.view.fullHeight = fullHeight;
  24230. this.view.offsetX = x;
  24231. this.view.offsetY = y;
  24232. this.view.width = width;
  24233. this.view.height = height;
  24234. this.updateProjectionMatrix();
  24235. },
  24236. clearViewOffset: function () {
  24237. if (this.view !== null) {
  24238. this.view.enabled = false;
  24239. }
  24240. this.updateProjectionMatrix();
  24241. },
  24242. updateProjectionMatrix: function () {
  24243. var dx = (this.right - this.left) / (2 * this.zoom);
  24244. var dy = (this.top - this.bottom) / (2 * this.zoom);
  24245. var cx = (this.right + this.left) / 2;
  24246. var cy = (this.top + this.bottom) / 2;
  24247. var left = cx - dx;
  24248. var right = cx + dx;
  24249. var top = cy + dy;
  24250. var bottom = cy - dy;
  24251. if (this.view !== null && this.view.enabled) {
  24252. var zoomW = this.zoom / (this.view.width / this.view.fullWidth);
  24253. var zoomH = this.zoom / (this.view.height / this.view.fullHeight);
  24254. var scaleW = (this.right - this.left) / this.view.width;
  24255. var scaleH = (this.top - this.bottom) / this.view.height;
  24256. left += scaleW * (this.view.offsetX / zoomW);
  24257. right = left + scaleW * (this.view.width / zoomW);
  24258. top -= scaleH * (this.view.offsetY / zoomH);
  24259. bottom = top - scaleH * (this.view.height / zoomH);
  24260. }
  24261. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  24262. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  24263. },
  24264. toJSON: function (meta) {
  24265. var data = Object3D.prototype.toJSON.call(this, meta);
  24266. data.object.zoom = this.zoom;
  24267. data.object.left = this.left;
  24268. data.object.right = this.right;
  24269. data.object.top = this.top;
  24270. data.object.bottom = this.bottom;
  24271. data.object.near = this.near;
  24272. data.object.far = this.far;
  24273. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  24274. return data;
  24275. }
  24276. });
  24277. /**
  24278. * @author mrdoob / http://mrdoob.com/
  24279. */
  24280. function DirectionalLightShadow() {
  24281. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  24282. }
  24283. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24284. constructor: DirectionalLightShadow,
  24285. isDirectionalLightShadow: true,
  24286. updateMatrices: function (light, viewCamera, viewportIndex) {
  24287. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24288. }
  24289. });
  24290. /**
  24291. * @author mrdoob / http://mrdoob.com/
  24292. * @author alteredq / http://alteredqualia.com/
  24293. */
  24294. function DirectionalLight(color, intensity) {
  24295. Light.call(this, color, intensity);
  24296. this.type = 'DirectionalLight';
  24297. this.position.copy(Object3D.DefaultUp);
  24298. this.updateMatrix();
  24299. this.target = new Object3D();
  24300. this.shadow = new DirectionalLightShadow();
  24301. }
  24302. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  24303. constructor: DirectionalLight,
  24304. isDirectionalLight: true,
  24305. copy: function (source) {
  24306. Light.prototype.copy.call(this, source);
  24307. this.target = source.target.clone();
  24308. this.shadow = source.shadow.clone();
  24309. return this;
  24310. }
  24311. });
  24312. /**
  24313. * @author mrdoob / http://mrdoob.com/
  24314. */
  24315. function AmbientLight(color, intensity) {
  24316. Light.call(this, color, intensity);
  24317. this.type = 'AmbientLight';
  24318. this.castShadow = undefined;
  24319. }
  24320. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  24321. constructor: AmbientLight,
  24322. isAmbientLight: true
  24323. });
  24324. /**
  24325. * @author abelnation / http://github.com/abelnation
  24326. */
  24327. function RectAreaLight(color, intensity, width, height) {
  24328. Light.call(this, color, intensity);
  24329. this.type = 'RectAreaLight';
  24330. this.width = width !== undefined ? width : 10;
  24331. this.height = height !== undefined ? height : 10;
  24332. }
  24333. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  24334. constructor: RectAreaLight,
  24335. isRectAreaLight: true,
  24336. copy: function (source) {
  24337. Light.prototype.copy.call(this, source);
  24338. this.width = source.width;
  24339. this.height = source.height;
  24340. return this;
  24341. },
  24342. toJSON: function (meta) {
  24343. var data = Light.prototype.toJSON.call(this, meta);
  24344. data.object.width = this.width;
  24345. data.object.height = this.height;
  24346. return data;
  24347. }
  24348. });
  24349. /**
  24350. * @author mrdoob / http://mrdoob.com/
  24351. */
  24352. function MaterialLoader(manager) {
  24353. Loader.call(this, manager);
  24354. this.textures = {};
  24355. }
  24356. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24357. constructor: MaterialLoader,
  24358. load: function (url, onLoad, onProgress, onError) {
  24359. var scope = this;
  24360. var loader = new FileLoader(scope.manager);
  24361. loader.setPath(scope.path);
  24362. loader.load(url, function (text) {
  24363. onLoad(scope.parse(JSON.parse(text)));
  24364. }, onProgress, onError);
  24365. },
  24366. parse: function (json) {
  24367. var textures = this.textures;
  24368. function getTexture(name) {
  24369. if (textures[name] === undefined) {
  24370. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24371. }
  24372. return textures[name];
  24373. }
  24374. var material = new Materials[json.type]();
  24375. if (json.uuid !== undefined) material.uuid = json.uuid;
  24376. if (json.name !== undefined) material.name = json.name;
  24377. if (json.color !== undefined) material.color.setHex(json.color);
  24378. if (json.roughness !== undefined) material.roughness = json.roughness;
  24379. if (json.metalness !== undefined) material.metalness = json.metalness;
  24380. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  24381. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  24382. if (json.specular !== undefined) material.specular.setHex(json.specular);
  24383. if (json.shininess !== undefined) material.shininess = json.shininess;
  24384. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24385. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24386. if (json.vertexColors !== undefined) material.vertexColors = json.vertexColors;
  24387. if (json.fog !== undefined) material.fog = json.fog;
  24388. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24389. if (json.blending !== undefined) material.blending = json.blending;
  24390. if (json.combine !== undefined) material.combine = json.combine;
  24391. if (json.side !== undefined) material.side = json.side;
  24392. if (json.opacity !== undefined) material.opacity = json.opacity;
  24393. if (json.transparent !== undefined) material.transparent = json.transparent;
  24394. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24395. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24396. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24397. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24398. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24399. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24400. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24401. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24402. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24403. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24404. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24405. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24406. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24407. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24408. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24409. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24410. if (json.rotation !== undefined) material.rotation = json.rotation;
  24411. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24412. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24413. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24414. if (json.scale !== undefined) material.scale = json.scale;
  24415. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24416. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24417. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24418. if (json.skinning !== undefined) material.skinning = json.skinning;
  24419. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  24420. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  24421. if (json.dithering !== undefined) material.dithering = json.dithering;
  24422. if (json.visible !== undefined) material.visible = json.visible;
  24423. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24424. if (json.userData !== undefined) material.userData = json.userData; // Shader Material
  24425. if (json.uniforms !== undefined) {
  24426. for (var name in json.uniforms) {
  24427. var uniform = json.uniforms[name];
  24428. material.uniforms[name] = {};
  24429. switch (uniform.type) {
  24430. case 't':
  24431. material.uniforms[name].value = getTexture(uniform.value);
  24432. break;
  24433. case 'c':
  24434. material.uniforms[name].value = new Color().setHex(uniform.value);
  24435. break;
  24436. case 'v2':
  24437. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24438. break;
  24439. case 'v3':
  24440. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24441. break;
  24442. case 'v4':
  24443. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24444. break;
  24445. case 'm3':
  24446. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24447. case 'm4':
  24448. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24449. break;
  24450. default:
  24451. material.uniforms[name].value = uniform.value;
  24452. }
  24453. }
  24454. }
  24455. if (json.defines !== undefined) material.defines = json.defines;
  24456. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24457. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24458. if (json.extensions !== undefined) {
  24459. for (var key in json.extensions) {
  24460. material.extensions[key] = json.extensions[key];
  24461. }
  24462. } // Deprecated
  24463. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24464. // for PointsMaterial
  24465. if (json.size !== undefined) material.size = json.size;
  24466. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24467. if (json.map !== undefined) material.map = getTexture(json.map);
  24468. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24469. if (json.alphaMap !== undefined) {
  24470. material.alphaMap = getTexture(json.alphaMap);
  24471. material.transparent = true;
  24472. }
  24473. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24474. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24475. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24476. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24477. if (json.normalScale !== undefined) {
  24478. var normalScale = json.normalScale;
  24479. if (Array.isArray(normalScale) === false) {
  24480. // Blender exporter used to export a scalar. See #7459
  24481. normalScale = [normalScale, normalScale];
  24482. }
  24483. material.normalScale = new Vector2().fromArray(normalScale);
  24484. }
  24485. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24486. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24487. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24488. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24489. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24490. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24491. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24492. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24493. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24494. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24495. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24496. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24497. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24498. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24499. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24500. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24501. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24502. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24503. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24504. return material;
  24505. },
  24506. setTextures: function (value) {
  24507. this.textures = value;
  24508. return this;
  24509. }
  24510. });
  24511. /**
  24512. * @author Don McCurdy / https://www.donmccurdy.com
  24513. */
  24514. var LoaderUtils = {
  24515. decodeText: function (array) {
  24516. if (typeof TextDecoder !== 'undefined') {
  24517. return new TextDecoder().decode(array);
  24518. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24519. // throws a "maximum call stack size exceeded" error for large arrays.
  24520. var s = '';
  24521. for (var i = 0, il = array.length; i < il; i++) {
  24522. // Implicitly assumes little-endian.
  24523. s += String.fromCharCode(array[i]);
  24524. }
  24525. try {
  24526. // merges multi-byte utf-8 characters.
  24527. return decodeURIComponent(escape(s));
  24528. } catch (e) {
  24529. // see #16358
  24530. return s;
  24531. }
  24532. },
  24533. extractUrlBase: function (url) {
  24534. var index = url.lastIndexOf('/');
  24535. if (index === -1) return './';
  24536. return url.substr(0, index + 1);
  24537. }
  24538. };
  24539. /**
  24540. * @author benaadams / https://twitter.com/ben_a_adams
  24541. */
  24542. exports.LoaderUtils = LoaderUtils;
  24543. function InstancedBufferGeometry() {
  24544. BufferGeometry.call(this);
  24545. this.type = 'InstancedBufferGeometry';
  24546. this.maxInstancedCount = undefined;
  24547. }
  24548. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  24549. constructor: InstancedBufferGeometry,
  24550. isInstancedBufferGeometry: true,
  24551. copy: function (source) {
  24552. BufferGeometry.prototype.copy.call(this, source);
  24553. this.maxInstancedCount = source.maxInstancedCount;
  24554. return this;
  24555. },
  24556. clone: function () {
  24557. return new this.constructor().copy(this);
  24558. },
  24559. toJSON: function () {
  24560. var data = BufferGeometry.prototype.toJSON.call(this);
  24561. data.maxInstancedCount = this.maxInstancedCount;
  24562. data.isInstancedBufferGeometry = true;
  24563. return data;
  24564. }
  24565. });
  24566. /**
  24567. * @author benaadams / https://twitter.com/ben_a_adams
  24568. */
  24569. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  24570. if (typeof normalized === 'number') {
  24571. meshPerAttribute = normalized;
  24572. normalized = false;
  24573. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  24574. }
  24575. BufferAttribute.call(this, array, itemSize, normalized);
  24576. this.meshPerAttribute = meshPerAttribute || 1;
  24577. }
  24578. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  24579. constructor: InstancedBufferAttribute,
  24580. isInstancedBufferAttribute: true,
  24581. copy: function (source) {
  24582. BufferAttribute.prototype.copy.call(this, source);
  24583. this.meshPerAttribute = source.meshPerAttribute;
  24584. return this;
  24585. },
  24586. toJSON: function () {
  24587. var data = BufferAttribute.prototype.toJSON.call(this);
  24588. data.meshPerAttribute = this.meshPerAttribute;
  24589. data.isInstancedBufferAttribute = true;
  24590. return data;
  24591. }
  24592. });
  24593. /**
  24594. * @author mrdoob / http://mrdoob.com/
  24595. */
  24596. function BufferGeometryLoader(manager) {
  24597. Loader.call(this, manager);
  24598. }
  24599. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24600. constructor: BufferGeometryLoader,
  24601. load: function (url, onLoad, onProgress, onError) {
  24602. var scope = this;
  24603. var loader = new FileLoader(scope.manager);
  24604. loader.setPath(scope.path);
  24605. loader.load(url, function (text) {
  24606. onLoad(scope.parse(JSON.parse(text)));
  24607. }, onProgress, onError);
  24608. },
  24609. parse: function (json) {
  24610. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24611. var index = json.data.index;
  24612. if (index !== undefined) {
  24613. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  24614. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24615. }
  24616. var attributes = json.data.attributes;
  24617. for (var key in attributes) {
  24618. var attribute = attributes[key];
  24619. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24620. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24621. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24622. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24623. geometry.addAttribute(key, bufferAttribute);
  24624. }
  24625. var morphAttributes = json.data.morphAttributes;
  24626. if (morphAttributes) {
  24627. for (var key in morphAttributes) {
  24628. var attributeArray = morphAttributes[key];
  24629. var array = [];
  24630. for (var i = 0, il = attributeArray.length; i < il; i++) {
  24631. var attribute = attributeArray[i];
  24632. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24633. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24634. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24635. array.push(bufferAttribute);
  24636. }
  24637. geometry.morphAttributes[key] = array;
  24638. }
  24639. }
  24640. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24641. if (groups !== undefined) {
  24642. for (var i = 0, n = groups.length; i !== n; ++i) {
  24643. var group = groups[i];
  24644. geometry.addGroup(group.start, group.count, group.materialIndex);
  24645. }
  24646. }
  24647. var boundingSphere = json.data.boundingSphere;
  24648. if (boundingSphere !== undefined) {
  24649. var center = new Vector3();
  24650. if (boundingSphere.center !== undefined) {
  24651. center.fromArray(boundingSphere.center);
  24652. }
  24653. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24654. }
  24655. if (json.name) geometry.name = json.name;
  24656. if (json.userData) geometry.userData = json.userData;
  24657. return geometry;
  24658. }
  24659. });
  24660. var TYPED_ARRAYS = {
  24661. Int8Array: Int8Array,
  24662. Uint8Array: Uint8Array,
  24663. // Workaround for IE11 pre KB2929437. See #11440
  24664. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  24665. Int16Array: Int16Array,
  24666. Uint16Array: Uint16Array,
  24667. Int32Array: Int32Array,
  24668. Uint32Array: Uint32Array,
  24669. Float32Array: Float32Array,
  24670. Float64Array: Float64Array
  24671. };
  24672. /**
  24673. * @author mrdoob / http://mrdoob.com/
  24674. */
  24675. function ObjectLoader(manager) {
  24676. Loader.call(this, manager);
  24677. }
  24678. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24679. constructor: ObjectLoader,
  24680. load: function (url, onLoad, onProgress, onError) {
  24681. var scope = this;
  24682. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24683. this.resourcePath = this.resourcePath || path;
  24684. var loader = new FileLoader(scope.manager);
  24685. loader.setPath(this.path);
  24686. loader.load(url, function (text) {
  24687. var json = null;
  24688. try {
  24689. json = JSON.parse(text);
  24690. } catch (error) {
  24691. if (onError !== undefined) onError(error);
  24692. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24693. return;
  24694. }
  24695. var metadata = json.metadata;
  24696. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24697. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24698. return;
  24699. }
  24700. scope.parse(json, onLoad);
  24701. }, onProgress, onError);
  24702. },
  24703. parse: function (json, onLoad) {
  24704. var shapes = this.parseShape(json.shapes);
  24705. var geometries = this.parseGeometries(json.geometries, shapes);
  24706. var images = this.parseImages(json.images, function () {
  24707. if (onLoad !== undefined) onLoad(object);
  24708. });
  24709. var textures = this.parseTextures(json.textures, images);
  24710. var materials = this.parseMaterials(json.materials, textures);
  24711. var object = this.parseObject(json.object, geometries, materials);
  24712. if (json.animations) {
  24713. object.animations = this.parseAnimations(json.animations);
  24714. }
  24715. if (json.images === undefined || json.images.length === 0) {
  24716. if (onLoad !== undefined) onLoad(object);
  24717. }
  24718. return object;
  24719. },
  24720. parseShape: function (json) {
  24721. var shapes = {};
  24722. if (json !== undefined) {
  24723. for (var i = 0, l = json.length; i < l; i++) {
  24724. var shape = new Shape().fromJSON(json[i]);
  24725. shapes[shape.uuid] = shape;
  24726. }
  24727. }
  24728. return shapes;
  24729. },
  24730. parseGeometries: function (json, shapes) {
  24731. var geometries = {};
  24732. if (json !== undefined) {
  24733. var bufferGeometryLoader = new BufferGeometryLoader();
  24734. for (var i = 0, l = json.length; i < l; i++) {
  24735. var geometry;
  24736. var data = json[i];
  24737. switch (data.type) {
  24738. case 'PlaneGeometry':
  24739. case 'PlaneBufferGeometry':
  24740. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24741. break;
  24742. case 'BoxGeometry':
  24743. case 'BoxBufferGeometry':
  24744. case 'CubeGeometry':
  24745. // backwards compatible
  24746. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24747. break;
  24748. case 'CircleGeometry':
  24749. case 'CircleBufferGeometry':
  24750. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24751. break;
  24752. case 'CylinderGeometry':
  24753. case 'CylinderBufferGeometry':
  24754. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24755. break;
  24756. case 'ConeGeometry':
  24757. case 'ConeBufferGeometry':
  24758. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24759. break;
  24760. case 'SphereGeometry':
  24761. case 'SphereBufferGeometry':
  24762. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24763. break;
  24764. case 'DodecahedronGeometry':
  24765. case 'DodecahedronBufferGeometry':
  24766. case 'IcosahedronGeometry':
  24767. case 'IcosahedronBufferGeometry':
  24768. case 'OctahedronGeometry':
  24769. case 'OctahedronBufferGeometry':
  24770. case 'TetrahedronGeometry':
  24771. case 'TetrahedronBufferGeometry':
  24772. geometry = new Geometries[data.type](data.radius, data.detail);
  24773. break;
  24774. case 'RingGeometry':
  24775. case 'RingBufferGeometry':
  24776. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24777. break;
  24778. case 'TorusGeometry':
  24779. case 'TorusBufferGeometry':
  24780. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24781. break;
  24782. case 'TorusKnotGeometry':
  24783. case 'TorusKnotBufferGeometry':
  24784. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24785. break;
  24786. case 'TubeGeometry':
  24787. case 'TubeBufferGeometry':
  24788. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24789. // User defined curves or instances of CurvePath will not be deserialized.
  24790. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24791. break;
  24792. case 'LatheGeometry':
  24793. case 'LatheBufferGeometry':
  24794. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24795. break;
  24796. case 'PolyhedronGeometry':
  24797. case 'PolyhedronBufferGeometry':
  24798. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24799. break;
  24800. case 'ShapeGeometry':
  24801. case 'ShapeBufferGeometry':
  24802. var geometryShapes = [];
  24803. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24804. var shape = shapes[data.shapes[j]];
  24805. geometryShapes.push(shape);
  24806. }
  24807. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24808. break;
  24809. case 'ExtrudeGeometry':
  24810. case 'ExtrudeBufferGeometry':
  24811. var geometryShapes = [];
  24812. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24813. var shape = shapes[data.shapes[j]];
  24814. geometryShapes.push(shape);
  24815. }
  24816. var extrudePath = data.options.extrudePath;
  24817. if (extrudePath !== undefined) {
  24818. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24819. }
  24820. geometry = new Geometries[data.type](geometryShapes, data.options);
  24821. break;
  24822. case 'BufferGeometry':
  24823. case 'InstancedBufferGeometry':
  24824. geometry = bufferGeometryLoader.parse(data);
  24825. break;
  24826. case 'Geometry':
  24827. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  24828. var geometryLoader = new THREE.LegacyJSONLoader();
  24829. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  24830. } else {
  24831. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  24832. }
  24833. break;
  24834. default:
  24835. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24836. continue;
  24837. }
  24838. geometry.uuid = data.uuid;
  24839. if (data.name !== undefined) geometry.name = data.name;
  24840. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24841. geometries[data.uuid] = geometry;
  24842. }
  24843. }
  24844. return geometries;
  24845. },
  24846. parseMaterials: function (json, textures) {
  24847. var cache = {}; // MultiMaterial
  24848. var materials = {};
  24849. if (json !== undefined) {
  24850. var loader = new MaterialLoader();
  24851. loader.setTextures(textures);
  24852. for (var i = 0, l = json.length; i < l; i++) {
  24853. var data = json[i];
  24854. if (data.type === 'MultiMaterial') {
  24855. // Deprecated
  24856. var array = [];
  24857. for (var j = 0; j < data.materials.length; j++) {
  24858. var material = data.materials[j];
  24859. if (cache[material.uuid] === undefined) {
  24860. cache[material.uuid] = loader.parse(material);
  24861. }
  24862. array.push(cache[material.uuid]);
  24863. }
  24864. materials[data.uuid] = array;
  24865. } else {
  24866. if (cache[data.uuid] === undefined) {
  24867. cache[data.uuid] = loader.parse(data);
  24868. }
  24869. materials[data.uuid] = cache[data.uuid];
  24870. }
  24871. }
  24872. }
  24873. return materials;
  24874. },
  24875. parseAnimations: function (json) {
  24876. var animations = [];
  24877. for (var i = 0; i < json.length; i++) {
  24878. var data = json[i];
  24879. var clip = AnimationClip.parse(data);
  24880. if (data.uuid !== undefined) clip.uuid = data.uuid;
  24881. animations.push(clip);
  24882. }
  24883. return animations;
  24884. },
  24885. parseImages: function (json, onLoad) {
  24886. var scope = this;
  24887. var images = {};
  24888. function loadImage(url) {
  24889. scope.manager.itemStart(url);
  24890. return loader.load(url, function () {
  24891. scope.manager.itemEnd(url);
  24892. }, undefined, function () {
  24893. scope.manager.itemError(url);
  24894. scope.manager.itemEnd(url);
  24895. });
  24896. }
  24897. if (json !== undefined && json.length > 0) {
  24898. var manager = new LoadingManager(onLoad);
  24899. var loader = new ImageLoader(manager);
  24900. loader.setCrossOrigin(this.crossOrigin);
  24901. for (var i = 0, il = json.length; i < il; i++) {
  24902. var image = json[i];
  24903. var url = image.url;
  24904. if (Array.isArray(url)) {
  24905. // load array of images e.g CubeTexture
  24906. images[image.uuid] = [];
  24907. for (var j = 0, jl = url.length; j < jl; j++) {
  24908. var currentUrl = url[j];
  24909. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  24910. images[image.uuid].push(loadImage(path));
  24911. }
  24912. } else {
  24913. // load single image
  24914. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  24915. images[image.uuid] = loadImage(path);
  24916. }
  24917. }
  24918. }
  24919. return images;
  24920. },
  24921. parseTextures: function (json, images) {
  24922. function parseConstant(value, type) {
  24923. if (typeof value === 'number') return value;
  24924. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24925. return type[value];
  24926. }
  24927. var textures = {};
  24928. if (json !== undefined) {
  24929. for (var i = 0, l = json.length; i < l; i++) {
  24930. var data = json[i];
  24931. if (data.image === undefined) {
  24932. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24933. }
  24934. if (images[data.image] === undefined) {
  24935. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24936. }
  24937. var texture;
  24938. if (Array.isArray(images[data.image])) {
  24939. texture = new CubeTexture(images[data.image]);
  24940. } else {
  24941. texture = new Texture(images[data.image]);
  24942. }
  24943. texture.needsUpdate = true;
  24944. texture.uuid = data.uuid;
  24945. if (data.name !== undefined) texture.name = data.name;
  24946. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24947. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24948. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24949. if (data.center !== undefined) texture.center.fromArray(data.center);
  24950. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24951. if (data.wrap !== undefined) {
  24952. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24953. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24954. }
  24955. if (data.format !== undefined) texture.format = data.format;
  24956. if (data.type !== undefined) texture.type = data.type;
  24957. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24958. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24959. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24960. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24961. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24962. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24963. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24964. textures[data.uuid] = texture;
  24965. }
  24966. }
  24967. return textures;
  24968. },
  24969. parseObject: function (data, geometries, materials) {
  24970. var object;
  24971. function getGeometry(name) {
  24972. if (geometries[name] === undefined) {
  24973. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24974. }
  24975. return geometries[name];
  24976. }
  24977. function getMaterial(name) {
  24978. if (name === undefined) return undefined;
  24979. if (Array.isArray(name)) {
  24980. var array = [];
  24981. for (var i = 0, l = name.length; i < l; i++) {
  24982. var uuid = name[i];
  24983. if (materials[uuid] === undefined) {
  24984. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24985. }
  24986. array.push(materials[uuid]);
  24987. }
  24988. return array;
  24989. }
  24990. if (materials[name] === undefined) {
  24991. console.warn('THREE.ObjectLoader: Undefined material', name);
  24992. }
  24993. return materials[name];
  24994. }
  24995. switch (data.type) {
  24996. case 'Scene':
  24997. object = new Scene();
  24998. if (data.background !== undefined) {
  24999. if (Number.isInteger(data.background)) {
  25000. object.background = new Color(data.background);
  25001. }
  25002. }
  25003. if (data.fog !== undefined) {
  25004. if (data.fog.type === 'Fog') {
  25005. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  25006. } else if (data.fog.type === 'FogExp2') {
  25007. object.fog = new FogExp2(data.fog.color, data.fog.density);
  25008. }
  25009. }
  25010. break;
  25011. case 'PerspectiveCamera':
  25012. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  25013. if (data.focus !== undefined) object.focus = data.focus;
  25014. if (data.zoom !== undefined) object.zoom = data.zoom;
  25015. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  25016. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  25017. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  25018. break;
  25019. case 'OrthographicCamera':
  25020. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  25021. if (data.zoom !== undefined) object.zoom = data.zoom;
  25022. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  25023. break;
  25024. case 'AmbientLight':
  25025. object = new AmbientLight(data.color, data.intensity);
  25026. break;
  25027. case 'DirectionalLight':
  25028. object = new DirectionalLight(data.color, data.intensity);
  25029. break;
  25030. case 'PointLight':
  25031. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  25032. break;
  25033. case 'RectAreaLight':
  25034. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  25035. break;
  25036. case 'SpotLight':
  25037. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  25038. break;
  25039. case 'HemisphereLight':
  25040. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  25041. break;
  25042. case 'SkinnedMesh':
  25043. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  25044. case 'Mesh':
  25045. var geometry = getGeometry(data.geometry);
  25046. var material = getMaterial(data.material);
  25047. if (geometry.bones && geometry.bones.length > 0) {
  25048. object = new SkinnedMesh(geometry, material);
  25049. } else {
  25050. object = new Mesh(geometry, material);
  25051. }
  25052. if (data.drawMode !== undefined) object.setDrawMode(data.drawMode);
  25053. break;
  25054. case 'LOD':
  25055. object = new LOD();
  25056. break;
  25057. case 'Line':
  25058. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  25059. break;
  25060. case 'LineLoop':
  25061. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  25062. break;
  25063. case 'LineSegments':
  25064. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  25065. break;
  25066. case 'PointCloud':
  25067. case 'Points':
  25068. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  25069. break;
  25070. case 'Sprite':
  25071. object = new Sprite(getMaterial(data.material));
  25072. break;
  25073. case 'Group':
  25074. object = new Group();
  25075. break;
  25076. default:
  25077. object = new Object3D();
  25078. }
  25079. object.uuid = data.uuid;
  25080. if (data.name !== undefined) object.name = data.name;
  25081. if (data.matrix !== undefined) {
  25082. object.matrix.fromArray(data.matrix);
  25083. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25084. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  25085. } else {
  25086. if (data.position !== undefined) object.position.fromArray(data.position);
  25087. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  25088. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  25089. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  25090. }
  25091. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  25092. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  25093. if (data.shadow) {
  25094. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  25095. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  25096. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  25097. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  25098. }
  25099. if (data.visible !== undefined) object.visible = data.visible;
  25100. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  25101. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  25102. if (data.userData !== undefined) object.userData = data.userData;
  25103. if (data.layers !== undefined) object.layers.mask = data.layers;
  25104. if (data.children !== undefined) {
  25105. var children = data.children;
  25106. for (var i = 0; i < children.length; i++) {
  25107. object.add(this.parseObject(children[i], geometries, materials));
  25108. }
  25109. }
  25110. if (data.type === 'LOD') {
  25111. var levels = data.levels;
  25112. for (var l = 0; l < levels.length; l++) {
  25113. var level = levels[l];
  25114. var child = object.getObjectByProperty('uuid', level.object);
  25115. if (child !== undefined) {
  25116. object.addLevel(child, level.distance);
  25117. }
  25118. }
  25119. }
  25120. return object;
  25121. }
  25122. });
  25123. var TEXTURE_MAPPING = {
  25124. UVMapping: UVMapping,
  25125. CubeReflectionMapping: CubeReflectionMapping,
  25126. CubeRefractionMapping: CubeRefractionMapping,
  25127. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25128. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25129. SphericalReflectionMapping: SphericalReflectionMapping,
  25130. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25131. CubeUVRefractionMapping: CubeUVRefractionMapping
  25132. };
  25133. var TEXTURE_WRAPPING = {
  25134. RepeatWrapping: RepeatWrapping,
  25135. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25136. MirroredRepeatWrapping: MirroredRepeatWrapping
  25137. };
  25138. var TEXTURE_FILTER = {
  25139. NearestFilter: NearestFilter,
  25140. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25141. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25142. LinearFilter: LinearFilter,
  25143. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25144. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25145. };
  25146. /**
  25147. * @author thespite / http://clicktorelease.com/
  25148. */
  25149. function ImageBitmapLoader(manager) {
  25150. if (typeof createImageBitmap === 'undefined') {
  25151. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25152. }
  25153. if (typeof fetch === 'undefined') {
  25154. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25155. }
  25156. Loader.call(this, manager);
  25157. this.options = undefined;
  25158. }
  25159. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25160. constructor: ImageBitmapLoader,
  25161. setOptions: function setOptions(options) {
  25162. this.options = options;
  25163. return this;
  25164. },
  25165. load: function (url, onLoad, onProgress, onError) {
  25166. if (url === undefined) url = '';
  25167. if (this.path !== undefined) url = this.path + url;
  25168. url = this.manager.resolveURL(url);
  25169. var scope = this;
  25170. var cached = Cache.get(url);
  25171. if (cached !== undefined) {
  25172. scope.manager.itemStart(url);
  25173. setTimeout(function () {
  25174. if (onLoad) onLoad(cached);
  25175. scope.manager.itemEnd(url);
  25176. }, 0);
  25177. return cached;
  25178. }
  25179. fetch(url).then(function (res) {
  25180. return res.blob();
  25181. }).then(function (blob) {
  25182. if (scope.options === undefined) {
  25183. // Workaround for FireFox. It causes an error if you pass options.
  25184. return createImageBitmap(blob);
  25185. } else {
  25186. return createImageBitmap(blob, scope.options);
  25187. }
  25188. }).then(function (imageBitmap) {
  25189. Cache.add(url, imageBitmap);
  25190. if (onLoad) onLoad(imageBitmap);
  25191. scope.manager.itemEnd(url);
  25192. }).catch(function (e) {
  25193. if (onError) onError(e);
  25194. scope.manager.itemError(url);
  25195. scope.manager.itemEnd(url);
  25196. });
  25197. scope.manager.itemStart(url);
  25198. }
  25199. });
  25200. /**
  25201. * @author zz85 / http://www.lab4games.net/zz85/blog
  25202. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  25203. **/
  25204. function ShapePath() {
  25205. this.type = 'ShapePath';
  25206. this.color = new Color();
  25207. this.subPaths = [];
  25208. this.currentPath = null;
  25209. }
  25210. Object.assign(ShapePath.prototype, {
  25211. moveTo: function (x, y) {
  25212. this.currentPath = new Path();
  25213. this.subPaths.push(this.currentPath);
  25214. this.currentPath.moveTo(x, y);
  25215. },
  25216. lineTo: function (x, y) {
  25217. this.currentPath.lineTo(x, y);
  25218. },
  25219. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  25220. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  25221. },
  25222. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  25223. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  25224. },
  25225. splineThru: function (pts) {
  25226. this.currentPath.splineThru(pts);
  25227. },
  25228. toShapes: function (isCCW, noHoles) {
  25229. function toShapesNoHoles(inSubpaths) {
  25230. var shapes = [];
  25231. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  25232. var tmpPath = inSubpaths[i];
  25233. var tmpShape = new Shape();
  25234. tmpShape.curves = tmpPath.curves;
  25235. shapes.push(tmpShape);
  25236. }
  25237. return shapes;
  25238. }
  25239. function isPointInsidePolygon(inPt, inPolygon) {
  25240. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  25241. // toggling of inside/outside at every single! intersection point of an edge
  25242. // with the horizontal line through inPt, left of inPt
  25243. // not counting lowerY endpoints of edges and whole edges on that line
  25244. var inside = false;
  25245. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  25246. var edgeLowPt = inPolygon[p];
  25247. var edgeHighPt = inPolygon[q];
  25248. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  25249. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  25250. if (Math.abs(edgeDy) > Number.EPSILON) {
  25251. // not parallel
  25252. if (edgeDy < 0) {
  25253. edgeLowPt = inPolygon[q];
  25254. edgeDx = -edgeDx;
  25255. edgeHighPt = inPolygon[p];
  25256. edgeDy = -edgeDy;
  25257. }
  25258. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  25259. if (inPt.y === edgeLowPt.y) {
  25260. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  25261. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25262. } else {
  25263. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  25264. if (perpEdge === 0) return true; // inPt is on contour ?
  25265. if (perpEdge < 0) continue;
  25266. inside = !inside; // true intersection left of inPt
  25267. }
  25268. } else {
  25269. // parallel or collinear
  25270. if (inPt.y !== edgeLowPt.y) continue; // parallel
  25271. // edge lies on the same horizontal line as inPt
  25272. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  25273. // continue;
  25274. }
  25275. }
  25276. return inside;
  25277. }
  25278. var isClockWise = ShapeUtils.isClockWise;
  25279. var subPaths = this.subPaths;
  25280. if (subPaths.length === 0) return [];
  25281. if (noHoles === true) return toShapesNoHoles(subPaths);
  25282. var solid,
  25283. tmpPath,
  25284. tmpShape,
  25285. shapes = [];
  25286. if (subPaths.length === 1) {
  25287. tmpPath = subPaths[0];
  25288. tmpShape = new Shape();
  25289. tmpShape.curves = tmpPath.curves;
  25290. shapes.push(tmpShape);
  25291. return shapes;
  25292. }
  25293. var holesFirst = !isClockWise(subPaths[0].getPoints());
  25294. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  25295. var betterShapeHoles = [];
  25296. var newShapes = [];
  25297. var newShapeHoles = [];
  25298. var mainIdx = 0;
  25299. var tmpPoints;
  25300. newShapes[mainIdx] = undefined;
  25301. newShapeHoles[mainIdx] = [];
  25302. for (var i = 0, l = subPaths.length; i < l; i++) {
  25303. tmpPath = subPaths[i];
  25304. tmpPoints = tmpPath.getPoints();
  25305. solid = isClockWise(tmpPoints);
  25306. solid = isCCW ? !solid : solid;
  25307. if (solid) {
  25308. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  25309. newShapes[mainIdx] = {
  25310. s: new Shape(),
  25311. p: tmpPoints
  25312. };
  25313. newShapes[mainIdx].s.curves = tmpPath.curves;
  25314. if (holesFirst) mainIdx++;
  25315. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  25316. } else {
  25317. newShapeHoles[mainIdx].push({
  25318. h: tmpPath,
  25319. p: tmpPoints[0]
  25320. }); //console.log('ccw', i);
  25321. }
  25322. } // only Holes? -> probably all Shapes with wrong orientation
  25323. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  25324. if (newShapes.length > 1) {
  25325. var ambiguous = false;
  25326. var toChange = [];
  25327. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25328. betterShapeHoles[sIdx] = [];
  25329. }
  25330. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25331. var sho = newShapeHoles[sIdx];
  25332. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  25333. var ho = sho[hIdx];
  25334. var hole_unassigned = true;
  25335. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  25336. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  25337. if (sIdx !== s2Idx) toChange.push({
  25338. froms: sIdx,
  25339. tos: s2Idx,
  25340. hole: hIdx
  25341. });
  25342. if (hole_unassigned) {
  25343. hole_unassigned = false;
  25344. betterShapeHoles[s2Idx].push(ho);
  25345. } else {
  25346. ambiguous = true;
  25347. }
  25348. }
  25349. }
  25350. if (hole_unassigned) {
  25351. betterShapeHoles[sIdx].push(ho);
  25352. }
  25353. }
  25354. } // console.log("ambiguous: ", ambiguous);
  25355. if (toChange.length > 0) {
  25356. // console.log("to change: ", toChange);
  25357. if (!ambiguous) newShapeHoles = betterShapeHoles;
  25358. }
  25359. }
  25360. var tmpHoles;
  25361. for (var i = 0, il = newShapes.length; i < il; i++) {
  25362. tmpShape = newShapes[i].s;
  25363. shapes.push(tmpShape);
  25364. tmpHoles = newShapeHoles[i];
  25365. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  25366. tmpShape.holes.push(tmpHoles[j].h);
  25367. }
  25368. } //console.log("shape", shapes);
  25369. return shapes;
  25370. }
  25371. });
  25372. /**
  25373. * @author zz85 / http://www.lab4games.net/zz85/blog
  25374. * @author mrdoob / http://mrdoob.com/
  25375. */
  25376. function Font(data) {
  25377. this.type = 'Font';
  25378. this.data = data;
  25379. }
  25380. Object.assign(Font.prototype, {
  25381. isFont: true,
  25382. generateShapes: function (text, size) {
  25383. if (size === undefined) size = 100;
  25384. var shapes = [];
  25385. var paths = createPaths(text, size, this.data);
  25386. for (var p = 0, pl = paths.length; p < pl; p++) {
  25387. Array.prototype.push.apply(shapes, paths[p].toShapes());
  25388. }
  25389. return shapes;
  25390. }
  25391. });
  25392. function createPaths(text, size, data) {
  25393. var chars = Array.from ? Array.from(text) : String(text).split(''); // see #13988
  25394. var scale = size / data.resolution;
  25395. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  25396. var paths = [];
  25397. var offsetX = 0,
  25398. offsetY = 0;
  25399. for (var i = 0; i < chars.length; i++) {
  25400. var char = chars[i];
  25401. if (char === '\n') {
  25402. offsetX = 0;
  25403. offsetY -= line_height;
  25404. } else {
  25405. var ret = createPath(char, scale, offsetX, offsetY, data);
  25406. offsetX += ret.offsetX;
  25407. paths.push(ret.path);
  25408. }
  25409. }
  25410. return paths;
  25411. }
  25412. function createPath(char, scale, offsetX, offsetY, data) {
  25413. var glyph = data.glyphs[char] || data.glyphs['?'];
  25414. if (!glyph) {
  25415. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  25416. return;
  25417. }
  25418. var path = new ShapePath();
  25419. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25420. if (glyph.o) {
  25421. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  25422. for (var i = 0, l = outline.length; i < l;) {
  25423. var action = outline[i++];
  25424. switch (action) {
  25425. case 'm':
  25426. // moveTo
  25427. x = outline[i++] * scale + offsetX;
  25428. y = outline[i++] * scale + offsetY;
  25429. path.moveTo(x, y);
  25430. break;
  25431. case 'l':
  25432. // lineTo
  25433. x = outline[i++] * scale + offsetX;
  25434. y = outline[i++] * scale + offsetY;
  25435. path.lineTo(x, y);
  25436. break;
  25437. case 'q':
  25438. // quadraticCurveTo
  25439. cpx = outline[i++] * scale + offsetX;
  25440. cpy = outline[i++] * scale + offsetY;
  25441. cpx1 = outline[i++] * scale + offsetX;
  25442. cpy1 = outline[i++] * scale + offsetY;
  25443. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  25444. break;
  25445. case 'b':
  25446. // bezierCurveTo
  25447. cpx = outline[i++] * scale + offsetX;
  25448. cpy = outline[i++] * scale + offsetY;
  25449. cpx1 = outline[i++] * scale + offsetX;
  25450. cpy1 = outline[i++] * scale + offsetY;
  25451. cpx2 = outline[i++] * scale + offsetX;
  25452. cpy2 = outline[i++] * scale + offsetY;
  25453. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  25454. break;
  25455. }
  25456. }
  25457. }
  25458. return {
  25459. offsetX: glyph.ha * scale,
  25460. path: path
  25461. };
  25462. }
  25463. /**
  25464. * @author mrdoob / http://mrdoob.com/
  25465. */
  25466. function FontLoader(manager) {
  25467. Loader.call(this, manager);
  25468. }
  25469. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25470. constructor: FontLoader,
  25471. load: function (url, onLoad, onProgress, onError) {
  25472. var scope = this;
  25473. var loader = new FileLoader(this.manager);
  25474. loader.setPath(this.path);
  25475. loader.load(url, function (text) {
  25476. var json;
  25477. try {
  25478. json = JSON.parse(text);
  25479. } catch (e) {
  25480. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  25481. json = JSON.parse(text.substring(65, text.length - 2));
  25482. }
  25483. var font = scope.parse(json);
  25484. if (onLoad) onLoad(font);
  25485. }, onProgress, onError);
  25486. },
  25487. parse: function (json) {
  25488. return new Font(json);
  25489. }
  25490. });
  25491. /**
  25492. * @author mrdoob / http://mrdoob.com/
  25493. */
  25494. var _context;
  25495. var AudioContext = {
  25496. getContext: function () {
  25497. if (_context === undefined) {
  25498. _context = new (window.AudioContext || window.webkitAudioContext)();
  25499. }
  25500. return _context;
  25501. },
  25502. setContext: function (value) {
  25503. _context = value;
  25504. }
  25505. };
  25506. /**
  25507. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25508. */
  25509. exports.AudioContext = AudioContext;
  25510. function AudioLoader(manager) {
  25511. Loader.call(this, manager);
  25512. }
  25513. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25514. constructor: AudioLoader,
  25515. load: function (url, onLoad, onProgress, onError) {
  25516. var loader = new FileLoader(this.manager);
  25517. loader.setResponseType('arraybuffer');
  25518. loader.setPath(this.path);
  25519. loader.load(url, function (buffer) {
  25520. // Create a copy of the buffer. The `decodeAudioData` method
  25521. // detaches the buffer when complete, preventing reuse.
  25522. var bufferCopy = buffer.slice(0);
  25523. var context = AudioContext.getContext();
  25524. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25525. onLoad(audioBuffer);
  25526. });
  25527. }, onProgress, onError);
  25528. }
  25529. });
  25530. /**
  25531. * @author bhouston / http://clara.io
  25532. * @author WestLangley / http://github.com/WestLangley
  25533. *
  25534. * Primary reference:
  25535. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25536. *
  25537. * Secondary reference:
  25538. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25539. */
  25540. // 3-band SH defined by 9 coefficients
  25541. function SphericalHarmonics3() {
  25542. this.coefficients = [];
  25543. for (var i = 0; i < 9; i++) {
  25544. this.coefficients.push(new Vector3());
  25545. }
  25546. }
  25547. Object.assign(SphericalHarmonics3.prototype, {
  25548. isSphericalHarmonics3: true,
  25549. set: function (coefficients) {
  25550. for (var i = 0; i < 9; i++) {
  25551. this.coefficients[i].copy(coefficients[i]);
  25552. }
  25553. return this;
  25554. },
  25555. zero: function () {
  25556. for (var i = 0; i < 9; i++) {
  25557. this.coefficients[i].set(0, 0, 0);
  25558. }
  25559. return this;
  25560. },
  25561. // get the radiance in the direction of the normal
  25562. // target is a Vector3
  25563. getAt: function (normal, target) {
  25564. // normal is assumed to be unit length
  25565. var x = normal.x,
  25566. y = normal.y,
  25567. z = normal.z;
  25568. var coeff = this.coefficients; // band 0
  25569. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  25570. target.addScale(coeff[1], 0.488603 * y);
  25571. target.addScale(coeff[2], 0.488603 * z);
  25572. target.addScale(coeff[3], 0.488603 * x); // band 2
  25573. target.addScale(coeff[4], 1.092548 * (x * y));
  25574. target.addScale(coeff[5], 1.092548 * (y * z));
  25575. target.addScale(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  25576. target.addScale(coeff[7], 1.092548 * (x * z));
  25577. target.addScale(coeff[8], 0.546274 * (x * x - y * y));
  25578. return target;
  25579. },
  25580. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25581. // target is a Vector3
  25582. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25583. getIrradianceAt: function (normal, target) {
  25584. // normal is assumed to be unit length
  25585. var x = normal.x,
  25586. y = normal.y,
  25587. z = normal.z;
  25588. var coeff = this.coefficients; // band 0
  25589. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  25590. // band 1
  25591. target.addScale(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  25592. target.addScale(coeff[2], 2.0 * 0.511664 * z);
  25593. target.addScale(coeff[3], 2.0 * 0.511664 * x); // band 2
  25594. target.addScale(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  25595. target.addScale(coeff[5], 2.0 * 0.429043 * y * z);
  25596. target.addScale(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  25597. target.addScale(coeff[7], 2.0 * 0.429043 * x * z);
  25598. target.addScale(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  25599. return target;
  25600. },
  25601. add: function (sh) {
  25602. for (var i = 0; i < 9; i++) {
  25603. this.coefficients[i].add(sh.coefficients[i]);
  25604. }
  25605. return this;
  25606. },
  25607. scale: function (s) {
  25608. for (var i = 0; i < 9; i++) {
  25609. this.coefficients[i].multiplyScalar(s);
  25610. }
  25611. return this;
  25612. },
  25613. lerp: function (sh, alpha) {
  25614. for (var i = 0; i < 9; i++) {
  25615. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  25616. }
  25617. return this;
  25618. },
  25619. equals: function (sh) {
  25620. for (var i = 0; i < 9; i++) {
  25621. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  25622. return false;
  25623. }
  25624. }
  25625. return true;
  25626. },
  25627. copy: function (sh) {
  25628. return this.set(sh.coefficients);
  25629. },
  25630. clone: function () {
  25631. return new this.constructor().copy(this);
  25632. },
  25633. fromArray: function (array, offset) {
  25634. if (offset === undefined) offset = 0;
  25635. var coefficients = this.coefficients;
  25636. for (var i = 0; i < 9; i++) {
  25637. coefficients[i].fromArray(array, offset + i * 3);
  25638. }
  25639. return this;
  25640. },
  25641. toArray: function (array, offset) {
  25642. if (array === undefined) array = [];
  25643. if (offset === undefined) offset = 0;
  25644. var coefficients = this.coefficients;
  25645. for (var i = 0; i < 9; i++) {
  25646. coefficients[i].toArray(array, offset + i * 3);
  25647. }
  25648. return array;
  25649. }
  25650. });
  25651. Object.assign(SphericalHarmonics3, {
  25652. // evaluate the basis functions
  25653. // shBasis is an Array[ 9 ]
  25654. getBasisAt: function (normal, shBasis) {
  25655. // normal is assumed to be unit length
  25656. var x = normal.x,
  25657. y = normal.y,
  25658. z = normal.z; // band 0
  25659. shBasis[0] = 0.282095; // band 1
  25660. shBasis[1] = 0.488603 * y;
  25661. shBasis[2] = 0.488603 * z;
  25662. shBasis[3] = 0.488603 * x; // band 2
  25663. shBasis[4] = 1.092548 * x * y;
  25664. shBasis[5] = 1.092548 * y * z;
  25665. shBasis[6] = 0.315392 * (3 * z * z - 1);
  25666. shBasis[7] = 1.092548 * x * z;
  25667. shBasis[8] = 0.546274 * (x * x - y * y);
  25668. }
  25669. });
  25670. /**
  25671. * @author WestLangley / http://github.com/WestLangley
  25672. *
  25673. * A LightProbe is a source of indirect-diffuse light
  25674. */
  25675. function LightProbe(sh, intensity) {
  25676. Light.call(this, undefined, intensity);
  25677. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  25678. }
  25679. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  25680. constructor: LightProbe,
  25681. isLightProbe: true,
  25682. copy: function (source) {
  25683. Light.prototype.copy.call(this, source);
  25684. this.sh.copy(source.sh);
  25685. this.intensity = source.intensity;
  25686. return this;
  25687. },
  25688. toJSON: function (meta) {
  25689. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25690. return data;
  25691. }
  25692. });
  25693. /**
  25694. * @author WestLangley / http://github.com/WestLangley
  25695. */
  25696. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  25697. LightProbe.call(this, undefined, intensity);
  25698. var color1 = new Color().set(skyColor);
  25699. var color2 = new Color().set(groundColor);
  25700. var sky = new Vector3(color1.r, color1.g, color1.b);
  25701. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25702. var c0 = Math.sqrt(Math.PI);
  25703. var c1 = c0 * Math.sqrt(0.75);
  25704. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25705. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25706. }
  25707. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25708. constructor: HemisphereLightProbe,
  25709. isHemisphereLightProbe: true,
  25710. copy: function (source) {
  25711. // modifying colors not currently supported
  25712. LightProbe.prototype.copy.call(this, source);
  25713. return this;
  25714. },
  25715. toJSON: function (meta) {
  25716. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25717. return data;
  25718. }
  25719. });
  25720. /**
  25721. * @author WestLangley / http://github.com/WestLangley
  25722. */
  25723. function AmbientLightProbe(color, intensity) {
  25724. LightProbe.call(this, undefined, intensity);
  25725. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25726. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25727. }
  25728. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25729. constructor: AmbientLightProbe,
  25730. isAmbientLightProbe: true,
  25731. copy: function (source) {
  25732. // modifying color not currently supported
  25733. LightProbe.prototype.copy.call(this, source);
  25734. return this;
  25735. },
  25736. toJSON: function (meta) {
  25737. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25738. return data;
  25739. }
  25740. });
  25741. var _eyeRight = new Matrix4();
  25742. var _eyeLeft = new Matrix4();
  25743. /**
  25744. * @author mrdoob / http://mrdoob.com/
  25745. */
  25746. function StereoCamera() {
  25747. this.type = 'StereoCamera';
  25748. this.aspect = 1;
  25749. this.eyeSep = 0.064;
  25750. this.cameraL = new PerspectiveCamera();
  25751. this.cameraL.layers.enable(1);
  25752. this.cameraL.matrixAutoUpdate = false;
  25753. this.cameraR = new PerspectiveCamera();
  25754. this.cameraR.layers.enable(2);
  25755. this.cameraR.matrixAutoUpdate = false;
  25756. this._cache = {
  25757. focus: null,
  25758. fov: null,
  25759. aspect: null,
  25760. near: null,
  25761. far: null,
  25762. zoom: null,
  25763. eyeSep: null
  25764. };
  25765. }
  25766. Object.assign(StereoCamera.prototype, {
  25767. update: function (camera) {
  25768. var cache = this._cache;
  25769. 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;
  25770. if (needsUpdate) {
  25771. cache.focus = camera.focus;
  25772. cache.fov = camera.fov;
  25773. cache.aspect = camera.aspect * this.aspect;
  25774. cache.near = camera.near;
  25775. cache.far = camera.far;
  25776. cache.zoom = camera.zoom;
  25777. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25778. // http://paulbourke.net/stereographics/stereorender/
  25779. var projectionMatrix = camera.projectionMatrix.clone();
  25780. var eyeSepHalf = cache.eyeSep / 2;
  25781. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25782. var ymax = cache.near * Math.tan(_Math.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25783. var xmin, xmax; // translate xOffset
  25784. _eyeLeft.elements[12] = -eyeSepHalf;
  25785. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25786. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25787. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25788. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25789. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25790. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25791. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25792. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25793. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25794. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25795. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25796. }
  25797. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25798. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25799. }
  25800. });
  25801. /**
  25802. * @author alteredq / http://alteredqualia.com/
  25803. */
  25804. function Clock(autoStart) {
  25805. this.autoStart = autoStart !== undefined ? autoStart : true;
  25806. this.startTime = 0;
  25807. this.oldTime = 0;
  25808. this.elapsedTime = 0;
  25809. this.running = false;
  25810. }
  25811. Object.assign(Clock.prototype, {
  25812. start: function () {
  25813. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25814. this.oldTime = this.startTime;
  25815. this.elapsedTime = 0;
  25816. this.running = true;
  25817. },
  25818. stop: function () {
  25819. this.getElapsedTime();
  25820. this.running = false;
  25821. this.autoStart = false;
  25822. },
  25823. getElapsedTime: function () {
  25824. this.getDelta();
  25825. return this.elapsedTime;
  25826. },
  25827. getDelta: function () {
  25828. var diff = 0;
  25829. if (this.autoStart && !this.running) {
  25830. this.start();
  25831. return 0;
  25832. }
  25833. if (this.running) {
  25834. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  25835. diff = (newTime - this.oldTime) / 1000;
  25836. this.oldTime = newTime;
  25837. this.elapsedTime += diff;
  25838. }
  25839. return diff;
  25840. }
  25841. });
  25842. /**
  25843. * @author mrdoob / http://mrdoob.com/
  25844. */
  25845. var _position$2 = new Vector3();
  25846. var _quaternion$3 = new Quaternion();
  25847. var _scale$1 = new Vector3();
  25848. var _orientation = new Vector3();
  25849. function AudioListener() {
  25850. Object3D.call(this);
  25851. this.type = 'AudioListener';
  25852. this.context = AudioContext.getContext();
  25853. this.gain = this.context.createGain();
  25854. this.gain.connect(this.context.destination);
  25855. this.filter = null;
  25856. this.timeDelta = 0; // private
  25857. this._clock = new Clock();
  25858. }
  25859. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  25860. constructor: AudioListener,
  25861. getInput: function () {
  25862. return this.gain;
  25863. },
  25864. removeFilter: function () {
  25865. if (this.filter !== null) {
  25866. this.gain.disconnect(this.filter);
  25867. this.filter.disconnect(this.context.destination);
  25868. this.gain.connect(this.context.destination);
  25869. this.filter = null;
  25870. }
  25871. return this;
  25872. },
  25873. getFilter: function () {
  25874. return this.filter;
  25875. },
  25876. setFilter: function (value) {
  25877. if (this.filter !== null) {
  25878. this.gain.disconnect(this.filter);
  25879. this.filter.disconnect(this.context.destination);
  25880. } else {
  25881. this.gain.disconnect(this.context.destination);
  25882. }
  25883. this.filter = value;
  25884. this.gain.connect(this.filter);
  25885. this.filter.connect(this.context.destination);
  25886. return this;
  25887. },
  25888. getMasterVolume: function () {
  25889. return this.gain.gain.value;
  25890. },
  25891. setMasterVolume: function (value) {
  25892. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25893. return this;
  25894. },
  25895. updateMatrixWorld: function (force) {
  25896. Object3D.prototype.updateMatrixWorld.call(this, force);
  25897. var listener = this.context.listener;
  25898. var up = this.up;
  25899. this.timeDelta = this._clock.getDelta();
  25900. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25901. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25902. if (listener.positionX) {
  25903. // code path for Chrome (see #14393)
  25904. var endTime = this.context.currentTime + this.timeDelta;
  25905. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25906. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25907. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25908. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25909. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25910. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25911. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25912. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25913. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25914. } else {
  25915. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25916. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25917. }
  25918. }
  25919. });
  25920. /**
  25921. * @author mrdoob / http://mrdoob.com/
  25922. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25923. */
  25924. function Audio(listener) {
  25925. Object3D.call(this);
  25926. this.type = 'Audio';
  25927. this.listener = listener;
  25928. this.context = listener.context;
  25929. this.gain = this.context.createGain();
  25930. this.gain.connect(listener.getInput());
  25931. this.autoplay = false;
  25932. this.buffer = null;
  25933. this.detune = 0;
  25934. this.loop = false;
  25935. this.startTime = 0;
  25936. this.offset = 0;
  25937. this.duration = undefined;
  25938. this.playbackRate = 1;
  25939. this.isPlaying = false;
  25940. this.hasPlaybackControl = true;
  25941. this.sourceType = 'empty';
  25942. this.filters = [];
  25943. }
  25944. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  25945. constructor: Audio,
  25946. getOutput: function () {
  25947. return this.gain;
  25948. },
  25949. setNodeSource: function (audioNode) {
  25950. this.hasPlaybackControl = false;
  25951. this.sourceType = 'audioNode';
  25952. this.source = audioNode;
  25953. this.connect();
  25954. return this;
  25955. },
  25956. setMediaElementSource: function (mediaElement) {
  25957. this.hasPlaybackControl = false;
  25958. this.sourceType = 'mediaNode';
  25959. this.source = this.context.createMediaElementSource(mediaElement);
  25960. this.connect();
  25961. return this;
  25962. },
  25963. setMediaStreamSource: function (mediaStream) {
  25964. this.hasPlaybackControl = false;
  25965. this.sourceType = 'mediaStreamNode';
  25966. this.source = this.context.createMediaStreamSource(mediaStream);
  25967. this.connect();
  25968. return this;
  25969. },
  25970. setBuffer: function (audioBuffer) {
  25971. this.buffer = audioBuffer;
  25972. this.sourceType = 'buffer';
  25973. if (this.autoplay) this.play();
  25974. return this;
  25975. },
  25976. play: function () {
  25977. if (this.isPlaying === true) {
  25978. console.warn('THREE.Audio: Audio is already playing.');
  25979. return;
  25980. }
  25981. if (this.hasPlaybackControl === false) {
  25982. console.warn('THREE.Audio: this Audio has no playback control.');
  25983. return;
  25984. }
  25985. var source = this.context.createBufferSource();
  25986. source.buffer = this.buffer;
  25987. source.loop = this.loop;
  25988. source.onended = this.onEnded.bind(this);
  25989. this.startTime = this.context.currentTime;
  25990. source.start(this.startTime, this.offset, this.duration);
  25991. this.isPlaying = true;
  25992. this.source = source;
  25993. this.setDetune(this.detune);
  25994. this.setPlaybackRate(this.playbackRate);
  25995. return this.connect();
  25996. },
  25997. pause: function () {
  25998. if (this.hasPlaybackControl === false) {
  25999. console.warn('THREE.Audio: this Audio has no playback control.');
  26000. return;
  26001. }
  26002. if (this.isPlaying === true) {
  26003. this.source.stop();
  26004. this.source.onended = null;
  26005. this.offset += (this.context.currentTime - this.startTime) * this.playbackRate;
  26006. this.isPlaying = false;
  26007. }
  26008. return this;
  26009. },
  26010. stop: function () {
  26011. if (this.hasPlaybackControl === false) {
  26012. console.warn('THREE.Audio: this Audio has no playback control.');
  26013. return;
  26014. }
  26015. this.source.stop();
  26016. this.source.onended = null;
  26017. this.offset = 0;
  26018. this.isPlaying = false;
  26019. return this;
  26020. },
  26021. connect: function () {
  26022. if (this.filters.length > 0) {
  26023. this.source.connect(this.filters[0]);
  26024. for (var i = 1, l = this.filters.length; i < l; i++) {
  26025. this.filters[i - 1].connect(this.filters[i]);
  26026. }
  26027. this.filters[this.filters.length - 1].connect(this.getOutput());
  26028. } else {
  26029. this.source.connect(this.getOutput());
  26030. }
  26031. return this;
  26032. },
  26033. disconnect: function () {
  26034. if (this.filters.length > 0) {
  26035. this.source.disconnect(this.filters[0]);
  26036. for (var i = 1, l = this.filters.length; i < l; i++) {
  26037. this.filters[i - 1].disconnect(this.filters[i]);
  26038. }
  26039. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  26040. } else {
  26041. this.source.disconnect(this.getOutput());
  26042. }
  26043. return this;
  26044. },
  26045. getFilters: function () {
  26046. return this.filters;
  26047. },
  26048. setFilters: function (value) {
  26049. if (!value) value = [];
  26050. if (this.isPlaying === true) {
  26051. this.disconnect();
  26052. this.filters = value;
  26053. this.connect();
  26054. } else {
  26055. this.filters = value;
  26056. }
  26057. return this;
  26058. },
  26059. setDetune: function (value) {
  26060. this.detune = value;
  26061. if (this.source.detune === undefined) return; // only set detune when available
  26062. if (this.isPlaying === true) {
  26063. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  26064. }
  26065. return this;
  26066. },
  26067. getDetune: function () {
  26068. return this.detune;
  26069. },
  26070. getFilter: function () {
  26071. return this.getFilters()[0];
  26072. },
  26073. setFilter: function (filter) {
  26074. return this.setFilters(filter ? [filter] : []);
  26075. },
  26076. setPlaybackRate: function (value) {
  26077. if (this.hasPlaybackControl === false) {
  26078. console.warn('THREE.Audio: this Audio has no playback control.');
  26079. return;
  26080. }
  26081. this.playbackRate = value;
  26082. if (this.isPlaying === true) {
  26083. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  26084. }
  26085. return this;
  26086. },
  26087. getPlaybackRate: function () {
  26088. return this.playbackRate;
  26089. },
  26090. onEnded: function () {
  26091. this.isPlaying = false;
  26092. },
  26093. getLoop: function () {
  26094. if (this.hasPlaybackControl === false) {
  26095. console.warn('THREE.Audio: this Audio has no playback control.');
  26096. return false;
  26097. }
  26098. return this.loop;
  26099. },
  26100. setLoop: function (value) {
  26101. if (this.hasPlaybackControl === false) {
  26102. console.warn('THREE.Audio: this Audio has no playback control.');
  26103. return;
  26104. }
  26105. this.loop = value;
  26106. if (this.isPlaying === true) {
  26107. this.source.loop = this.loop;
  26108. }
  26109. return this;
  26110. },
  26111. getVolume: function () {
  26112. return this.gain.gain.value;
  26113. },
  26114. setVolume: function (value) {
  26115. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  26116. return this;
  26117. }
  26118. });
  26119. /**
  26120. * @author mrdoob / http://mrdoob.com/
  26121. */
  26122. var _position$3 = new Vector3();
  26123. var _quaternion$4 = new Quaternion();
  26124. var _scale$2 = new Vector3();
  26125. var _orientation$1 = new Vector3();
  26126. function PositionalAudio(listener) {
  26127. Audio.call(this, listener);
  26128. this.panner = this.context.createPanner();
  26129. this.panner.panningModel = 'HRTF';
  26130. this.panner.connect(this.gain);
  26131. }
  26132. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  26133. constructor: PositionalAudio,
  26134. getOutput: function () {
  26135. return this.panner;
  26136. },
  26137. getRefDistance: function () {
  26138. return this.panner.refDistance;
  26139. },
  26140. setRefDistance: function (value) {
  26141. this.panner.refDistance = value;
  26142. return this;
  26143. },
  26144. getRolloffFactor: function () {
  26145. return this.panner.rolloffFactor;
  26146. },
  26147. setRolloffFactor: function (value) {
  26148. this.panner.rolloffFactor = value;
  26149. return this;
  26150. },
  26151. getDistanceModel: function () {
  26152. return this.panner.distanceModel;
  26153. },
  26154. setDistanceModel: function (value) {
  26155. this.panner.distanceModel = value;
  26156. return this;
  26157. },
  26158. getMaxDistance: function () {
  26159. return this.panner.maxDistance;
  26160. },
  26161. setMaxDistance: function (value) {
  26162. this.panner.maxDistance = value;
  26163. return this;
  26164. },
  26165. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26166. this.panner.coneInnerAngle = coneInnerAngle;
  26167. this.panner.coneOuterAngle = coneOuterAngle;
  26168. this.panner.coneOuterGain = coneOuterGain;
  26169. return this;
  26170. },
  26171. updateMatrixWorld: function (force) {
  26172. Object3D.prototype.updateMatrixWorld.call(this, force);
  26173. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  26174. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  26175. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  26176. var panner = this.panner;
  26177. if (panner.positionX) {
  26178. // code path for Chrome and Firefox (see #14393)
  26179. var endTime = this.context.currentTime + this.listener.timeDelta;
  26180. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  26181. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  26182. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  26183. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  26184. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  26185. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  26186. } else {
  26187. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  26188. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  26189. }
  26190. }
  26191. });
  26192. /**
  26193. * @author mrdoob / http://mrdoob.com/
  26194. */
  26195. function AudioAnalyser(audio, fftSize) {
  26196. this.analyser = audio.context.createAnalyser();
  26197. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  26198. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  26199. audio.getOutput().connect(this.analyser);
  26200. }
  26201. Object.assign(AudioAnalyser.prototype, {
  26202. getFrequencyData: function () {
  26203. this.analyser.getByteFrequencyData(this.data);
  26204. return this.data;
  26205. },
  26206. getAverageFrequency: function () {
  26207. var value = 0,
  26208. data = this.getFrequencyData();
  26209. for (var i = 0; i < data.length; i++) {
  26210. value += data[i];
  26211. }
  26212. return value / data.length;
  26213. }
  26214. });
  26215. /**
  26216. *
  26217. * Buffered scene graph property that allows weighted accumulation.
  26218. *
  26219. *
  26220. * @author Ben Houston / http://clara.io/
  26221. * @author David Sarno / http://lighthaus.us/
  26222. * @author tschw
  26223. */
  26224. function PropertyMixer(binding, typeName, valueSize) {
  26225. this.binding = binding;
  26226. this.valueSize = valueSize;
  26227. var bufferType = Float64Array,
  26228. mixFunction;
  26229. switch (typeName) {
  26230. case 'quaternion':
  26231. mixFunction = this._slerp;
  26232. break;
  26233. case 'string':
  26234. case 'bool':
  26235. bufferType = Array;
  26236. mixFunction = this._select;
  26237. break;
  26238. default:
  26239. mixFunction = this._lerp;
  26240. }
  26241. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  26242. //
  26243. // interpolators can use .buffer as their .result
  26244. // the data then goes to 'incoming'
  26245. //
  26246. // 'accu0' and 'accu1' are used frame-interleaved for
  26247. // the cumulative result and are compared to detect
  26248. // changes
  26249. //
  26250. // 'orig' stores the original state of the property
  26251. this._mixBufferRegion = mixFunction;
  26252. this.cumulativeWeight = 0;
  26253. this.useCount = 0;
  26254. this.referenceCount = 0;
  26255. }
  26256. Object.assign(PropertyMixer.prototype, {
  26257. // accumulate data in the 'incoming' region into 'accu<i>'
  26258. accumulate: function (accuIndex, weight) {
  26259. // note: happily accumulating nothing when weight = 0, the caller knows
  26260. // the weight and shouldn't have made the call in the first place
  26261. var buffer = this.buffer,
  26262. stride = this.valueSize,
  26263. offset = accuIndex * stride + stride,
  26264. currentWeight = this.cumulativeWeight;
  26265. if (currentWeight === 0) {
  26266. // accuN := incoming * weight
  26267. for (var i = 0; i !== stride; ++i) {
  26268. buffer[offset + i] = buffer[i];
  26269. }
  26270. currentWeight = weight;
  26271. } else {
  26272. // accuN := accuN + incoming * weight
  26273. currentWeight += weight;
  26274. var mix = weight / currentWeight;
  26275. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26276. }
  26277. this.cumulativeWeight = currentWeight;
  26278. },
  26279. // apply the state of 'accu<i>' to the binding when accus differ
  26280. apply: function (accuIndex) {
  26281. var stride = this.valueSize,
  26282. buffer = this.buffer,
  26283. offset = accuIndex * stride + stride,
  26284. weight = this.cumulativeWeight,
  26285. binding = this.binding;
  26286. this.cumulativeWeight = 0;
  26287. if (weight < 1) {
  26288. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26289. var originalValueOffset = stride * 3;
  26290. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26291. }
  26292. for (var i = stride, e = stride + stride; i !== e; ++i) {
  26293. if (buffer[i] !== buffer[i + stride]) {
  26294. // value has changed -> update scene graph
  26295. binding.setValue(buffer, offset);
  26296. break;
  26297. }
  26298. }
  26299. },
  26300. // remember the state of the bound property and copy it to both accus
  26301. saveOriginalState: function () {
  26302. var binding = this.binding;
  26303. var buffer = this.buffer,
  26304. stride = this.valueSize,
  26305. originalValueOffset = stride * 3;
  26306. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  26307. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  26308. buffer[i] = buffer[originalValueOffset + i % stride];
  26309. }
  26310. this.cumulativeWeight = 0;
  26311. },
  26312. // apply the state previously taken via 'saveOriginalState' to the binding
  26313. restoreOriginalState: function () {
  26314. var originalValueOffset = this.valueSize * 3;
  26315. this.binding.setValue(this.buffer, originalValueOffset);
  26316. },
  26317. // mix functions
  26318. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  26319. if (t >= 0.5) {
  26320. for (var i = 0; i !== stride; ++i) {
  26321. buffer[dstOffset + i] = buffer[srcOffset + i];
  26322. }
  26323. }
  26324. },
  26325. _slerp: function (buffer, dstOffset, srcOffset, t) {
  26326. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26327. },
  26328. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  26329. var s = 1 - t;
  26330. for (var i = 0; i !== stride; ++i) {
  26331. var j = dstOffset + i;
  26332. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26333. }
  26334. }
  26335. });
  26336. /**
  26337. *
  26338. * A reference to a real property in the scene graph.
  26339. *
  26340. *
  26341. * @author Ben Houston / http://clara.io/
  26342. * @author David Sarno / http://lighthaus.us/
  26343. * @author tschw
  26344. */
  26345. // Characters [].:/ are reserved for track binding syntax.
  26346. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26347. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26348. // only latin characters, and the unicode \p{L} is not yet supported. So
  26349. // instead, we exclude reserved characters and match everything else.
  26350. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26351. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26352. // be matched to parse the rest of the track name.
  26353. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26354. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  26355. // characters. Accessor may contain any character except closing bracket.
  26356. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  26357. // contain any non-bracket characters.
  26358. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26359. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26360. var _supportedObjectNames = ['material', 'materials', 'bones'];
  26361. function Composite(targetGroup, path, optionalParsedPath) {
  26362. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26363. this._targetGroup = targetGroup;
  26364. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26365. }
  26366. Object.assign(Composite.prototype, {
  26367. getValue: function (array, offset) {
  26368. this.bind(); // bind all binding
  26369. var firstValidIndex = this._targetGroup.nCachedObjects_,
  26370. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  26371. if (binding !== undefined) binding.getValue(array, offset);
  26372. },
  26373. setValue: function (array, offset) {
  26374. var bindings = this._bindings;
  26375. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26376. bindings[i].setValue(array, offset);
  26377. }
  26378. },
  26379. bind: function () {
  26380. var bindings = this._bindings;
  26381. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26382. bindings[i].bind();
  26383. }
  26384. },
  26385. unbind: function () {
  26386. var bindings = this._bindings;
  26387. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26388. bindings[i].unbind();
  26389. }
  26390. }
  26391. });
  26392. function PropertyBinding(rootNode, path, parsedPath) {
  26393. this.path = path;
  26394. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26395. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26396. this.rootNode = rootNode;
  26397. }
  26398. Object.assign(PropertyBinding, {
  26399. Composite: Composite,
  26400. create: function (root, path, parsedPath) {
  26401. if (!(root && root.isAnimationObjectGroup)) {
  26402. return new PropertyBinding(root, path, parsedPath);
  26403. } else {
  26404. return new PropertyBinding.Composite(root, path, parsedPath);
  26405. }
  26406. },
  26407. /**
  26408. * Replaces spaces with underscores and removes unsupported characters from
  26409. * node names, to ensure compatibility with parseTrackName().
  26410. *
  26411. * @param {string} name Node name to be sanitized.
  26412. * @return {string}
  26413. */
  26414. sanitizeNodeName: function (name) {
  26415. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26416. },
  26417. parseTrackName: function (trackName) {
  26418. var matches = _trackRe.exec(trackName);
  26419. if (!matches) {
  26420. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26421. }
  26422. var results = {
  26423. // directoryName: matches[ 1 ], // (tschw) currently unused
  26424. nodeName: matches[2],
  26425. objectName: matches[3],
  26426. objectIndex: matches[4],
  26427. propertyName: matches[5],
  26428. // required
  26429. propertyIndex: matches[6]
  26430. };
  26431. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26432. if (lastDot !== undefined && lastDot !== -1) {
  26433. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  26434. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26435. // 'bar' could be the objectName, or part of a nodeName (which can
  26436. // include '.' characters).
  26437. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26438. results.nodeName = results.nodeName.substring(0, lastDot);
  26439. results.objectName = objectName;
  26440. }
  26441. }
  26442. if (results.propertyName === null || results.propertyName.length === 0) {
  26443. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26444. }
  26445. return results;
  26446. },
  26447. findNode: function (root, nodeName) {
  26448. if (!nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26449. return root;
  26450. } // search into skeleton bones.
  26451. if (root.skeleton) {
  26452. var bone = root.skeleton.getBoneByName(nodeName);
  26453. if (bone !== undefined) {
  26454. return bone;
  26455. }
  26456. } // search into node subtree.
  26457. if (root.children) {
  26458. var searchNodeSubtree = function (children) {
  26459. for (var i = 0; i < children.length; i++) {
  26460. var childNode = children[i];
  26461. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26462. return childNode;
  26463. }
  26464. var result = searchNodeSubtree(childNode.children);
  26465. if (result) return result;
  26466. }
  26467. return null;
  26468. };
  26469. var subTreeNode = searchNodeSubtree(root.children);
  26470. if (subTreeNode) {
  26471. return subTreeNode;
  26472. }
  26473. }
  26474. return null;
  26475. }
  26476. });
  26477. Object.assign(PropertyBinding.prototype, {
  26478. // prototype, continued
  26479. // these are used to "bind" a nonexistent property
  26480. _getValue_unavailable: function () {},
  26481. _setValue_unavailable: function () {},
  26482. BindingType: {
  26483. Direct: 0,
  26484. EntireArray: 1,
  26485. ArrayElement: 2,
  26486. HasFromToArray: 3
  26487. },
  26488. Versioning: {
  26489. None: 0,
  26490. NeedsUpdate: 1,
  26491. MatrixWorldNeedsUpdate: 2
  26492. },
  26493. GetterByBindingType: [function getValue_direct(buffer, offset) {
  26494. buffer[offset] = this.node[this.propertyName];
  26495. }, function getValue_array(buffer, offset) {
  26496. var source = this.resolvedProperty;
  26497. for (var i = 0, n = source.length; i !== n; ++i) {
  26498. buffer[offset++] = source[i];
  26499. }
  26500. }, function getValue_arrayElement(buffer, offset) {
  26501. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26502. }, function getValue_toArray(buffer, offset) {
  26503. this.resolvedProperty.toArray(buffer, offset);
  26504. }],
  26505. SetterByBindingTypeAndVersioning: [[// Direct
  26506. function setValue_direct(buffer, offset) {
  26507. this.targetObject[this.propertyName] = buffer[offset];
  26508. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  26509. this.targetObject[this.propertyName] = buffer[offset];
  26510. this.targetObject.needsUpdate = true;
  26511. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26512. this.targetObject[this.propertyName] = buffer[offset];
  26513. this.targetObject.matrixWorldNeedsUpdate = true;
  26514. }], [// EntireArray
  26515. function setValue_array(buffer, offset) {
  26516. var dest = this.resolvedProperty;
  26517. for (var i = 0, n = dest.length; i !== n; ++i) {
  26518. dest[i] = buffer[offset++];
  26519. }
  26520. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  26521. var dest = this.resolvedProperty;
  26522. for (var i = 0, n = dest.length; i !== n; ++i) {
  26523. dest[i] = buffer[offset++];
  26524. }
  26525. this.targetObject.needsUpdate = true;
  26526. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26527. var dest = this.resolvedProperty;
  26528. for (var i = 0, n = dest.length; i !== n; ++i) {
  26529. dest[i] = buffer[offset++];
  26530. }
  26531. this.targetObject.matrixWorldNeedsUpdate = true;
  26532. }], [// ArrayElement
  26533. function setValue_arrayElement(buffer, offset) {
  26534. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26535. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26536. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26537. this.targetObject.needsUpdate = true;
  26538. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26539. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26540. this.targetObject.matrixWorldNeedsUpdate = true;
  26541. }], [// HasToFromArray
  26542. function setValue_fromArray(buffer, offset) {
  26543. this.resolvedProperty.fromArray(buffer, offset);
  26544. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26545. this.resolvedProperty.fromArray(buffer, offset);
  26546. this.targetObject.needsUpdate = true;
  26547. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26548. this.resolvedProperty.fromArray(buffer, offset);
  26549. this.targetObject.matrixWorldNeedsUpdate = true;
  26550. }]],
  26551. getValue: function getValue_unbound(targetArray, offset) {
  26552. this.bind();
  26553. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  26554. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26555. // prototype version of these methods with one that represents
  26556. // the bound state. When the property is not found, the methods
  26557. // become no-ops.
  26558. },
  26559. setValue: function getValue_unbound(sourceArray, offset) {
  26560. this.bind();
  26561. this.setValue(sourceArray, offset);
  26562. },
  26563. // create getter / setter pair for a property in the scene graph
  26564. bind: function () {
  26565. var targetObject = this.node,
  26566. parsedPath = this.parsedPath,
  26567. objectName = parsedPath.objectName,
  26568. propertyName = parsedPath.propertyName,
  26569. propertyIndex = parsedPath.propertyIndex;
  26570. if (!targetObject) {
  26571. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26572. this.node = targetObject;
  26573. } // set fail state so we can just 'return' on error
  26574. this.getValue = this._getValue_unavailable;
  26575. this.setValue = this._setValue_unavailable; // ensure there is a value node
  26576. if (!targetObject) {
  26577. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26578. return;
  26579. }
  26580. if (objectName) {
  26581. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26582. switch (objectName) {
  26583. case 'materials':
  26584. if (!targetObject.material) {
  26585. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26586. return;
  26587. }
  26588. if (!targetObject.material.materials) {
  26589. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  26590. return;
  26591. }
  26592. targetObject = targetObject.material.materials;
  26593. break;
  26594. case 'bones':
  26595. if (!targetObject.skeleton) {
  26596. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  26597. return;
  26598. } // potential future optimization: skip this if propertyIndex is already an integer
  26599. // and convert the integer string to a true integer.
  26600. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  26601. for (var i = 0; i < targetObject.length; i++) {
  26602. if (targetObject[i].name === objectIndex) {
  26603. objectIndex = i;
  26604. break;
  26605. }
  26606. }
  26607. break;
  26608. default:
  26609. if (targetObject[objectName] === undefined) {
  26610. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26611. return;
  26612. }
  26613. targetObject = targetObject[objectName];
  26614. }
  26615. if (objectIndex !== undefined) {
  26616. if (targetObject[objectIndex] === undefined) {
  26617. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26618. return;
  26619. }
  26620. targetObject = targetObject[objectIndex];
  26621. }
  26622. } // resolve property
  26623. var nodeProperty = targetObject[propertyName];
  26624. if (nodeProperty === undefined) {
  26625. var nodeName = parsedPath.nodeName;
  26626. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26627. return;
  26628. } // determine versioning scheme
  26629. var versioning = this.Versioning.None;
  26630. this.targetObject = targetObject;
  26631. if (targetObject.needsUpdate !== undefined) {
  26632. // material
  26633. versioning = this.Versioning.NeedsUpdate;
  26634. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26635. // node transform
  26636. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26637. } // determine how the property gets bound
  26638. var bindingType = this.BindingType.Direct;
  26639. if (propertyIndex !== undefined) {
  26640. // access a sub element of the property array (only primitives are supported right now)
  26641. if (propertyName === "morphTargetInfluences") {
  26642. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26643. // support resolving morphTarget names into indices.
  26644. if (!targetObject.geometry) {
  26645. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26646. return;
  26647. }
  26648. if (targetObject.geometry.isBufferGeometry) {
  26649. if (!targetObject.geometry.morphAttributes) {
  26650. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26651. return;
  26652. }
  26653. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  26654. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  26655. propertyIndex = i;
  26656. break;
  26657. }
  26658. }
  26659. } else {
  26660. if (!targetObject.geometry.morphTargets) {
  26661. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  26662. return;
  26663. }
  26664. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  26665. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  26666. propertyIndex = i;
  26667. break;
  26668. }
  26669. }
  26670. }
  26671. }
  26672. bindingType = this.BindingType.ArrayElement;
  26673. this.resolvedProperty = nodeProperty;
  26674. this.propertyIndex = propertyIndex;
  26675. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26676. // must use copy for Object3D.Euler/Quaternion
  26677. bindingType = this.BindingType.HasFromToArray;
  26678. this.resolvedProperty = nodeProperty;
  26679. } else if (Array.isArray(nodeProperty)) {
  26680. bindingType = this.BindingType.EntireArray;
  26681. this.resolvedProperty = nodeProperty;
  26682. } else {
  26683. this.propertyName = propertyName;
  26684. } // select getter / setter
  26685. this.getValue = this.GetterByBindingType[bindingType];
  26686. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26687. },
  26688. unbind: function () {
  26689. this.node = null; // back to the prototype version of getValue / setValue
  26690. // note: avoiding to mutate the shape of 'this' via 'delete'
  26691. this.getValue = this._getValue_unbound;
  26692. this.setValue = this._setValue_unbound;
  26693. }
  26694. }); //!\ DECLARE ALIAS AFTER assign prototype !
  26695. Object.assign(PropertyBinding.prototype, {
  26696. // initial state of these methods that calls 'bind'
  26697. _getValue_unbound: PropertyBinding.prototype.getValue,
  26698. _setValue_unbound: PropertyBinding.prototype.setValue
  26699. });
  26700. /**
  26701. *
  26702. * A group of objects that receives a shared animation state.
  26703. *
  26704. * Usage:
  26705. *
  26706. * - Add objects you would otherwise pass as 'root' to the
  26707. * constructor or the .clipAction method of AnimationMixer.
  26708. *
  26709. * - Instead pass this object as 'root'.
  26710. *
  26711. * - You can also add and remove objects later when the mixer
  26712. * is running.
  26713. *
  26714. * Note:
  26715. *
  26716. * Objects of this class appear as one object to the mixer,
  26717. * so cache control of the individual objects must be done
  26718. * on the group.
  26719. *
  26720. * Limitation:
  26721. *
  26722. * - The animated properties must be compatible among the
  26723. * all objects in the group.
  26724. *
  26725. * - A single property can either be controlled through a
  26726. * target group or directly, but not both.
  26727. *
  26728. * @author tschw
  26729. */
  26730. function AnimationObjectGroup() {
  26731. this.uuid = _Math.generateUUID(); // cached objects followed by the active ones
  26732. this._objects = Array.prototype.slice.call(arguments);
  26733. this.nCachedObjects_ = 0; // threshold
  26734. // note: read by PropertyBinding.Composite
  26735. var indices = {};
  26736. this._indicesByUUID = indices; // for bookkeeping
  26737. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26738. indices[arguments[i].uuid] = i;
  26739. }
  26740. this._paths = []; // inside: string
  26741. this._parsedPaths = []; // inside: { we don't care, here }
  26742. this._bindings = []; // inside: Array< PropertyBinding >
  26743. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26744. var scope = this;
  26745. this.stats = {
  26746. objects: {
  26747. get total() {
  26748. return scope._objects.length;
  26749. },
  26750. get inUse() {
  26751. return this.total - scope.nCachedObjects_;
  26752. }
  26753. },
  26754. get bindingsPerObject() {
  26755. return scope._bindings.length;
  26756. }
  26757. };
  26758. }
  26759. Object.assign(AnimationObjectGroup.prototype, {
  26760. isAnimationObjectGroup: true,
  26761. add: function () {
  26762. var objects = this._objects,
  26763. nObjects = objects.length,
  26764. nCachedObjects = this.nCachedObjects_,
  26765. indicesByUUID = this._indicesByUUID,
  26766. paths = this._paths,
  26767. parsedPaths = this._parsedPaths,
  26768. bindings = this._bindings,
  26769. nBindings = bindings.length,
  26770. knownObject = undefined;
  26771. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26772. var object = arguments[i],
  26773. uuid = object.uuid,
  26774. index = indicesByUUID[uuid];
  26775. if (index === undefined) {
  26776. // unknown object -> add it to the ACTIVE region
  26777. index = nObjects++;
  26778. indicesByUUID[uuid] = index;
  26779. objects.push(object); // accounting is done, now do the same for all bindings
  26780. for (var j = 0, m = nBindings; j !== m; ++j) {
  26781. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26782. }
  26783. } else if (index < nCachedObjects) {
  26784. knownObject = objects[index]; // move existing object to the ACTIVE region
  26785. var firstActiveIndex = --nCachedObjects,
  26786. lastCachedObject = objects[firstActiveIndex];
  26787. indicesByUUID[lastCachedObject.uuid] = index;
  26788. objects[index] = lastCachedObject;
  26789. indicesByUUID[uuid] = firstActiveIndex;
  26790. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26791. for (var j = 0, m = nBindings; j !== m; ++j) {
  26792. var bindingsForPath = bindings[j],
  26793. lastCached = bindingsForPath[firstActiveIndex],
  26794. binding = bindingsForPath[index];
  26795. bindingsForPath[index] = lastCached;
  26796. if (binding === undefined) {
  26797. // since we do not bother to create new bindings
  26798. // for objects that are cached, the binding may
  26799. // or may not exist
  26800. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26801. }
  26802. bindingsForPath[firstActiveIndex] = binding;
  26803. }
  26804. } else if (objects[index] !== knownObject) {
  26805. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26806. } // else the object is already where we want it to be
  26807. } // for arguments
  26808. this.nCachedObjects_ = nCachedObjects;
  26809. },
  26810. remove: function () {
  26811. var objects = this._objects,
  26812. nCachedObjects = this.nCachedObjects_,
  26813. indicesByUUID = this._indicesByUUID,
  26814. bindings = this._bindings,
  26815. nBindings = bindings.length;
  26816. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26817. var object = arguments[i],
  26818. uuid = object.uuid,
  26819. index = indicesByUUID[uuid];
  26820. if (index !== undefined && index >= nCachedObjects) {
  26821. // move existing object into the CACHED region
  26822. var lastCachedIndex = nCachedObjects++,
  26823. firstActiveObject = objects[lastCachedIndex];
  26824. indicesByUUID[firstActiveObject.uuid] = index;
  26825. objects[index] = firstActiveObject;
  26826. indicesByUUID[uuid] = lastCachedIndex;
  26827. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26828. for (var j = 0, m = nBindings; j !== m; ++j) {
  26829. var bindingsForPath = bindings[j],
  26830. firstActive = bindingsForPath[lastCachedIndex],
  26831. binding = bindingsForPath[index];
  26832. bindingsForPath[index] = firstActive;
  26833. bindingsForPath[lastCachedIndex] = binding;
  26834. }
  26835. }
  26836. } // for arguments
  26837. this.nCachedObjects_ = nCachedObjects;
  26838. },
  26839. // remove & forget
  26840. uncache: function () {
  26841. var objects = this._objects,
  26842. nObjects = objects.length,
  26843. nCachedObjects = this.nCachedObjects_,
  26844. indicesByUUID = this._indicesByUUID,
  26845. bindings = this._bindings,
  26846. nBindings = bindings.length;
  26847. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26848. var object = arguments[i],
  26849. uuid = object.uuid,
  26850. index = indicesByUUID[uuid];
  26851. if (index !== undefined) {
  26852. delete indicesByUUID[uuid];
  26853. if (index < nCachedObjects) {
  26854. // object is cached, shrink the CACHED region
  26855. var firstActiveIndex = --nCachedObjects,
  26856. lastCachedObject = objects[firstActiveIndex],
  26857. lastIndex = --nObjects,
  26858. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26859. indicesByUUID[lastCachedObject.uuid] = index;
  26860. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26861. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26862. objects[firstActiveIndex] = lastObject;
  26863. objects.pop(); // accounting is done, now do the same for all bindings
  26864. for (var j = 0, m = nBindings; j !== m; ++j) {
  26865. var bindingsForPath = bindings[j],
  26866. lastCached = bindingsForPath[firstActiveIndex],
  26867. last = bindingsForPath[lastIndex];
  26868. bindingsForPath[index] = lastCached;
  26869. bindingsForPath[firstActiveIndex] = last;
  26870. bindingsForPath.pop();
  26871. }
  26872. } else {
  26873. // object is active, just swap with the last and pop
  26874. var lastIndex = --nObjects,
  26875. lastObject = objects[lastIndex];
  26876. indicesByUUID[lastObject.uuid] = index;
  26877. objects[index] = lastObject;
  26878. objects.pop(); // accounting is done, now do the same for all bindings
  26879. for (var j = 0, m = nBindings; j !== m; ++j) {
  26880. var bindingsForPath = bindings[j];
  26881. bindingsForPath[index] = bindingsForPath[lastIndex];
  26882. bindingsForPath.pop();
  26883. }
  26884. } // cached or active
  26885. } // if object is known
  26886. } // for arguments
  26887. this.nCachedObjects_ = nCachedObjects;
  26888. },
  26889. // Internal interface used by befriended PropertyBinding.Composite:
  26890. subscribe_: function (path, parsedPath) {
  26891. // returns an array of bindings for the given path that is changed
  26892. // according to the contained objects in the group
  26893. var indicesByPath = this._bindingsIndicesByPath,
  26894. index = indicesByPath[path],
  26895. bindings = this._bindings;
  26896. if (index !== undefined) return bindings[index];
  26897. var paths = this._paths,
  26898. parsedPaths = this._parsedPaths,
  26899. objects = this._objects,
  26900. nObjects = objects.length,
  26901. nCachedObjects = this.nCachedObjects_,
  26902. bindingsForPath = new Array(nObjects);
  26903. index = bindings.length;
  26904. indicesByPath[path] = index;
  26905. paths.push(path);
  26906. parsedPaths.push(parsedPath);
  26907. bindings.push(bindingsForPath);
  26908. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26909. var object = objects[i];
  26910. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26911. }
  26912. return bindingsForPath;
  26913. },
  26914. unsubscribe_: function (path) {
  26915. // tells the group to forget about a property path and no longer
  26916. // update the array previously obtained with 'subscribe_'
  26917. var indicesByPath = this._bindingsIndicesByPath,
  26918. index = indicesByPath[path];
  26919. if (index !== undefined) {
  26920. var paths = this._paths,
  26921. parsedPaths = this._parsedPaths,
  26922. bindings = this._bindings,
  26923. lastBindingsIndex = bindings.length - 1,
  26924. lastBindings = bindings[lastBindingsIndex],
  26925. lastBindingsPath = path[lastBindingsIndex];
  26926. indicesByPath[lastBindingsPath] = index;
  26927. bindings[index] = lastBindings;
  26928. bindings.pop();
  26929. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26930. parsedPaths.pop();
  26931. paths[index] = paths[lastBindingsIndex];
  26932. paths.pop();
  26933. }
  26934. }
  26935. });
  26936. /**
  26937. *
  26938. * Action provided by AnimationMixer for scheduling clip playback on specific
  26939. * objects.
  26940. *
  26941. * @author Ben Houston / http://clara.io/
  26942. * @author David Sarno / http://lighthaus.us/
  26943. * @author tschw
  26944. *
  26945. */
  26946. function AnimationAction(mixer, clip, localRoot) {
  26947. this._mixer = mixer;
  26948. this._clip = clip;
  26949. this._localRoot = localRoot || null;
  26950. var tracks = clip.tracks,
  26951. nTracks = tracks.length,
  26952. interpolants = new Array(nTracks);
  26953. var interpolantSettings = {
  26954. endingStart: ZeroCurvatureEnding,
  26955. endingEnd: ZeroCurvatureEnding
  26956. };
  26957. for (var i = 0; i !== nTracks; ++i) {
  26958. var interpolant = tracks[i].createInterpolant(null);
  26959. interpolants[i] = interpolant;
  26960. interpolant.settings = interpolantSettings;
  26961. }
  26962. this._interpolantSettings = interpolantSettings;
  26963. this._interpolants = interpolants; // bound by the mixer
  26964. // inside: PropertyMixer (managed by the mixer)
  26965. this._propertyBindings = new Array(nTracks);
  26966. this._cacheIndex = null; // for the memory manager
  26967. this._byClipCacheIndex = null; // for the memory manager
  26968. this._timeScaleInterpolant = null;
  26969. this._weightInterpolant = null;
  26970. this.loop = LoopRepeat;
  26971. this._loopCount = -1; // global mixer time when the action is to be started
  26972. // it's set back to 'null' upon start of the action
  26973. this._startTime = null; // scaled local time of the action
  26974. // gets clamped or wrapped to 0..clip.duration according to loop
  26975. this.time = 0;
  26976. this.timeScale = 1;
  26977. this._effectiveTimeScale = 1;
  26978. this.weight = 1;
  26979. this._effectiveWeight = 1;
  26980. this.repetitions = Infinity; // no. of repetitions when looping
  26981. this.paused = false; // true -> zero effective time scale
  26982. this.enabled = true; // false -> zero effective weight
  26983. this.clampWhenFinished = false; // keep feeding the last frame?
  26984. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26985. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26986. }
  26987. Object.assign(AnimationAction.prototype, {
  26988. // State & Scheduling
  26989. play: function () {
  26990. this._mixer._activateAction(this);
  26991. return this;
  26992. },
  26993. stop: function () {
  26994. this._mixer._deactivateAction(this);
  26995. return this.reset();
  26996. },
  26997. reset: function () {
  26998. this.paused = false;
  26999. this.enabled = true;
  27000. this.time = 0; // restart clip
  27001. this._loopCount = -1; // forget previous loops
  27002. this._startTime = null; // forget scheduling
  27003. return this.stopFading().stopWarping();
  27004. },
  27005. isRunning: function () {
  27006. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  27007. },
  27008. // return true when play has been called
  27009. isScheduled: function () {
  27010. return this._mixer._isActiveAction(this);
  27011. },
  27012. startAt: function (time) {
  27013. this._startTime = time;
  27014. return this;
  27015. },
  27016. setLoop: function (mode, repetitions) {
  27017. this.loop = mode;
  27018. this.repetitions = repetitions;
  27019. return this;
  27020. },
  27021. // Weight
  27022. // set the weight stopping any scheduled fading
  27023. // although .enabled = false yields an effective weight of zero, this
  27024. // method does *not* change .enabled, because it would be confusing
  27025. setEffectiveWeight: function (weight) {
  27026. this.weight = weight; // note: same logic as when updated at runtime
  27027. this._effectiveWeight = this.enabled ? weight : 0;
  27028. return this.stopFading();
  27029. },
  27030. // return the weight considering fading and .enabled
  27031. getEffectiveWeight: function () {
  27032. return this._effectiveWeight;
  27033. },
  27034. fadeIn: function (duration) {
  27035. return this._scheduleFading(duration, 0, 1);
  27036. },
  27037. fadeOut: function (duration) {
  27038. return this._scheduleFading(duration, 1, 0);
  27039. },
  27040. crossFadeFrom: function (fadeOutAction, duration, warp) {
  27041. fadeOutAction.fadeOut(duration);
  27042. this.fadeIn(duration);
  27043. if (warp) {
  27044. var fadeInDuration = this._clip.duration,
  27045. fadeOutDuration = fadeOutAction._clip.duration,
  27046. startEndRatio = fadeOutDuration / fadeInDuration,
  27047. endStartRatio = fadeInDuration / fadeOutDuration;
  27048. fadeOutAction.warp(1.0, startEndRatio, duration);
  27049. this.warp(endStartRatio, 1.0, duration);
  27050. }
  27051. return this;
  27052. },
  27053. crossFadeTo: function (fadeInAction, duration, warp) {
  27054. return fadeInAction.crossFadeFrom(this, duration, warp);
  27055. },
  27056. stopFading: function () {
  27057. var weightInterpolant = this._weightInterpolant;
  27058. if (weightInterpolant !== null) {
  27059. this._weightInterpolant = null;
  27060. this._mixer._takeBackControlInterpolant(weightInterpolant);
  27061. }
  27062. return this;
  27063. },
  27064. // Time Scale Control
  27065. // set the time scale stopping any scheduled warping
  27066. // although .paused = true yields an effective time scale of zero, this
  27067. // method does *not* change .paused, because it would be confusing
  27068. setEffectiveTimeScale: function (timeScale) {
  27069. this.timeScale = timeScale;
  27070. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27071. return this.stopWarping();
  27072. },
  27073. // return the time scale considering warping and .paused
  27074. getEffectiveTimeScale: function () {
  27075. return this._effectiveTimeScale;
  27076. },
  27077. setDuration: function (duration) {
  27078. this.timeScale = this._clip.duration / duration;
  27079. return this.stopWarping();
  27080. },
  27081. syncWith: function (action) {
  27082. this.time = action.time;
  27083. this.timeScale = action.timeScale;
  27084. return this.stopWarping();
  27085. },
  27086. halt: function (duration) {
  27087. return this.warp(this._effectiveTimeScale, 0, duration);
  27088. },
  27089. warp: function (startTimeScale, endTimeScale, duration) {
  27090. var mixer = this._mixer,
  27091. now = mixer.time,
  27092. interpolant = this._timeScaleInterpolant,
  27093. timeScale = this.timeScale;
  27094. if (interpolant === null) {
  27095. interpolant = mixer._lendControlInterpolant();
  27096. this._timeScaleInterpolant = interpolant;
  27097. }
  27098. var times = interpolant.parameterPositions,
  27099. values = interpolant.sampleValues;
  27100. times[0] = now;
  27101. times[1] = now + duration;
  27102. values[0] = startTimeScale / timeScale;
  27103. values[1] = endTimeScale / timeScale;
  27104. return this;
  27105. },
  27106. stopWarping: function () {
  27107. var timeScaleInterpolant = this._timeScaleInterpolant;
  27108. if (timeScaleInterpolant !== null) {
  27109. this._timeScaleInterpolant = null;
  27110. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  27111. }
  27112. return this;
  27113. },
  27114. // Object Accessors
  27115. getMixer: function () {
  27116. return this._mixer;
  27117. },
  27118. getClip: function () {
  27119. return this._clip;
  27120. },
  27121. getRoot: function () {
  27122. return this._localRoot || this._mixer._root;
  27123. },
  27124. // Interna
  27125. _update: function (time, deltaTime, timeDirection, accuIndex) {
  27126. // called by the mixer
  27127. if (!this.enabled) {
  27128. // call ._updateWeight() to update ._effectiveWeight
  27129. this._updateWeight(time);
  27130. return;
  27131. }
  27132. var startTime = this._startTime;
  27133. if (startTime !== null) {
  27134. // check for scheduled start of action
  27135. var timeRunning = (time - startTime) * timeDirection;
  27136. if (timeRunning < 0 || timeDirection === 0) {
  27137. return; // yet to come / don't decide when delta = 0
  27138. } // start
  27139. this._startTime = null; // unschedule
  27140. deltaTime = timeDirection * timeRunning;
  27141. } // apply time scale and advance time
  27142. deltaTime *= this._updateTimeScale(time);
  27143. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  27144. // an effective weight of 0
  27145. var weight = this._updateWeight(time);
  27146. if (weight > 0) {
  27147. var interpolants = this._interpolants;
  27148. var propertyMixers = this._propertyBindings;
  27149. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  27150. interpolants[j].evaluate(clipTime);
  27151. propertyMixers[j].accumulate(accuIndex, weight);
  27152. }
  27153. }
  27154. },
  27155. _updateWeight: function (time) {
  27156. var weight = 0;
  27157. if (this.enabled) {
  27158. weight = this.weight;
  27159. var interpolant = this._weightInterpolant;
  27160. if (interpolant !== null) {
  27161. var interpolantValue = interpolant.evaluate(time)[0];
  27162. weight *= interpolantValue;
  27163. if (time > interpolant.parameterPositions[1]) {
  27164. this.stopFading();
  27165. if (interpolantValue === 0) {
  27166. // faded out, disable
  27167. this.enabled = false;
  27168. }
  27169. }
  27170. }
  27171. }
  27172. this._effectiveWeight = weight;
  27173. return weight;
  27174. },
  27175. _updateTimeScale: function (time) {
  27176. var timeScale = 0;
  27177. if (!this.paused) {
  27178. timeScale = this.timeScale;
  27179. var interpolant = this._timeScaleInterpolant;
  27180. if (interpolant !== null) {
  27181. var interpolantValue = interpolant.evaluate(time)[0];
  27182. timeScale *= interpolantValue;
  27183. if (time > interpolant.parameterPositions[1]) {
  27184. this.stopWarping();
  27185. if (timeScale === 0) {
  27186. // motion has halted, pause
  27187. this.paused = true;
  27188. } else {
  27189. // warp done - apply final time scale
  27190. this.timeScale = timeScale;
  27191. }
  27192. }
  27193. }
  27194. }
  27195. this._effectiveTimeScale = timeScale;
  27196. return timeScale;
  27197. },
  27198. _updateTime: function (deltaTime) {
  27199. var time = this.time + deltaTime;
  27200. var duration = this._clip.duration;
  27201. var loop = this.loop;
  27202. var loopCount = this._loopCount;
  27203. var pingPong = loop === LoopPingPong;
  27204. if (deltaTime === 0) {
  27205. if (loopCount === -1) return time;
  27206. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27207. }
  27208. if (loop === LoopOnce) {
  27209. if (loopCount === -1) {
  27210. // just started
  27211. this._loopCount = 0;
  27212. this._setEndings(true, true, false);
  27213. }
  27214. handle_stop: {
  27215. if (time >= duration) {
  27216. time = duration;
  27217. } else if (time < 0) {
  27218. time = 0;
  27219. } else {
  27220. this.time = time;
  27221. break handle_stop;
  27222. }
  27223. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27224. this.time = time;
  27225. this._mixer.dispatchEvent({
  27226. type: 'finished',
  27227. action: this,
  27228. direction: deltaTime < 0 ? -1 : 1
  27229. });
  27230. }
  27231. } else {
  27232. // repetitive Repeat or PingPong
  27233. if (loopCount === -1) {
  27234. // just started
  27235. if (deltaTime >= 0) {
  27236. loopCount = 0;
  27237. this._setEndings(true, this.repetitions === 0, pingPong);
  27238. } else {
  27239. // when looping in reverse direction, the initial
  27240. // transition through zero counts as a repetition,
  27241. // so leave loopCount at -1
  27242. this._setEndings(this.repetitions === 0, true, pingPong);
  27243. }
  27244. }
  27245. if (time >= duration || time < 0) {
  27246. // wrap around
  27247. var loopDelta = Math.floor(time / duration); // signed
  27248. time -= duration * loopDelta;
  27249. loopCount += Math.abs(loopDelta);
  27250. var pending = this.repetitions - loopCount;
  27251. if (pending <= 0) {
  27252. // have to stop (switch state, clamp time, fire event)
  27253. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27254. time = deltaTime > 0 ? duration : 0;
  27255. this.time = time;
  27256. this._mixer.dispatchEvent({
  27257. type: 'finished',
  27258. action: this,
  27259. direction: deltaTime > 0 ? 1 : -1
  27260. });
  27261. } else {
  27262. // keep running
  27263. if (pending === 1) {
  27264. // entering the last round
  27265. var atStart = deltaTime < 0;
  27266. this._setEndings(atStart, !atStart, pingPong);
  27267. } else {
  27268. this._setEndings(false, false, pingPong);
  27269. }
  27270. this._loopCount = loopCount;
  27271. this.time = time;
  27272. this._mixer.dispatchEvent({
  27273. type: 'loop',
  27274. action: this,
  27275. loopDelta: loopDelta
  27276. });
  27277. }
  27278. } else {
  27279. this.time = time;
  27280. }
  27281. if (pingPong && (loopCount & 1) === 1) {
  27282. // invert time for the "pong round"
  27283. return duration - time;
  27284. }
  27285. }
  27286. return time;
  27287. },
  27288. _setEndings: function (atStart, atEnd, pingPong) {
  27289. var settings = this._interpolantSettings;
  27290. if (pingPong) {
  27291. settings.endingStart = ZeroSlopeEnding;
  27292. settings.endingEnd = ZeroSlopeEnding;
  27293. } else {
  27294. // assuming for LoopOnce atStart == atEnd == true
  27295. if (atStart) {
  27296. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27297. } else {
  27298. settings.endingStart = WrapAroundEnding;
  27299. }
  27300. if (atEnd) {
  27301. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27302. } else {
  27303. settings.endingEnd = WrapAroundEnding;
  27304. }
  27305. }
  27306. },
  27307. _scheduleFading: function (duration, weightNow, weightThen) {
  27308. var mixer = this._mixer,
  27309. now = mixer.time,
  27310. interpolant = this._weightInterpolant;
  27311. if (interpolant === null) {
  27312. interpolant = mixer._lendControlInterpolant();
  27313. this._weightInterpolant = interpolant;
  27314. }
  27315. var times = interpolant.parameterPositions,
  27316. values = interpolant.sampleValues;
  27317. times[0] = now;
  27318. values[0] = weightNow;
  27319. times[1] = now + duration;
  27320. values[1] = weightThen;
  27321. return this;
  27322. }
  27323. });
  27324. /**
  27325. *
  27326. * Player for AnimationClips.
  27327. *
  27328. *
  27329. * @author Ben Houston / http://clara.io/
  27330. * @author David Sarno / http://lighthaus.us/
  27331. * @author tschw
  27332. */
  27333. function AnimationMixer(root) {
  27334. this._root = root;
  27335. this._initMemoryManager();
  27336. this._accuIndex = 0;
  27337. this.time = 0;
  27338. this.timeScale = 1.0;
  27339. }
  27340. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  27341. constructor: AnimationMixer,
  27342. _bindAction: function (action, prototypeAction) {
  27343. var root = action._localRoot || this._root,
  27344. tracks = action._clip.tracks,
  27345. nTracks = tracks.length,
  27346. bindings = action._propertyBindings,
  27347. interpolants = action._interpolants,
  27348. rootUuid = root.uuid,
  27349. bindingsByRoot = this._bindingsByRootAndName,
  27350. bindingsByName = bindingsByRoot[rootUuid];
  27351. if (bindingsByName === undefined) {
  27352. bindingsByName = {};
  27353. bindingsByRoot[rootUuid] = bindingsByName;
  27354. }
  27355. for (var i = 0; i !== nTracks; ++i) {
  27356. var track = tracks[i],
  27357. trackName = track.name,
  27358. binding = bindingsByName[trackName];
  27359. if (binding !== undefined) {
  27360. bindings[i] = binding;
  27361. } else {
  27362. binding = bindings[i];
  27363. if (binding !== undefined) {
  27364. // existing binding, make sure the cache knows
  27365. if (binding._cacheIndex === null) {
  27366. ++binding.referenceCount;
  27367. this._addInactiveBinding(binding, rootUuid, trackName);
  27368. }
  27369. continue;
  27370. }
  27371. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27372. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27373. ++binding.referenceCount;
  27374. this._addInactiveBinding(binding, rootUuid, trackName);
  27375. bindings[i] = binding;
  27376. }
  27377. interpolants[i].resultBuffer = binding.buffer;
  27378. }
  27379. },
  27380. _activateAction: function (action) {
  27381. if (!this._isActiveAction(action)) {
  27382. if (action._cacheIndex === null) {
  27383. // this action has been forgotten by the cache, but the user
  27384. // appears to be still using it -> rebind
  27385. var rootUuid = (action._localRoot || this._root).uuid,
  27386. clipUuid = action._clip.uuid,
  27387. actionsForClip = this._actionsByClip[clipUuid];
  27388. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27389. this._addInactiveAction(action, clipUuid, rootUuid);
  27390. }
  27391. var bindings = action._propertyBindings; // increment reference counts / sort out state
  27392. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27393. var binding = bindings[i];
  27394. if (binding.useCount++ === 0) {
  27395. this._lendBinding(binding);
  27396. binding.saveOriginalState();
  27397. }
  27398. }
  27399. this._lendAction(action);
  27400. }
  27401. },
  27402. _deactivateAction: function (action) {
  27403. if (this._isActiveAction(action)) {
  27404. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  27405. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27406. var binding = bindings[i];
  27407. if (--binding.useCount === 0) {
  27408. binding.restoreOriginalState();
  27409. this._takeBackBinding(binding);
  27410. }
  27411. }
  27412. this._takeBackAction(action);
  27413. }
  27414. },
  27415. // Memory manager
  27416. _initMemoryManager: function () {
  27417. this._actions = []; // 'nActiveActions' followed by inactive ones
  27418. this._nActiveActions = 0;
  27419. this._actionsByClip = {}; // inside:
  27420. // {
  27421. // knownActions: Array< AnimationAction > - used as prototypes
  27422. // actionByRoot: AnimationAction - lookup
  27423. // }
  27424. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27425. this._nActiveBindings = 0;
  27426. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27427. this._controlInterpolants = []; // same game as above
  27428. this._nActiveControlInterpolants = 0;
  27429. var scope = this;
  27430. this.stats = {
  27431. actions: {
  27432. get total() {
  27433. return scope._actions.length;
  27434. },
  27435. get inUse() {
  27436. return scope._nActiveActions;
  27437. }
  27438. },
  27439. bindings: {
  27440. get total() {
  27441. return scope._bindings.length;
  27442. },
  27443. get inUse() {
  27444. return scope._nActiveBindings;
  27445. }
  27446. },
  27447. controlInterpolants: {
  27448. get total() {
  27449. return scope._controlInterpolants.length;
  27450. },
  27451. get inUse() {
  27452. return scope._nActiveControlInterpolants;
  27453. }
  27454. }
  27455. };
  27456. },
  27457. // Memory management for AnimationAction objects
  27458. _isActiveAction: function (action) {
  27459. var index = action._cacheIndex;
  27460. return index !== null && index < this._nActiveActions;
  27461. },
  27462. _addInactiveAction: function (action, clipUuid, rootUuid) {
  27463. var actions = this._actions,
  27464. actionsByClip = this._actionsByClip,
  27465. actionsForClip = actionsByClip[clipUuid];
  27466. if (actionsForClip === undefined) {
  27467. actionsForClip = {
  27468. knownActions: [action],
  27469. actionByRoot: {}
  27470. };
  27471. action._byClipCacheIndex = 0;
  27472. actionsByClip[clipUuid] = actionsForClip;
  27473. } else {
  27474. var knownActions = actionsForClip.knownActions;
  27475. action._byClipCacheIndex = knownActions.length;
  27476. knownActions.push(action);
  27477. }
  27478. action._cacheIndex = actions.length;
  27479. actions.push(action);
  27480. actionsForClip.actionByRoot[rootUuid] = action;
  27481. },
  27482. _removeInactiveAction: function (action) {
  27483. var actions = this._actions,
  27484. lastInactiveAction = actions[actions.length - 1],
  27485. cacheIndex = action._cacheIndex;
  27486. lastInactiveAction._cacheIndex = cacheIndex;
  27487. actions[cacheIndex] = lastInactiveAction;
  27488. actions.pop();
  27489. action._cacheIndex = null;
  27490. var clipUuid = action._clip.uuid,
  27491. actionsByClip = this._actionsByClip,
  27492. actionsForClip = actionsByClip[clipUuid],
  27493. knownActionsForClip = actionsForClip.knownActions,
  27494. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27495. byClipCacheIndex = action._byClipCacheIndex;
  27496. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27497. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27498. knownActionsForClip.pop();
  27499. action._byClipCacheIndex = null;
  27500. var actionByRoot = actionsForClip.actionByRoot,
  27501. rootUuid = (action._localRoot || this._root).uuid;
  27502. delete actionByRoot[rootUuid];
  27503. if (knownActionsForClip.length === 0) {
  27504. delete actionsByClip[clipUuid];
  27505. }
  27506. this._removeInactiveBindingsForAction(action);
  27507. },
  27508. _removeInactiveBindingsForAction: function (action) {
  27509. var bindings = action._propertyBindings;
  27510. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27511. var binding = bindings[i];
  27512. if (--binding.referenceCount === 0) {
  27513. this._removeInactiveBinding(binding);
  27514. }
  27515. }
  27516. },
  27517. _lendAction: function (action) {
  27518. // [ active actions | inactive actions ]
  27519. // [ active actions >| inactive actions ]
  27520. // s a
  27521. // <-swap->
  27522. // a s
  27523. var actions = this._actions,
  27524. prevIndex = action._cacheIndex,
  27525. lastActiveIndex = this._nActiveActions++,
  27526. firstInactiveAction = actions[lastActiveIndex];
  27527. action._cacheIndex = lastActiveIndex;
  27528. actions[lastActiveIndex] = action;
  27529. firstInactiveAction._cacheIndex = prevIndex;
  27530. actions[prevIndex] = firstInactiveAction;
  27531. },
  27532. _takeBackAction: function (action) {
  27533. // [ active actions | inactive actions ]
  27534. // [ active actions |< inactive actions ]
  27535. // a s
  27536. // <-swap->
  27537. // s a
  27538. var actions = this._actions,
  27539. prevIndex = action._cacheIndex,
  27540. firstInactiveIndex = --this._nActiveActions,
  27541. lastActiveAction = actions[firstInactiveIndex];
  27542. action._cacheIndex = firstInactiveIndex;
  27543. actions[firstInactiveIndex] = action;
  27544. lastActiveAction._cacheIndex = prevIndex;
  27545. actions[prevIndex] = lastActiveAction;
  27546. },
  27547. // Memory management for PropertyMixer objects
  27548. _addInactiveBinding: function (binding, rootUuid, trackName) {
  27549. var bindingsByRoot = this._bindingsByRootAndName,
  27550. bindingByName = bindingsByRoot[rootUuid],
  27551. bindings = this._bindings;
  27552. if (bindingByName === undefined) {
  27553. bindingByName = {};
  27554. bindingsByRoot[rootUuid] = bindingByName;
  27555. }
  27556. bindingByName[trackName] = binding;
  27557. binding._cacheIndex = bindings.length;
  27558. bindings.push(binding);
  27559. },
  27560. _removeInactiveBinding: function (binding) {
  27561. var bindings = this._bindings,
  27562. propBinding = binding.binding,
  27563. rootUuid = propBinding.rootNode.uuid,
  27564. trackName = propBinding.path,
  27565. bindingsByRoot = this._bindingsByRootAndName,
  27566. bindingByName = bindingsByRoot[rootUuid],
  27567. lastInactiveBinding = bindings[bindings.length - 1],
  27568. cacheIndex = binding._cacheIndex;
  27569. lastInactiveBinding._cacheIndex = cacheIndex;
  27570. bindings[cacheIndex] = lastInactiveBinding;
  27571. bindings.pop();
  27572. delete bindingByName[trackName];
  27573. if (Object.keys(bindingByName).length === 0) {
  27574. delete bindingsByRoot[rootUuid];
  27575. }
  27576. },
  27577. _lendBinding: function (binding) {
  27578. var bindings = this._bindings,
  27579. prevIndex = binding._cacheIndex,
  27580. lastActiveIndex = this._nActiveBindings++,
  27581. firstInactiveBinding = bindings[lastActiveIndex];
  27582. binding._cacheIndex = lastActiveIndex;
  27583. bindings[lastActiveIndex] = binding;
  27584. firstInactiveBinding._cacheIndex = prevIndex;
  27585. bindings[prevIndex] = firstInactiveBinding;
  27586. },
  27587. _takeBackBinding: function (binding) {
  27588. var bindings = this._bindings,
  27589. prevIndex = binding._cacheIndex,
  27590. firstInactiveIndex = --this._nActiveBindings,
  27591. lastActiveBinding = bindings[firstInactiveIndex];
  27592. binding._cacheIndex = firstInactiveIndex;
  27593. bindings[firstInactiveIndex] = binding;
  27594. lastActiveBinding._cacheIndex = prevIndex;
  27595. bindings[prevIndex] = lastActiveBinding;
  27596. },
  27597. // Memory management of Interpolants for weight and time scale
  27598. _lendControlInterpolant: function () {
  27599. var interpolants = this._controlInterpolants,
  27600. lastActiveIndex = this._nActiveControlInterpolants++,
  27601. interpolant = interpolants[lastActiveIndex];
  27602. if (interpolant === undefined) {
  27603. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  27604. interpolant.__cacheIndex = lastActiveIndex;
  27605. interpolants[lastActiveIndex] = interpolant;
  27606. }
  27607. return interpolant;
  27608. },
  27609. _takeBackControlInterpolant: function (interpolant) {
  27610. var interpolants = this._controlInterpolants,
  27611. prevIndex = interpolant.__cacheIndex,
  27612. firstInactiveIndex = --this._nActiveControlInterpolants,
  27613. lastActiveInterpolant = interpolants[firstInactiveIndex];
  27614. interpolant.__cacheIndex = firstInactiveIndex;
  27615. interpolants[firstInactiveIndex] = interpolant;
  27616. lastActiveInterpolant.__cacheIndex = prevIndex;
  27617. interpolants[prevIndex] = lastActiveInterpolant;
  27618. },
  27619. _controlInterpolantsResultBuffer: new Float32Array(1),
  27620. // return an action for a clip optionally using a custom root target
  27621. // object (this method allocates a lot of dynamic memory in case a
  27622. // previously unknown clip/root combination is specified)
  27623. clipAction: function (clip, optionalRoot) {
  27624. var root = optionalRoot || this._root,
  27625. rootUuid = root.uuid,
  27626. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27627. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  27628. actionsForClip = this._actionsByClip[clipUuid],
  27629. prototypeAction = null;
  27630. if (actionsForClip !== undefined) {
  27631. var existingAction = actionsForClip.actionByRoot[rootUuid];
  27632. if (existingAction !== undefined) {
  27633. return existingAction;
  27634. } // we know the clip, so we don't have to parse all
  27635. // the bindings again but can just copy
  27636. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27637. if (clipObject === null) clipObject = prototypeAction._clip;
  27638. } // clip must be known when specified via string
  27639. if (clipObject === null) return null; // allocate all resources required to run it
  27640. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  27641. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27642. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27643. return newAction;
  27644. },
  27645. // get an existing action
  27646. existingAction: function (clip, optionalRoot) {
  27647. var root = optionalRoot || this._root,
  27648. rootUuid = root.uuid,
  27649. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27650. clipUuid = clipObject ? clipObject.uuid : clip,
  27651. actionsForClip = this._actionsByClip[clipUuid];
  27652. if (actionsForClip !== undefined) {
  27653. return actionsForClip.actionByRoot[rootUuid] || null;
  27654. }
  27655. return null;
  27656. },
  27657. // deactivates all previously scheduled actions
  27658. stopAllAction: function () {
  27659. var actions = this._actions,
  27660. nActions = this._nActiveActions,
  27661. bindings = this._bindings,
  27662. nBindings = this._nActiveBindings;
  27663. this._nActiveActions = 0;
  27664. this._nActiveBindings = 0;
  27665. for (var i = 0; i !== nActions; ++i) {
  27666. actions[i].reset();
  27667. }
  27668. for (var i = 0; i !== nBindings; ++i) {
  27669. bindings[i].useCount = 0;
  27670. }
  27671. return this;
  27672. },
  27673. // advance the time and update apply the animation
  27674. update: function (deltaTime) {
  27675. deltaTime *= this.timeScale;
  27676. var actions = this._actions,
  27677. nActions = this._nActiveActions,
  27678. time = this.time += deltaTime,
  27679. timeDirection = Math.sign(deltaTime),
  27680. accuIndex = this._accuIndex ^= 1; // run active actions
  27681. for (var i = 0; i !== nActions; ++i) {
  27682. var action = actions[i];
  27683. action._update(time, deltaTime, timeDirection, accuIndex);
  27684. } // update scene graph
  27685. var bindings = this._bindings,
  27686. nBindings = this._nActiveBindings;
  27687. for (var i = 0; i !== nBindings; ++i) {
  27688. bindings[i].apply(accuIndex);
  27689. }
  27690. return this;
  27691. },
  27692. // Allows you to seek to a specific time in an animation.
  27693. setTime: function (timeInSeconds) {
  27694. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27695. for (var i = 0; i < this._actions.length; i++) {
  27696. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27697. }
  27698. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27699. },
  27700. // return this mixer's root target object
  27701. getRoot: function () {
  27702. return this._root;
  27703. },
  27704. // free all resources specific to a particular clip
  27705. uncacheClip: function (clip) {
  27706. var actions = this._actions,
  27707. clipUuid = clip.uuid,
  27708. actionsByClip = this._actionsByClip,
  27709. actionsForClip = actionsByClip[clipUuid];
  27710. if (actionsForClip !== undefined) {
  27711. // note: just calling _removeInactiveAction would mess up the
  27712. // iteration state and also require updating the state we can
  27713. // just throw away
  27714. var actionsToRemove = actionsForClip.knownActions;
  27715. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27716. var action = actionsToRemove[i];
  27717. this._deactivateAction(action);
  27718. var cacheIndex = action._cacheIndex,
  27719. lastInactiveAction = actions[actions.length - 1];
  27720. action._cacheIndex = null;
  27721. action._byClipCacheIndex = null;
  27722. lastInactiveAction._cacheIndex = cacheIndex;
  27723. actions[cacheIndex] = lastInactiveAction;
  27724. actions.pop();
  27725. this._removeInactiveBindingsForAction(action);
  27726. }
  27727. delete actionsByClip[clipUuid];
  27728. }
  27729. },
  27730. // free all resources specific to a particular root target object
  27731. uncacheRoot: function (root) {
  27732. var rootUuid = root.uuid,
  27733. actionsByClip = this._actionsByClip;
  27734. for (var clipUuid in actionsByClip) {
  27735. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27736. action = actionByRoot[rootUuid];
  27737. if (action !== undefined) {
  27738. this._deactivateAction(action);
  27739. this._removeInactiveAction(action);
  27740. }
  27741. }
  27742. var bindingsByRoot = this._bindingsByRootAndName,
  27743. bindingByName = bindingsByRoot[rootUuid];
  27744. if (bindingByName !== undefined) {
  27745. for (var trackName in bindingByName) {
  27746. var binding = bindingByName[trackName];
  27747. binding.restoreOriginalState();
  27748. this._removeInactiveBinding(binding);
  27749. }
  27750. }
  27751. },
  27752. // remove a targeted clip from the cache
  27753. uncacheAction: function (clip, optionalRoot) {
  27754. var action = this.existingAction(clip, optionalRoot);
  27755. if (action !== null) {
  27756. this._deactivateAction(action);
  27757. this._removeInactiveAction(action);
  27758. }
  27759. }
  27760. });
  27761. /**
  27762. * @author mrdoob / http://mrdoob.com/
  27763. */
  27764. function Uniform(value) {
  27765. if (typeof value === 'string') {
  27766. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27767. value = arguments[1];
  27768. }
  27769. this.value = value;
  27770. }
  27771. Uniform.prototype.clone = function () {
  27772. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27773. };
  27774. /**
  27775. * @author benaadams / https://twitter.com/ben_a_adams
  27776. */
  27777. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27778. InterleavedBuffer.call(this, array, stride);
  27779. this.meshPerAttribute = meshPerAttribute || 1;
  27780. }
  27781. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27782. constructor: InstancedInterleavedBuffer,
  27783. isInstancedInterleavedBuffer: true,
  27784. copy: function (source) {
  27785. InterleavedBuffer.prototype.copy.call(this, source);
  27786. this.meshPerAttribute = source.meshPerAttribute;
  27787. return this;
  27788. }
  27789. });
  27790. /**
  27791. * @author mrdoob / http://mrdoob.com/
  27792. * @author bhouston / http://clara.io/
  27793. * @author stephomi / http://stephaneginier.com/
  27794. */
  27795. function Raycaster(origin, direction, near, far) {
  27796. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27797. this.near = near || 0;
  27798. this.far = far || Infinity;
  27799. this.camera = null;
  27800. this.params = {
  27801. Mesh: {},
  27802. Line: {},
  27803. LOD: {},
  27804. Points: {
  27805. threshold: 1
  27806. },
  27807. Sprite: {}
  27808. };
  27809. Object.defineProperties(this.params, {
  27810. PointCloud: {
  27811. get: function () {
  27812. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27813. return this.Points;
  27814. }
  27815. }
  27816. });
  27817. }
  27818. function ascSort(a, b) {
  27819. return a.distance - b.distance;
  27820. }
  27821. function intersectObject(object, raycaster, intersects, recursive) {
  27822. if (object.visible === false) return;
  27823. object.raycast(raycaster, intersects);
  27824. if (recursive === true) {
  27825. var children = object.children;
  27826. for (var i = 0, l = children.length; i < l; i++) {
  27827. intersectObject(children[i], raycaster, intersects, true);
  27828. }
  27829. }
  27830. }
  27831. Object.assign(Raycaster.prototype, {
  27832. linePrecision: 1,
  27833. set: function (origin, direction) {
  27834. // direction is assumed to be normalized (for accurate distance calculations)
  27835. this.ray.set(origin, direction);
  27836. },
  27837. setFromCamera: function (coords, camera) {
  27838. if (camera && camera.isPerspectiveCamera) {
  27839. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27840. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27841. this.camera = camera;
  27842. } else if (camera && camera.isOrthographicCamera) {
  27843. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27844. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27845. this.camera = camera;
  27846. } else {
  27847. console.error('THREE.Raycaster: Unsupported camera type.');
  27848. }
  27849. },
  27850. intersectObject: function (object, recursive, optionalTarget) {
  27851. var intersects = optionalTarget || [];
  27852. intersectObject(object, this, intersects, recursive);
  27853. intersects.sort(ascSort);
  27854. return intersects;
  27855. },
  27856. intersectObjects: function (objects, recursive, optionalTarget) {
  27857. var intersects = optionalTarget || [];
  27858. if (Array.isArray(objects) === false) {
  27859. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27860. return intersects;
  27861. }
  27862. for (var i = 0, l = objects.length; i < l; i++) {
  27863. intersectObject(objects[i], this, intersects, recursive);
  27864. }
  27865. intersects.sort(ascSort);
  27866. return intersects;
  27867. }
  27868. });
  27869. /**
  27870. * @author bhouston / http://clara.io
  27871. * @author WestLangley / http://github.com/WestLangley
  27872. *
  27873. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27874. *
  27875. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27876. * The azimuthal angle (theta) is measured from the positive z-axiz.
  27877. */
  27878. function Spherical(radius, phi, theta) {
  27879. this.radius = radius !== undefined ? radius : 1.0;
  27880. this.phi = phi !== undefined ? phi : 0; // polar angle
  27881. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  27882. return this;
  27883. }
  27884. Object.assign(Spherical.prototype, {
  27885. set: function (radius, phi, theta) {
  27886. this.radius = radius;
  27887. this.phi = phi;
  27888. this.theta = theta;
  27889. return this;
  27890. },
  27891. clone: function () {
  27892. return new this.constructor().copy(this);
  27893. },
  27894. copy: function (other) {
  27895. this.radius = other.radius;
  27896. this.phi = other.phi;
  27897. this.theta = other.theta;
  27898. return this;
  27899. },
  27900. // restrict phi to be betwee EPS and PI-EPS
  27901. makeSafe: function () {
  27902. var EPS = 0.000001;
  27903. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27904. return this;
  27905. },
  27906. setFromVector3: function (v) {
  27907. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27908. },
  27909. setFromCartesianCoords: function (x, y, z) {
  27910. this.radius = Math.sqrt(x * x + y * y + z * z);
  27911. if (this.radius === 0) {
  27912. this.theta = 0;
  27913. this.phi = 0;
  27914. } else {
  27915. this.theta = Math.atan2(x, z);
  27916. this.phi = Math.acos(_Math.clamp(y / this.radius, -1, 1));
  27917. }
  27918. return this;
  27919. }
  27920. });
  27921. /**
  27922. * @author Mugen87 / https://github.com/Mugen87
  27923. *
  27924. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27925. *
  27926. */
  27927. function Cylindrical(radius, theta, y) {
  27928. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27929. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27930. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27931. return this;
  27932. }
  27933. Object.assign(Cylindrical.prototype, {
  27934. set: function (radius, theta, y) {
  27935. this.radius = radius;
  27936. this.theta = theta;
  27937. this.y = y;
  27938. return this;
  27939. },
  27940. clone: function () {
  27941. return new this.constructor().copy(this);
  27942. },
  27943. copy: function (other) {
  27944. this.radius = other.radius;
  27945. this.theta = other.theta;
  27946. this.y = other.y;
  27947. return this;
  27948. },
  27949. setFromVector3: function (v) {
  27950. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27951. },
  27952. setFromCartesianCoords: function (x, y, z) {
  27953. this.radius = Math.sqrt(x * x + z * z);
  27954. this.theta = Math.atan2(x, z);
  27955. this.y = y;
  27956. return this;
  27957. }
  27958. });
  27959. /**
  27960. * @author bhouston / http://clara.io
  27961. */
  27962. var _vector$6 = new Vector2();
  27963. function Box2(min, max) {
  27964. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27965. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27966. }
  27967. Object.assign(Box2.prototype, {
  27968. set: function (min, max) {
  27969. this.min.copy(min);
  27970. this.max.copy(max);
  27971. return this;
  27972. },
  27973. setFromPoints: function (points) {
  27974. this.makeEmpty();
  27975. for (var i = 0, il = points.length; i < il; i++) {
  27976. this.expandByPoint(points[i]);
  27977. }
  27978. return this;
  27979. },
  27980. setFromCenterAndSize: function (center, size) {
  27981. var halfSize = _vector$6.copy(size).multiplyScalar(0.5);
  27982. this.min.copy(center).sub(halfSize);
  27983. this.max.copy(center).add(halfSize);
  27984. return this;
  27985. },
  27986. clone: function () {
  27987. return new this.constructor().copy(this);
  27988. },
  27989. copy: function (box) {
  27990. this.min.copy(box.min);
  27991. this.max.copy(box.max);
  27992. return this;
  27993. },
  27994. makeEmpty: function () {
  27995. this.min.x = this.min.y = +Infinity;
  27996. this.max.x = this.max.y = -Infinity;
  27997. return this;
  27998. },
  27999. isEmpty: function () {
  28000. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28001. return this.max.x < this.min.x || this.max.y < this.min.y;
  28002. },
  28003. getCenter: function (target) {
  28004. if (target === undefined) {
  28005. console.warn('THREE.Box2: .getCenter() target is now required');
  28006. target = new Vector2();
  28007. }
  28008. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  28009. },
  28010. getSize: function (target) {
  28011. if (target === undefined) {
  28012. console.warn('THREE.Box2: .getSize() target is now required');
  28013. target = new Vector2();
  28014. }
  28015. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  28016. },
  28017. expandByPoint: function (point) {
  28018. this.min.min(point);
  28019. this.max.max(point);
  28020. return this;
  28021. },
  28022. expandByVector: function (vector) {
  28023. this.min.sub(vector);
  28024. this.max.add(vector);
  28025. return this;
  28026. },
  28027. expandByScalar: function (scalar) {
  28028. this.min.addScalar(-scalar);
  28029. this.max.addScalar(scalar);
  28030. return this;
  28031. },
  28032. containsPoint: function (point) {
  28033. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  28034. },
  28035. containsBox: function (box) {
  28036. 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;
  28037. },
  28038. getParameter: function (point, target) {
  28039. // This can potentially have a divide by zero if the box
  28040. // has a size dimension of 0.
  28041. if (target === undefined) {
  28042. console.warn('THREE.Box2: .getParameter() target is now required');
  28043. target = new Vector2();
  28044. }
  28045. 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));
  28046. },
  28047. intersectsBox: function (box) {
  28048. // using 4 splitting planes to rule out intersections
  28049. 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;
  28050. },
  28051. clampPoint: function (point, target) {
  28052. if (target === undefined) {
  28053. console.warn('THREE.Box2: .clampPoint() target is now required');
  28054. target = new Vector2();
  28055. }
  28056. return target.copy(point).clamp(this.min, this.max);
  28057. },
  28058. distanceToPoint: function (point) {
  28059. var clampedPoint = _vector$6.copy(point).clamp(this.min, this.max);
  28060. return clampedPoint.sub(point).length();
  28061. },
  28062. intersect: function (box) {
  28063. this.min.max(box.min);
  28064. this.max.min(box.max);
  28065. return this;
  28066. },
  28067. union: function (box) {
  28068. this.min.min(box.min);
  28069. this.max.max(box.max);
  28070. return this;
  28071. },
  28072. translate: function (offset) {
  28073. this.min.add(offset);
  28074. this.max.add(offset);
  28075. return this;
  28076. },
  28077. equals: function (box) {
  28078. return box.min.equals(this.min) && box.max.equals(this.max);
  28079. }
  28080. });
  28081. /**
  28082. * @author bhouston / http://clara.io
  28083. */
  28084. var _startP = new Vector3();
  28085. var _startEnd = new Vector3();
  28086. function Line3(start, end) {
  28087. this.start = start !== undefined ? start : new Vector3();
  28088. this.end = end !== undefined ? end : new Vector3();
  28089. }
  28090. Object.assign(Line3.prototype, {
  28091. set: function (start, end) {
  28092. this.start.copy(start);
  28093. this.end.copy(end);
  28094. return this;
  28095. },
  28096. clone: function () {
  28097. return new this.constructor().copy(this);
  28098. },
  28099. copy: function (line) {
  28100. this.start.copy(line.start);
  28101. this.end.copy(line.end);
  28102. return this;
  28103. },
  28104. getCenter: function (target) {
  28105. if (target === undefined) {
  28106. console.warn('THREE.Line3: .getCenter() target is now required');
  28107. target = new Vector3();
  28108. }
  28109. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  28110. },
  28111. delta: function (target) {
  28112. if (target === undefined) {
  28113. console.warn('THREE.Line3: .delta() target is now required');
  28114. target = new Vector3();
  28115. }
  28116. return target.subVectors(this.end, this.start);
  28117. },
  28118. distanceSq: function () {
  28119. return this.start.distanceToSquared(this.end);
  28120. },
  28121. distance: function () {
  28122. return this.start.distanceTo(this.end);
  28123. },
  28124. at: function (t, target) {
  28125. if (target === undefined) {
  28126. console.warn('THREE.Line3: .at() target is now required');
  28127. target = new Vector3();
  28128. }
  28129. return this.delta(target).multiplyScalar(t).add(this.start);
  28130. },
  28131. closestPointToPointParameter: function (point, clampToLine) {
  28132. _startP.subVectors(point, this.start);
  28133. _startEnd.subVectors(this.end, this.start);
  28134. var startEnd2 = _startEnd.dot(_startEnd);
  28135. var startEnd_startP = _startEnd.dot(_startP);
  28136. var t = startEnd_startP / startEnd2;
  28137. if (clampToLine) {
  28138. t = _Math.clamp(t, 0, 1);
  28139. }
  28140. return t;
  28141. },
  28142. closestPointToPoint: function (point, clampToLine, target) {
  28143. var t = this.closestPointToPointParameter(point, clampToLine);
  28144. if (target === undefined) {
  28145. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  28146. target = new Vector3();
  28147. }
  28148. return this.delta(target).multiplyScalar(t).add(this.start);
  28149. },
  28150. applyMatrix4: function (matrix) {
  28151. this.start.applyMatrix4(matrix);
  28152. this.end.applyMatrix4(matrix);
  28153. return this;
  28154. },
  28155. equals: function (line) {
  28156. return line.start.equals(this.start) && line.end.equals(this.end);
  28157. }
  28158. });
  28159. /**
  28160. * @author alteredq / http://alteredqualia.com/
  28161. */
  28162. function ImmediateRenderObject(material) {
  28163. Object3D.call(this);
  28164. this.material = material;
  28165. this.render = function ()
  28166. /* renderCallback */
  28167. {};
  28168. }
  28169. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  28170. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28171. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28172. /**
  28173. * @author mrdoob / http://mrdoob.com/
  28174. * @author WestLangley / http://github.com/WestLangley
  28175. */
  28176. var _v1$5 = new Vector3();
  28177. var _v2$3 = new Vector3();
  28178. var _normalMatrix$1 = new Matrix3();
  28179. var _keys = ['a', 'b', 'c'];
  28180. function VertexNormalsHelper(object, size, hex, linewidth) {
  28181. this.object = object;
  28182. this.size = size !== undefined ? size : 1;
  28183. var color = hex !== undefined ? hex : 0xff0000;
  28184. var width = linewidth !== undefined ? linewidth : 1; //
  28185. var nNormals = 0;
  28186. var objGeometry = this.object.geometry;
  28187. if (objGeometry && objGeometry.isGeometry) {
  28188. nNormals = objGeometry.faces.length * 3;
  28189. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28190. nNormals = objGeometry.attributes.normal.count;
  28191. } //
  28192. var geometry = new BufferGeometry();
  28193. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28194. geometry.addAttribute('position', positions);
  28195. LineSegments.call(this, geometry, new LineBasicMaterial({
  28196. color: color,
  28197. linewidth: width
  28198. })); //
  28199. this.matrixAutoUpdate = false;
  28200. this.update();
  28201. }
  28202. VertexNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28203. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  28204. VertexNormalsHelper.prototype.update = function () {
  28205. this.object.updateMatrixWorld(true);
  28206. _normalMatrix$1.getNormalMatrix(this.object.matrixWorld);
  28207. var matrixWorld = this.object.matrixWorld;
  28208. var position = this.geometry.attributes.position; //
  28209. var objGeometry = this.object.geometry;
  28210. if (objGeometry && objGeometry.isGeometry) {
  28211. var vertices = objGeometry.vertices;
  28212. var faces = objGeometry.faces;
  28213. var idx = 0;
  28214. for (var i = 0, l = faces.length; i < l; i++) {
  28215. var face = faces[i];
  28216. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  28217. var vertex = vertices[face[_keys[j]]];
  28218. var normal = face.vertexNormals[j];
  28219. _v1$5.copy(vertex).applyMatrix4(matrixWorld);
  28220. _v2$3.copy(normal).applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28221. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28222. idx = idx + 1;
  28223. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28224. idx = idx + 1;
  28225. }
  28226. }
  28227. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28228. var objPos = objGeometry.attributes.position;
  28229. var objNorm = objGeometry.attributes.normal;
  28230. var idx = 0; // for simplicity, ignore index and drawcalls, and render every normal
  28231. for (var j = 0, jl = objPos.count; j < jl; j++) {
  28232. _v1$5.set(objPos.getX(j), objPos.getY(j), objPos.getZ(j)).applyMatrix4(matrixWorld);
  28233. _v2$3.set(objNorm.getX(j), objNorm.getY(j), objNorm.getZ(j));
  28234. _v2$3.applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28235. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28236. idx = idx + 1;
  28237. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28238. idx = idx + 1;
  28239. }
  28240. }
  28241. position.needsUpdate = true;
  28242. };
  28243. /**
  28244. * @author alteredq / http://alteredqualia.com/
  28245. * @author mrdoob / http://mrdoob.com/
  28246. * @author WestLangley / http://github.com/WestLangley
  28247. */
  28248. var _vector$7 = new Vector3();
  28249. function SpotLightHelper(light, color) {
  28250. Object3D.call(this);
  28251. this.light = light;
  28252. this.light.updateMatrixWorld();
  28253. this.matrix = light.matrixWorld;
  28254. this.matrixAutoUpdate = false;
  28255. this.color = color;
  28256. var geometry = new BufferGeometry();
  28257. 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];
  28258. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  28259. var p1 = i / l * Math.PI * 2;
  28260. var p2 = j / l * Math.PI * 2;
  28261. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28262. }
  28263. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28264. var material = new LineBasicMaterial({
  28265. fog: false
  28266. });
  28267. this.cone = new LineSegments(geometry, material);
  28268. this.add(this.cone);
  28269. this.update();
  28270. }
  28271. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  28272. SpotLightHelper.prototype.constructor = SpotLightHelper;
  28273. SpotLightHelper.prototype.dispose = function () {
  28274. this.cone.geometry.dispose();
  28275. this.cone.material.dispose();
  28276. };
  28277. SpotLightHelper.prototype.update = function () {
  28278. this.light.updateMatrixWorld();
  28279. var coneLength = this.light.distance ? this.light.distance : 1000;
  28280. var coneWidth = coneLength * Math.tan(this.light.angle);
  28281. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28282. _vector$7.setFromMatrixPosition(this.light.target.matrixWorld);
  28283. this.cone.lookAt(_vector$7);
  28284. if (this.color !== undefined) {
  28285. this.cone.material.color.set(this.color);
  28286. } else {
  28287. this.cone.material.color.copy(this.light.color);
  28288. }
  28289. };
  28290. /**
  28291. * @author Sean Griffin / http://twitter.com/sgrif
  28292. * @author Michael Guerrero / http://realitymeltdown.com
  28293. * @author mrdoob / http://mrdoob.com/
  28294. * @author ikerr / http://verold.com
  28295. * @author Mugen87 / https://github.com/Mugen87
  28296. */
  28297. var _vector$8 = new Vector3();
  28298. var _boneMatrix = new Matrix4();
  28299. var _matrixWorldInv = new Matrix4();
  28300. function getBoneList(object) {
  28301. var boneList = [];
  28302. if (object && object.isBone) {
  28303. boneList.push(object);
  28304. }
  28305. for (var i = 0; i < object.children.length; i++) {
  28306. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28307. }
  28308. return boneList;
  28309. }
  28310. function SkeletonHelper(object) {
  28311. var bones = getBoneList(object);
  28312. var geometry = new BufferGeometry();
  28313. var vertices = [];
  28314. var colors = [];
  28315. var color1 = new Color(0, 0, 1);
  28316. var color2 = new Color(0, 1, 0);
  28317. for (var i = 0; i < bones.length; i++) {
  28318. var bone = bones[i];
  28319. if (bone.parent && bone.parent.isBone) {
  28320. vertices.push(0, 0, 0);
  28321. vertices.push(0, 0, 0);
  28322. colors.push(color1.r, color1.g, color1.b);
  28323. colors.push(color2.r, color2.g, color2.b);
  28324. }
  28325. }
  28326. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28327. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28328. var material = new LineBasicMaterial({
  28329. vertexColors: VertexColors,
  28330. depthTest: false,
  28331. depthWrite: false,
  28332. transparent: true
  28333. });
  28334. LineSegments.call(this, geometry, material);
  28335. this.root = object;
  28336. this.bones = bones;
  28337. this.matrix = object.matrixWorld;
  28338. this.matrixAutoUpdate = false;
  28339. }
  28340. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  28341. SkeletonHelper.prototype.constructor = SkeletonHelper;
  28342. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  28343. var bones = this.bones;
  28344. var geometry = this.geometry;
  28345. var position = geometry.getAttribute('position');
  28346. _matrixWorldInv.getInverse(this.root.matrixWorld);
  28347. for (var i = 0, j = 0; i < bones.length; i++) {
  28348. var bone = bones[i];
  28349. if (bone.parent && bone.parent.isBone) {
  28350. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28351. _vector$8.setFromMatrixPosition(_boneMatrix);
  28352. position.setXYZ(j, _vector$8.x, _vector$8.y, _vector$8.z);
  28353. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28354. _vector$8.setFromMatrixPosition(_boneMatrix);
  28355. position.setXYZ(j + 1, _vector$8.x, _vector$8.y, _vector$8.z);
  28356. j += 2;
  28357. }
  28358. }
  28359. geometry.getAttribute('position').needsUpdate = true;
  28360. Object3D.prototype.updateMatrixWorld.call(this, force);
  28361. };
  28362. /**
  28363. * @author alteredq / http://alteredqualia.com/
  28364. * @author mrdoob / http://mrdoob.com/
  28365. */
  28366. function PointLightHelper(light, sphereSize, color) {
  28367. this.light = light;
  28368. this.light.updateMatrixWorld();
  28369. this.color = color;
  28370. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  28371. var material = new MeshBasicMaterial({
  28372. wireframe: true,
  28373. fog: false
  28374. });
  28375. Mesh.call(this, geometry, material);
  28376. this.matrix = this.light.matrixWorld;
  28377. this.matrixAutoUpdate = false;
  28378. this.update();
  28379. /*
  28380. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28381. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28382. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28383. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28384. var d = light.distance;
  28385. if ( d === 0.0 ) {
  28386. this.lightDistance.visible = false;
  28387. } else {
  28388. this.lightDistance.scale.set( d, d, d );
  28389. }
  28390. this.add( this.lightDistance );
  28391. */
  28392. }
  28393. PointLightHelper.prototype = Object.create(Mesh.prototype);
  28394. PointLightHelper.prototype.constructor = PointLightHelper;
  28395. PointLightHelper.prototype.dispose = function () {
  28396. this.geometry.dispose();
  28397. this.material.dispose();
  28398. };
  28399. PointLightHelper.prototype.update = function () {
  28400. if (this.color !== undefined) {
  28401. this.material.color.set(this.color);
  28402. } else {
  28403. this.material.color.copy(this.light.color);
  28404. }
  28405. /*
  28406. var d = this.light.distance;
  28407. if ( d === 0.0 ) {
  28408. this.lightDistance.visible = false;
  28409. } else {
  28410. this.lightDistance.visible = true;
  28411. this.lightDistance.scale.set( d, d, d );
  28412. }
  28413. */
  28414. };
  28415. /**
  28416. * @author abelnation / http://github.com/abelnation
  28417. * @author Mugen87 / http://github.com/Mugen87
  28418. * @author WestLangley / http://github.com/WestLangley
  28419. *
  28420. * This helper must be added as a child of the light
  28421. */
  28422. function RectAreaLightHelper(light, color) {
  28423. this.type = 'RectAreaLightHelper';
  28424. this.light = light;
  28425. this.color = color; // optional hardwired color for the helper
  28426. var positions = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
  28427. var geometry = new BufferGeometry();
  28428. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28429. geometry.computeBoundingSphere();
  28430. var material = new LineBasicMaterial({
  28431. fog: false
  28432. });
  28433. Line.call(this, geometry, material); //
  28434. var positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  28435. var geometry2 = new BufferGeometry();
  28436. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  28437. geometry2.computeBoundingSphere();
  28438. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28439. side: BackSide,
  28440. fog: false
  28441. })));
  28442. this.update();
  28443. }
  28444. RectAreaLightHelper.prototype = Object.create(Line.prototype);
  28445. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  28446. RectAreaLightHelper.prototype.update = function () {
  28447. this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);
  28448. if (this.color !== undefined) {
  28449. this.material.color.set(this.color);
  28450. this.children[0].material.color.set(this.color);
  28451. } else {
  28452. this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity); // prevent hue shift
  28453. var c = this.material.color;
  28454. var max = Math.max(c.r, c.g, c.b);
  28455. if (max > 1) c.multiplyScalar(1 / max);
  28456. this.children[0].material.color.copy(this.material.color);
  28457. }
  28458. };
  28459. RectAreaLightHelper.prototype.dispose = function () {
  28460. this.geometry.dispose();
  28461. this.material.dispose();
  28462. this.children[0].geometry.dispose();
  28463. this.children[0].material.dispose();
  28464. };
  28465. /**
  28466. * @author alteredq / http://alteredqualia.com/
  28467. * @author mrdoob / http://mrdoob.com/
  28468. * @author Mugen87 / https://github.com/Mugen87
  28469. */
  28470. var _vector$9 = new Vector3();
  28471. var _color1 = new Color();
  28472. var _color2 = new Color();
  28473. function HemisphereLightHelper(light, size, color) {
  28474. Object3D.call(this);
  28475. this.light = light;
  28476. this.light.updateMatrixWorld();
  28477. this.matrix = light.matrixWorld;
  28478. this.matrixAutoUpdate = false;
  28479. this.color = color;
  28480. var geometry = new OctahedronBufferGeometry(size);
  28481. geometry.rotateY(Math.PI * 0.5);
  28482. this.material = new MeshBasicMaterial({
  28483. wireframe: true,
  28484. fog: false
  28485. });
  28486. if (this.color === undefined) this.material.vertexColors = VertexColors;
  28487. var position = geometry.getAttribute('position');
  28488. var colors = new Float32Array(position.count * 3);
  28489. geometry.addAttribute('color', new BufferAttribute(colors, 3));
  28490. this.add(new Mesh(geometry, this.material));
  28491. this.update();
  28492. }
  28493. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  28494. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  28495. HemisphereLightHelper.prototype.dispose = function () {
  28496. this.children[0].geometry.dispose();
  28497. this.children[0].material.dispose();
  28498. };
  28499. HemisphereLightHelper.prototype.update = function () {
  28500. var mesh = this.children[0];
  28501. if (this.color !== undefined) {
  28502. this.material.color.set(this.color);
  28503. } else {
  28504. var colors = mesh.geometry.getAttribute('color');
  28505. _color1.copy(this.light.color);
  28506. _color2.copy(this.light.groundColor);
  28507. for (var i = 0, l = colors.count; i < l; i++) {
  28508. var color = i < l / 2 ? _color1 : _color2;
  28509. colors.setXYZ(i, color.r, color.g, color.b);
  28510. }
  28511. colors.needsUpdate = true;
  28512. }
  28513. mesh.lookAt(_vector$9.setFromMatrixPosition(this.light.matrixWorld).negate());
  28514. };
  28515. /**
  28516. * @author WestLangley / http://github.com/WestLangley
  28517. */
  28518. function LightProbeHelper(lightProbe, size) {
  28519. this.lightProbe = lightProbe;
  28520. this.size = size;
  28521. var defines = {};
  28522. defines['GAMMA_OUTPUT'] = ""; // material
  28523. var material = new ShaderMaterial({
  28524. defines: defines,
  28525. uniforms: {
  28526. sh: {
  28527. value: this.lightProbe.sh.coefficients
  28528. },
  28529. // by reference
  28530. intensity: {
  28531. value: this.lightProbe.intensity
  28532. }
  28533. },
  28534. vertexShader: ['varying vec3 vNormal;', 'void main() {', ' vNormal = normalize( normalMatrix * normal );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'),
  28535. fragmentShader: ['#define RECIPROCAL_PI 0.318309886', 'vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {', ' // matrix is assumed to be orthogonal', ' return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );', '}', 'vec3 linearToOutput( in vec3 a ) {', ' #ifdef GAMMA_OUTPUT', ' return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );', ' #else', ' return a;', ' #endif', '}', '// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf', 'vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {', ' // normal is assumed to have unit length', ' float x = normal.x, y = normal.y, z = normal.z;', ' // band 0', ' vec3 result = shCoefficients[ 0 ] * 0.886227;', ' // band 1', ' result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;', ' result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;', ' result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;', ' // band 2', ' result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;', ' result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;', ' result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );', ' result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;', ' result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );', ' return result;', '}', 'uniform vec3 sh[ 9 ]; // sh coefficients', 'uniform float intensity; // light probe intensity', 'varying vec3 vNormal;', 'void main() {', ' vec3 normal = normalize( vNormal );', ' vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );', ' vec3 irradiance = shGetIrradianceAt( worldNormal, sh );', ' vec3 outgoingLight = RECIPROCAL_PI * irradiance * intensity;', ' outgoingLight = linearToOutput( outgoingLight );', ' gl_FragColor = vec4( outgoingLight, 1.0 );', '}'].join('\n')
  28536. });
  28537. var geometry = new SphereBufferGeometry(1, 32, 16);
  28538. Mesh.call(this, geometry, material);
  28539. this.onBeforeRender();
  28540. }
  28541. LightProbeHelper.prototype = Object.create(Mesh.prototype);
  28542. LightProbeHelper.prototype.constructor = LightProbeHelper;
  28543. LightProbeHelper.prototype.dispose = function () {
  28544. this.geometry.dispose();
  28545. this.material.dispose();
  28546. };
  28547. LightProbeHelper.prototype.onBeforeRender = function () {
  28548. this.position.copy(this.lightProbe.position);
  28549. this.scale.set(1, 1, 1).multiplyScalar(this.size);
  28550. this.material.uniforms.intensity.value = this.lightProbe.intensity;
  28551. };
  28552. /**
  28553. * @author mrdoob / http://mrdoob.com/
  28554. */
  28555. function GridHelper(size, divisions, color1, color2) {
  28556. size = size || 10;
  28557. divisions = divisions || 10;
  28558. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28559. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28560. var center = divisions / 2;
  28561. var step = size / divisions;
  28562. var halfSize = size / 2;
  28563. var vertices = [],
  28564. colors = [];
  28565. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28566. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28567. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28568. var color = i === center ? color1 : color2;
  28569. color.toArray(colors, j);
  28570. j += 3;
  28571. color.toArray(colors, j);
  28572. j += 3;
  28573. color.toArray(colors, j);
  28574. j += 3;
  28575. color.toArray(colors, j);
  28576. j += 3;
  28577. }
  28578. var geometry = new BufferGeometry();
  28579. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28580. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28581. var material = new LineBasicMaterial({
  28582. vertexColors: VertexColors
  28583. });
  28584. LineSegments.call(this, geometry, material);
  28585. }
  28586. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  28587. constructor: GridHelper,
  28588. copy: function (source) {
  28589. LineSegments.prototype.copy.call(this, source);
  28590. this.geometry.copy(source.geometry);
  28591. this.material.copy(source.material);
  28592. return this;
  28593. },
  28594. clone: function () {
  28595. return new this.constructor().copy(this);
  28596. }
  28597. });
  28598. /**
  28599. * @author mrdoob / http://mrdoob.com/
  28600. * @author Mugen87 / http://github.com/Mugen87
  28601. * @author Hectate / http://www.github.com/Hectate
  28602. */
  28603. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  28604. radius = radius || 10;
  28605. radials = radials || 16;
  28606. circles = circles || 8;
  28607. divisions = divisions || 64;
  28608. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28609. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28610. var vertices = [];
  28611. var colors = [];
  28612. var x, z;
  28613. var v, i, j, r, color; // create the radials
  28614. for (i = 0; i <= radials; i++) {
  28615. v = i / radials * (Math.PI * 2);
  28616. x = Math.sin(v) * radius;
  28617. z = Math.cos(v) * radius;
  28618. vertices.push(0, 0, 0);
  28619. vertices.push(x, 0, z);
  28620. color = i & 1 ? color1 : color2;
  28621. colors.push(color.r, color.g, color.b);
  28622. colors.push(color.r, color.g, color.b);
  28623. } // create the circles
  28624. for (i = 0; i <= circles; i++) {
  28625. color = i & 1 ? color1 : color2;
  28626. r = radius - radius / circles * i;
  28627. for (j = 0; j < divisions; j++) {
  28628. // first vertex
  28629. v = j / divisions * (Math.PI * 2);
  28630. x = Math.sin(v) * r;
  28631. z = Math.cos(v) * r;
  28632. vertices.push(x, 0, z);
  28633. colors.push(color.r, color.g, color.b); // second vertex
  28634. v = (j + 1) / divisions * (Math.PI * 2);
  28635. x = Math.sin(v) * r;
  28636. z = Math.cos(v) * r;
  28637. vertices.push(x, 0, z);
  28638. colors.push(color.r, color.g, color.b);
  28639. }
  28640. }
  28641. var geometry = new BufferGeometry();
  28642. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28643. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28644. var material = new LineBasicMaterial({
  28645. vertexColors: VertexColors
  28646. });
  28647. LineSegments.call(this, geometry, material);
  28648. }
  28649. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  28650. PolarGridHelper.prototype.constructor = PolarGridHelper;
  28651. /**
  28652. * @author Mugen87 / http://github.com/Mugen87
  28653. */
  28654. function PositionalAudioHelper(audio, range, divisionsInnerAngle, divisionsOuterAngle) {
  28655. this.audio = audio;
  28656. this.range = range || 1;
  28657. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  28658. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  28659. var geometry = new BufferGeometry();
  28660. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  28661. var positions = new Float32Array((divisions * 3 + 3) * 3);
  28662. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28663. var materialInnerAngle = new LineBasicMaterial({
  28664. color: 0x00ff00
  28665. });
  28666. var materialOuterAngle = new LineBasicMaterial({
  28667. color: 0xffff00
  28668. });
  28669. Line.call(this, geometry, [materialOuterAngle, materialInnerAngle]);
  28670. this.update();
  28671. }
  28672. PositionalAudioHelper.prototype = Object.create(Line.prototype);
  28673. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  28674. PositionalAudioHelper.prototype.update = function () {
  28675. var audio = this.audio;
  28676. var range = this.range;
  28677. var divisionsInnerAngle = this.divisionsInnerAngle;
  28678. var divisionsOuterAngle = this.divisionsOuterAngle;
  28679. var coneInnerAngle = _Math.degToRad(audio.panner.coneInnerAngle);
  28680. var coneOuterAngle = _Math.degToRad(audio.panner.coneOuterAngle);
  28681. var halfConeInnerAngle = coneInnerAngle / 2;
  28682. var halfConeOuterAngle = coneOuterAngle / 2;
  28683. var start = 0;
  28684. var count = 0;
  28685. var i, stride;
  28686. var geometry = this.geometry;
  28687. var positionAttribute = geometry.attributes.position;
  28688. geometry.clearGroups(); //
  28689. function generateSegment(from, to, divisions, materialIndex) {
  28690. var step = (to - from) / divisions;
  28691. positionAttribute.setXYZ(start, 0, 0, 0);
  28692. count++;
  28693. for (i = from; i < to; i += step) {
  28694. stride = start + count;
  28695. positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range);
  28696. positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range);
  28697. positionAttribute.setXYZ(stride + 2, 0, 0, 0);
  28698. count += 3;
  28699. }
  28700. geometry.addGroup(start, count, materialIndex);
  28701. start += count;
  28702. count = 0;
  28703. } //
  28704. generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0);
  28705. generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1);
  28706. generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0); //
  28707. positionAttribute.needsUpdate = true;
  28708. if (coneInnerAngle === coneOuterAngle) this.material[0].visible = false;
  28709. };
  28710. PositionalAudioHelper.prototype.dispose = function () {
  28711. this.geometry.dispose();
  28712. this.material[0].dispose();
  28713. this.material[1].dispose();
  28714. };
  28715. /**
  28716. * @author mrdoob / http://mrdoob.com/
  28717. * @author WestLangley / http://github.com/WestLangley
  28718. */
  28719. var _v1$6 = new Vector3();
  28720. var _v2$4 = new Vector3();
  28721. var _normalMatrix$2 = new Matrix3();
  28722. function FaceNormalsHelper(object, size, hex, linewidth) {
  28723. // FaceNormalsHelper only supports THREE.Geometry
  28724. this.object = object;
  28725. this.size = size !== undefined ? size : 1;
  28726. var color = hex !== undefined ? hex : 0xffff00;
  28727. var width = linewidth !== undefined ? linewidth : 1; //
  28728. var nNormals = 0;
  28729. var objGeometry = this.object.geometry;
  28730. if (objGeometry && objGeometry.isGeometry) {
  28731. nNormals = objGeometry.faces.length;
  28732. } else {
  28733. console.warn('THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.');
  28734. } //
  28735. var geometry = new BufferGeometry();
  28736. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28737. geometry.addAttribute('position', positions);
  28738. LineSegments.call(this, geometry, new LineBasicMaterial({
  28739. color: color,
  28740. linewidth: width
  28741. })); //
  28742. this.matrixAutoUpdate = false;
  28743. this.update();
  28744. }
  28745. FaceNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28746. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  28747. FaceNormalsHelper.prototype.update = function () {
  28748. this.object.updateMatrixWorld(true);
  28749. _normalMatrix$2.getNormalMatrix(this.object.matrixWorld);
  28750. var matrixWorld = this.object.matrixWorld;
  28751. var position = this.geometry.attributes.position; //
  28752. var objGeometry = this.object.geometry;
  28753. var vertices = objGeometry.vertices;
  28754. var faces = objGeometry.faces;
  28755. var idx = 0;
  28756. for (var i = 0, l = faces.length; i < l; i++) {
  28757. var face = faces[i];
  28758. var normal = face.normal;
  28759. _v1$6.copy(vertices[face.a]).add(vertices[face.b]).add(vertices[face.c]).divideScalar(3).applyMatrix4(matrixWorld);
  28760. _v2$4.copy(normal).applyMatrix3(_normalMatrix$2).normalize().multiplyScalar(this.size).add(_v1$6);
  28761. position.setXYZ(idx, _v1$6.x, _v1$6.y, _v1$6.z);
  28762. idx = idx + 1;
  28763. position.setXYZ(idx, _v2$4.x, _v2$4.y, _v2$4.z);
  28764. idx = idx + 1;
  28765. }
  28766. position.needsUpdate = true;
  28767. };
  28768. /**
  28769. * @author alteredq / http://alteredqualia.com/
  28770. * @author mrdoob / http://mrdoob.com/
  28771. * @author WestLangley / http://github.com/WestLangley
  28772. */
  28773. var _v1$7 = new Vector3();
  28774. var _v2$5 = new Vector3();
  28775. var _v3$1 = new Vector3();
  28776. function DirectionalLightHelper(light, size, color) {
  28777. Object3D.call(this);
  28778. this.light = light;
  28779. this.light.updateMatrixWorld();
  28780. this.matrix = light.matrixWorld;
  28781. this.matrixAutoUpdate = false;
  28782. this.color = color;
  28783. if (size === undefined) size = 1;
  28784. var geometry = new BufferGeometry();
  28785. geometry.addAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28786. var material = new LineBasicMaterial({
  28787. fog: false
  28788. });
  28789. this.lightPlane = new Line(geometry, material);
  28790. this.add(this.lightPlane);
  28791. geometry = new BufferGeometry();
  28792. geometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28793. this.targetLine = new Line(geometry, material);
  28794. this.add(this.targetLine);
  28795. this.update();
  28796. }
  28797. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  28798. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  28799. DirectionalLightHelper.prototype.dispose = function () {
  28800. this.lightPlane.geometry.dispose();
  28801. this.lightPlane.material.dispose();
  28802. this.targetLine.geometry.dispose();
  28803. this.targetLine.material.dispose();
  28804. };
  28805. DirectionalLightHelper.prototype.update = function () {
  28806. _v1$7.setFromMatrixPosition(this.light.matrixWorld);
  28807. _v2$5.setFromMatrixPosition(this.light.target.matrixWorld);
  28808. _v3$1.subVectors(_v2$5, _v1$7);
  28809. this.lightPlane.lookAt(_v2$5);
  28810. if (this.color !== undefined) {
  28811. this.lightPlane.material.color.set(this.color);
  28812. this.targetLine.material.color.set(this.color);
  28813. } else {
  28814. this.lightPlane.material.color.copy(this.light.color);
  28815. this.targetLine.material.color.copy(this.light.color);
  28816. }
  28817. this.targetLine.lookAt(_v2$5);
  28818. this.targetLine.scale.z = _v3$1.length();
  28819. };
  28820. /**
  28821. * @author alteredq / http://alteredqualia.com/
  28822. * @author Mugen87 / https://github.com/Mugen87
  28823. *
  28824. * - shows frustum, line of sight and up of the camera
  28825. * - suitable for fast updates
  28826. * - based on frustum visualization in lightgl.js shadowmap example
  28827. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28828. */
  28829. var _vector$a = new Vector3();
  28830. var _camera = new Camera();
  28831. function CameraHelper(camera) {
  28832. var geometry = new BufferGeometry();
  28833. var material = new LineBasicMaterial({
  28834. color: 0xffffff,
  28835. vertexColors: FaceColors
  28836. });
  28837. var vertices = [];
  28838. var colors = [];
  28839. var pointMap = {}; // colors
  28840. var colorFrustum = new Color(0xffaa00);
  28841. var colorCone = new Color(0xff0000);
  28842. var colorUp = new Color(0x00aaff);
  28843. var colorTarget = new Color(0xffffff);
  28844. var colorCross = new Color(0x333333); // near
  28845. addLine('n1', 'n2', colorFrustum);
  28846. addLine('n2', 'n4', colorFrustum);
  28847. addLine('n4', 'n3', colorFrustum);
  28848. addLine('n3', 'n1', colorFrustum); // far
  28849. addLine('f1', 'f2', colorFrustum);
  28850. addLine('f2', 'f4', colorFrustum);
  28851. addLine('f4', 'f3', colorFrustum);
  28852. addLine('f3', 'f1', colorFrustum); // sides
  28853. addLine('n1', 'f1', colorFrustum);
  28854. addLine('n2', 'f2', colorFrustum);
  28855. addLine('n3', 'f3', colorFrustum);
  28856. addLine('n4', 'f4', colorFrustum); // cone
  28857. addLine('p', 'n1', colorCone);
  28858. addLine('p', 'n2', colorCone);
  28859. addLine('p', 'n3', colorCone);
  28860. addLine('p', 'n4', colorCone); // up
  28861. addLine('u1', 'u2', colorUp);
  28862. addLine('u2', 'u3', colorUp);
  28863. addLine('u3', 'u1', colorUp); // target
  28864. addLine('c', 't', colorTarget);
  28865. addLine('p', 'c', colorCross); // cross
  28866. addLine('cn1', 'cn2', colorCross);
  28867. addLine('cn3', 'cn4', colorCross);
  28868. addLine('cf1', 'cf2', colorCross);
  28869. addLine('cf3', 'cf4', colorCross);
  28870. function addLine(a, b, color) {
  28871. addPoint(a, color);
  28872. addPoint(b, color);
  28873. }
  28874. function addPoint(id, color) {
  28875. vertices.push(0, 0, 0);
  28876. colors.push(color.r, color.g, color.b);
  28877. if (pointMap[id] === undefined) {
  28878. pointMap[id] = [];
  28879. }
  28880. pointMap[id].push(vertices.length / 3 - 1);
  28881. }
  28882. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28883. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28884. LineSegments.call(this, geometry, material);
  28885. this.camera = camera;
  28886. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  28887. this.matrix = camera.matrixWorld;
  28888. this.matrixAutoUpdate = false;
  28889. this.pointMap = pointMap;
  28890. this.update();
  28891. }
  28892. CameraHelper.prototype = Object.create(LineSegments.prototype);
  28893. CameraHelper.prototype.constructor = CameraHelper;
  28894. CameraHelper.prototype.update = function () {
  28895. var geometry = this.geometry;
  28896. var pointMap = this.pointMap;
  28897. var w = 1,
  28898. h = 1; // we need just camera projection matrix inverse
  28899. // world matrix must be identity
  28900. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28901. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28902. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28903. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28904. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28905. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28906. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28907. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28908. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28909. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28910. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28911. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28912. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28913. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28914. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28915. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28916. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28917. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28918. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28919. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28920. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28921. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28922. geometry.getAttribute('position').needsUpdate = true;
  28923. };
  28924. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28925. _vector$a.set(x, y, z).unproject(camera);
  28926. var points = pointMap[point];
  28927. if (points !== undefined) {
  28928. var position = geometry.getAttribute('position');
  28929. for (var i = 0, l = points.length; i < l; i++) {
  28930. position.setXYZ(points[i], _vector$a.x, _vector$a.y, _vector$a.z);
  28931. }
  28932. }
  28933. }
  28934. /**
  28935. * @author mrdoob / http://mrdoob.com/
  28936. * @author Mugen87 / http://github.com/Mugen87
  28937. */
  28938. var _box$2 = new Box3();
  28939. function BoxHelper(object, color) {
  28940. this.object = object;
  28941. if (color === undefined) color = 0xffff00;
  28942. 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]);
  28943. var positions = new Float32Array(8 * 3);
  28944. var geometry = new BufferGeometry();
  28945. geometry.setIndex(new BufferAttribute(indices, 1));
  28946. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28947. LineSegments.call(this, geometry, new LineBasicMaterial({
  28948. color: color
  28949. }));
  28950. this.matrixAutoUpdate = false;
  28951. this.update();
  28952. }
  28953. BoxHelper.prototype = Object.create(LineSegments.prototype);
  28954. BoxHelper.prototype.constructor = BoxHelper;
  28955. BoxHelper.prototype.update = function (object) {
  28956. if (object !== undefined) {
  28957. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28958. }
  28959. if (this.object !== undefined) {
  28960. _box$2.setFromObject(this.object);
  28961. }
  28962. if (_box$2.isEmpty()) return;
  28963. var min = _box$2.min;
  28964. var max = _box$2.max;
  28965. /*
  28966. 5____4
  28967. 1/___0/|
  28968. | 6__|_7
  28969. 2/___3/
  28970. 0: max.x, max.y, max.z
  28971. 1: min.x, max.y, max.z
  28972. 2: min.x, min.y, max.z
  28973. 3: max.x, min.y, max.z
  28974. 4: max.x, max.y, min.z
  28975. 5: min.x, max.y, min.z
  28976. 6: min.x, min.y, min.z
  28977. 7: max.x, min.y, min.z
  28978. */
  28979. var position = this.geometry.attributes.position;
  28980. var array = position.array;
  28981. array[0] = max.x;
  28982. array[1] = max.y;
  28983. array[2] = max.z;
  28984. array[3] = min.x;
  28985. array[4] = max.y;
  28986. array[5] = max.z;
  28987. array[6] = min.x;
  28988. array[7] = min.y;
  28989. array[8] = max.z;
  28990. array[9] = max.x;
  28991. array[10] = min.y;
  28992. array[11] = max.z;
  28993. array[12] = max.x;
  28994. array[13] = max.y;
  28995. array[14] = min.z;
  28996. array[15] = min.x;
  28997. array[16] = max.y;
  28998. array[17] = min.z;
  28999. array[18] = min.x;
  29000. array[19] = min.y;
  29001. array[20] = min.z;
  29002. array[21] = max.x;
  29003. array[22] = min.y;
  29004. array[23] = min.z;
  29005. position.needsUpdate = true;
  29006. this.geometry.computeBoundingSphere();
  29007. };
  29008. BoxHelper.prototype.setFromObject = function (object) {
  29009. this.object = object;
  29010. this.update();
  29011. return this;
  29012. };
  29013. BoxHelper.prototype.copy = function (source) {
  29014. LineSegments.prototype.copy.call(this, source);
  29015. this.object = source.object;
  29016. return this;
  29017. };
  29018. BoxHelper.prototype.clone = function () {
  29019. return new this.constructor().copy(this);
  29020. };
  29021. /**
  29022. * @author WestLangley / http://github.com/WestLangley
  29023. */
  29024. function Box3Helper(box, color) {
  29025. this.type = 'Box3Helper';
  29026. this.box = box;
  29027. color = color || 0xffff00;
  29028. 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]);
  29029. 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];
  29030. var geometry = new BufferGeometry();
  29031. geometry.setIndex(new BufferAttribute(indices, 1));
  29032. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29033. LineSegments.call(this, geometry, new LineBasicMaterial({
  29034. color: color
  29035. }));
  29036. this.geometry.computeBoundingSphere();
  29037. }
  29038. Box3Helper.prototype = Object.create(LineSegments.prototype);
  29039. Box3Helper.prototype.constructor = Box3Helper;
  29040. Box3Helper.prototype.updateMatrixWorld = function (force) {
  29041. var box = this.box;
  29042. if (box.isEmpty()) return;
  29043. box.getCenter(this.position);
  29044. box.getSize(this.scale);
  29045. this.scale.multiplyScalar(0.5);
  29046. Object3D.prototype.updateMatrixWorld.call(this, force);
  29047. };
  29048. /**
  29049. * @author WestLangley / http://github.com/WestLangley
  29050. */
  29051. function PlaneHelper(plane, size, hex) {
  29052. this.type = 'PlaneHelper';
  29053. this.plane = plane;
  29054. this.size = size === undefined ? 1 : size;
  29055. var color = hex !== undefined ? hex : 0xffff00;
  29056. 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];
  29057. var geometry = new BufferGeometry();
  29058. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29059. geometry.computeBoundingSphere();
  29060. Line.call(this, geometry, new LineBasicMaterial({
  29061. color: color
  29062. })); //
  29063. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  29064. var geometry2 = new BufferGeometry();
  29065. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  29066. geometry2.computeBoundingSphere();
  29067. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  29068. color: color,
  29069. opacity: 0.2,
  29070. transparent: true,
  29071. depthWrite: false
  29072. })));
  29073. }
  29074. PlaneHelper.prototype = Object.create(Line.prototype);
  29075. PlaneHelper.prototype.constructor = PlaneHelper;
  29076. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  29077. var scale = -this.plane.constant;
  29078. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  29079. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  29080. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29081. this.lookAt(this.plane.normal);
  29082. Object3D.prototype.updateMatrixWorld.call(this, force);
  29083. };
  29084. /**
  29085. * @author WestLangley / http://github.com/WestLangley
  29086. * @author zz85 / http://github.com/zz85
  29087. * @author bhouston / http://clara.io
  29088. *
  29089. * Creates an arrow for visualizing directions
  29090. *
  29091. * Parameters:
  29092. * dir - Vector3
  29093. * origin - Vector3
  29094. * length - Number
  29095. * color - color in hex value
  29096. * headLength - Number
  29097. * headWidth - Number
  29098. */
  29099. var _axis = new Vector3();
  29100. var _lineGeometry, _coneGeometry;
  29101. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  29102. // dir is assumed to be normalized
  29103. Object3D.call(this);
  29104. if (dir === undefined) dir = new Vector3(0, 0, 1);
  29105. if (origin === undefined) origin = new Vector3(0, 0, 0);
  29106. if (length === undefined) length = 1;
  29107. if (color === undefined) color = 0xffff00;
  29108. if (headLength === undefined) headLength = 0.2 * length;
  29109. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29110. if (_lineGeometry === undefined) {
  29111. _lineGeometry = new BufferGeometry();
  29112. _lineGeometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  29113. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  29114. _coneGeometry.translate(0, -0.5, 0);
  29115. }
  29116. this.position.copy(origin);
  29117. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  29118. color: color
  29119. }));
  29120. this.line.matrixAutoUpdate = false;
  29121. this.add(this.line);
  29122. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  29123. color: color
  29124. }));
  29125. this.cone.matrixAutoUpdate = false;
  29126. this.add(this.cone);
  29127. this.setDirection(dir);
  29128. this.setLength(length, headLength, headWidth);
  29129. }
  29130. ArrowHelper.prototype = Object.create(Object3D.prototype);
  29131. ArrowHelper.prototype.constructor = ArrowHelper;
  29132. ArrowHelper.prototype.setDirection = function (dir) {
  29133. // dir is assumed to be normalized
  29134. if (dir.y > 0.99999) {
  29135. this.quaternion.set(0, 0, 0, 1);
  29136. } else if (dir.y < -0.99999) {
  29137. this.quaternion.set(1, 0, 0, 0);
  29138. } else {
  29139. _axis.set(dir.z, 0, -dir.x).normalize();
  29140. var radians = Math.acos(dir.y);
  29141. this.quaternion.setFromAxisAngle(_axis, radians);
  29142. }
  29143. };
  29144. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  29145. if (headLength === undefined) headLength = 0.2 * length;
  29146. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29147. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  29148. this.line.updateMatrix();
  29149. this.cone.scale.set(headWidth, headLength, headWidth);
  29150. this.cone.position.y = length;
  29151. this.cone.updateMatrix();
  29152. };
  29153. ArrowHelper.prototype.setColor = function (color) {
  29154. this.line.material.color.set(color);
  29155. this.cone.material.color.set(color);
  29156. };
  29157. ArrowHelper.prototype.copy = function (source) {
  29158. Object3D.prototype.copy.call(this, source, false);
  29159. this.line.copy(source.line);
  29160. this.cone.copy(source.cone);
  29161. return this;
  29162. };
  29163. ArrowHelper.prototype.clone = function () {
  29164. return new this.constructor().copy(this);
  29165. };
  29166. /**
  29167. * @author sroucheray / http://sroucheray.org/
  29168. * @author mrdoob / http://mrdoob.com/
  29169. */
  29170. function AxesHelper(size) {
  29171. size = size || 1;
  29172. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  29173. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  29174. var geometry = new BufferGeometry();
  29175. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  29176. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  29177. var material = new LineBasicMaterial({
  29178. vertexColors: VertexColors
  29179. });
  29180. LineSegments.call(this, geometry, material);
  29181. }
  29182. AxesHelper.prototype = Object.create(LineSegments.prototype);
  29183. AxesHelper.prototype.constructor = AxesHelper;
  29184. /**
  29185. * @author mrdoob / http://mrdoob.com/
  29186. */
  29187. function Face4(a, b, c, d, normal, color, materialIndex) {
  29188. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  29189. return new Face3(a, b, c, normal, color, materialIndex);
  29190. }
  29191. var LineStrip = 0;
  29192. exports.LineStrip = LineStrip;
  29193. var LinePieces = 1;
  29194. exports.LinePieces = LinePieces;
  29195. function MeshFaceMaterial(materials) {
  29196. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  29197. return materials;
  29198. }
  29199. function MultiMaterial(materials) {
  29200. if (materials === undefined) materials = [];
  29201. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  29202. materials.isMultiMaterial = true;
  29203. materials.materials = materials;
  29204. materials.clone = function () {
  29205. return materials.slice();
  29206. };
  29207. return materials;
  29208. }
  29209. function PointCloud(geometry, material) {
  29210. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  29211. return new Points(geometry, material);
  29212. }
  29213. function Particle(material) {
  29214. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  29215. return new Sprite(material);
  29216. }
  29217. function ParticleSystem(geometry, material) {
  29218. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  29219. return new Points(geometry, material);
  29220. }
  29221. function PointCloudMaterial(parameters) {
  29222. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  29223. return new PointsMaterial(parameters);
  29224. }
  29225. function ParticleBasicMaterial(parameters) {
  29226. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  29227. return new PointsMaterial(parameters);
  29228. }
  29229. function ParticleSystemMaterial(parameters) {
  29230. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  29231. return new PointsMaterial(parameters);
  29232. }
  29233. function Vertex(x, y, z) {
  29234. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  29235. return new Vector3(x, y, z);
  29236. } //
  29237. function DynamicBufferAttribute(array, itemSize) {
  29238. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.');
  29239. return new BufferAttribute(array, itemSize).setDynamic(true);
  29240. }
  29241. function Int8Attribute(array, itemSize) {
  29242. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  29243. return new Int8BufferAttribute(array, itemSize);
  29244. }
  29245. function Uint8Attribute(array, itemSize) {
  29246. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  29247. return new Uint8BufferAttribute(array, itemSize);
  29248. }
  29249. function Uint8ClampedAttribute(array, itemSize) {
  29250. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  29251. return new Uint8ClampedBufferAttribute(array, itemSize);
  29252. }
  29253. function Int16Attribute(array, itemSize) {
  29254. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  29255. return new Int16BufferAttribute(array, itemSize);
  29256. }
  29257. function Uint16Attribute(array, itemSize) {
  29258. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  29259. return new Uint16BufferAttribute(array, itemSize);
  29260. }
  29261. function Int32Attribute(array, itemSize) {
  29262. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  29263. return new Int32BufferAttribute(array, itemSize);
  29264. }
  29265. function Uint32Attribute(array, itemSize) {
  29266. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  29267. return new Uint32BufferAttribute(array, itemSize);
  29268. }
  29269. function Float32Attribute(array, itemSize) {
  29270. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  29271. return new Float32BufferAttribute(array, itemSize);
  29272. }
  29273. function Float64Attribute(array, itemSize) {
  29274. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  29275. return new Float64BufferAttribute(array, itemSize);
  29276. } //
  29277. Curve.create = function (construct, getPoint) {
  29278. console.log('THREE.Curve.create() has been deprecated');
  29279. construct.prototype = Object.create(Curve.prototype);
  29280. construct.prototype.constructor = construct;
  29281. construct.prototype.getPoint = getPoint;
  29282. return construct;
  29283. }; //
  29284. Object.assign(CurvePath.prototype, {
  29285. createPointsGeometry: function (divisions) {
  29286. 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)
  29287. var pts = this.getPoints(divisions);
  29288. return this.createGeometry(pts);
  29289. },
  29290. createSpacedPointsGeometry: function (divisions) {
  29291. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  29292. var pts = this.getSpacedPoints(divisions);
  29293. return this.createGeometry(pts);
  29294. },
  29295. createGeometry: function (points) {
  29296. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  29297. var geometry = new Geometry();
  29298. for (var i = 0, l = points.length; i < l; i++) {
  29299. var point = points[i];
  29300. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  29301. }
  29302. return geometry;
  29303. }
  29304. }); //
  29305. Object.assign(Path.prototype, {
  29306. fromPoints: function (points) {
  29307. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  29308. this.setFromPoints(points);
  29309. }
  29310. }); //
  29311. function ClosedSplineCurve3(points) {
  29312. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29313. CatmullRomCurve3.call(this, points);
  29314. this.type = 'catmullrom';
  29315. this.closed = true;
  29316. }
  29317. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29318. function SplineCurve3(points) {
  29319. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29320. CatmullRomCurve3.call(this, points);
  29321. this.type = 'catmullrom';
  29322. }
  29323. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29324. function Spline(points) {
  29325. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  29326. CatmullRomCurve3.call(this, points);
  29327. this.type = 'catmullrom';
  29328. }
  29329. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  29330. Object.assign(Spline.prototype, {
  29331. initFromArray: function ()
  29332. /* a */
  29333. {
  29334. console.error('THREE.Spline: .initFromArray() has been removed.');
  29335. },
  29336. getControlPointsArray: function ()
  29337. /* optionalTarget */
  29338. {
  29339. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  29340. },
  29341. reparametrizeByArcLength: function ()
  29342. /* samplingCoef */
  29343. {
  29344. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  29345. }
  29346. }); //
  29347. function AxisHelper(size) {
  29348. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  29349. return new AxesHelper(size);
  29350. }
  29351. function BoundingBoxHelper(object, color) {
  29352. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  29353. return new BoxHelper(object, color);
  29354. }
  29355. function EdgesHelper(object, hex) {
  29356. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29357. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29358. color: hex !== undefined ? hex : 0xffffff
  29359. }));
  29360. }
  29361. GridHelper.prototype.setColors = function () {
  29362. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29363. };
  29364. SkeletonHelper.prototype.update = function () {
  29365. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29366. };
  29367. function WireframeHelper(object, hex) {
  29368. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29369. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29370. color: hex !== undefined ? hex : 0xffffff
  29371. }));
  29372. } //
  29373. Object.assign(Loader.prototype, {
  29374. extractUrlBase: function (url) {
  29375. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29376. return LoaderUtils.extractUrlBase(url);
  29377. }
  29378. });
  29379. Loader.Handlers = {
  29380. add: function ()
  29381. /* regex, loader */
  29382. {
  29383. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29384. },
  29385. get: function ()
  29386. /* file */
  29387. {
  29388. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29389. }
  29390. };
  29391. function XHRLoader(manager) {
  29392. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29393. return new FileLoader(manager);
  29394. }
  29395. function BinaryTextureLoader(manager) {
  29396. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29397. return new DataTextureLoader(manager);
  29398. }
  29399. Object.assign(ObjectLoader.prototype, {
  29400. setTexturePath: function (value) {
  29401. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  29402. return this.setResourcePath(value);
  29403. }
  29404. }); //
  29405. Object.assign(Box2.prototype, {
  29406. center: function (optionalTarget) {
  29407. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29408. return this.getCenter(optionalTarget);
  29409. },
  29410. empty: function () {
  29411. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29412. return this.isEmpty();
  29413. },
  29414. isIntersectionBox: function (box) {
  29415. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29416. return this.intersectsBox(box);
  29417. },
  29418. size: function (optionalTarget) {
  29419. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29420. return this.getSize(optionalTarget);
  29421. }
  29422. });
  29423. Object.assign(Box3.prototype, {
  29424. center: function (optionalTarget) {
  29425. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29426. return this.getCenter(optionalTarget);
  29427. },
  29428. empty: function () {
  29429. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29430. return this.isEmpty();
  29431. },
  29432. isIntersectionBox: function (box) {
  29433. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29434. return this.intersectsBox(box);
  29435. },
  29436. isIntersectionSphere: function (sphere) {
  29437. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29438. return this.intersectsSphere(sphere);
  29439. },
  29440. size: function (optionalTarget) {
  29441. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29442. return this.getSize(optionalTarget);
  29443. }
  29444. });
  29445. Line3.prototype.center = function (optionalTarget) {
  29446. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29447. return this.getCenter(optionalTarget);
  29448. };
  29449. Object.assign(_Math, {
  29450. random16: function () {
  29451. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29452. return Math.random();
  29453. },
  29454. nearestPowerOfTwo: function (value) {
  29455. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29456. return _Math.floorPowerOfTwo(value);
  29457. },
  29458. nextPowerOfTwo: function (value) {
  29459. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29460. return _Math.ceilPowerOfTwo(value);
  29461. }
  29462. });
  29463. Object.assign(Matrix3.prototype, {
  29464. flattenToArrayOffset: function (array, offset) {
  29465. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29466. return this.toArray(array, offset);
  29467. },
  29468. multiplyVector3: function (vector) {
  29469. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29470. return vector.applyMatrix3(this);
  29471. },
  29472. multiplyVector3Array: function ()
  29473. /* a */
  29474. {
  29475. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29476. },
  29477. applyToBuffer: function (buffer
  29478. /*, offset, length */
  29479. ) {
  29480. console.warn('THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29481. return this.applyToBufferAttribute(buffer);
  29482. },
  29483. applyToVector3Array: function ()
  29484. /* array, offset, length */
  29485. {
  29486. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29487. }
  29488. });
  29489. Object.assign(Matrix4.prototype, {
  29490. extractPosition: function (m) {
  29491. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29492. return this.copyPosition(m);
  29493. },
  29494. flattenToArrayOffset: function (array, offset) {
  29495. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29496. return this.toArray(array, offset);
  29497. },
  29498. getPosition: function () {
  29499. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29500. return new Vector3().setFromMatrixColumn(this, 3);
  29501. },
  29502. setRotationFromQuaternion: function (q) {
  29503. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29504. return this.makeRotationFromQuaternion(q);
  29505. },
  29506. multiplyToArray: function () {
  29507. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29508. },
  29509. multiplyVector3: function (vector) {
  29510. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29511. return vector.applyMatrix4(this);
  29512. },
  29513. multiplyVector4: function (vector) {
  29514. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29515. return vector.applyMatrix4(this);
  29516. },
  29517. multiplyVector3Array: function ()
  29518. /* a */
  29519. {
  29520. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29521. },
  29522. rotateAxis: function (v) {
  29523. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29524. v.transformDirection(this);
  29525. },
  29526. crossVector: function (vector) {
  29527. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29528. return vector.applyMatrix4(this);
  29529. },
  29530. translate: function () {
  29531. console.error('THREE.Matrix4: .translate() has been removed.');
  29532. },
  29533. rotateX: function () {
  29534. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29535. },
  29536. rotateY: function () {
  29537. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29538. },
  29539. rotateZ: function () {
  29540. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29541. },
  29542. rotateByAxis: function () {
  29543. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29544. },
  29545. applyToBuffer: function (buffer
  29546. /*, offset, length */
  29547. ) {
  29548. console.warn('THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29549. return this.applyToBufferAttribute(buffer);
  29550. },
  29551. applyToVector3Array: function ()
  29552. /* array, offset, length */
  29553. {
  29554. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29555. },
  29556. makeFrustum: function (left, right, bottom, top, near, far) {
  29557. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29558. return this.makePerspective(left, right, top, bottom, near, far);
  29559. }
  29560. });
  29561. Plane.prototype.isIntersectionLine = function (line) {
  29562. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29563. return this.intersectsLine(line);
  29564. };
  29565. Quaternion.prototype.multiplyVector3 = function (vector) {
  29566. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29567. return vector.applyQuaternion(this);
  29568. };
  29569. Object.assign(Ray.prototype, {
  29570. isIntersectionBox: function (box) {
  29571. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29572. return this.intersectsBox(box);
  29573. },
  29574. isIntersectionPlane: function (plane) {
  29575. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29576. return this.intersectsPlane(plane);
  29577. },
  29578. isIntersectionSphere: function (sphere) {
  29579. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29580. return this.intersectsSphere(sphere);
  29581. }
  29582. });
  29583. Object.assign(Triangle.prototype, {
  29584. area: function () {
  29585. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29586. return this.getArea();
  29587. },
  29588. barycoordFromPoint: function (point, target) {
  29589. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29590. return this.getBarycoord(point, target);
  29591. },
  29592. midpoint: function (target) {
  29593. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29594. return this.getMidpoint(target);
  29595. },
  29596. normal: function (target) {
  29597. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29598. return this.getNormal(target);
  29599. },
  29600. plane: function (target) {
  29601. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29602. return this.getPlane(target);
  29603. }
  29604. });
  29605. Object.assign(Triangle, {
  29606. barycoordFromPoint: function (point, a, b, c, target) {
  29607. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29608. return Triangle.getBarycoord(point, a, b, c, target);
  29609. },
  29610. normal: function (a, b, c, target) {
  29611. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29612. return Triangle.getNormal(a, b, c, target);
  29613. }
  29614. });
  29615. Object.assign(Shape.prototype, {
  29616. extractAllPoints: function (divisions) {
  29617. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29618. return this.extractPoints(divisions);
  29619. },
  29620. extrude: function (options) {
  29621. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29622. return new ExtrudeGeometry(this, options);
  29623. },
  29624. makeGeometry: function (options) {
  29625. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29626. return new ShapeGeometry(this, options);
  29627. }
  29628. });
  29629. Object.assign(Vector2.prototype, {
  29630. fromAttribute: function (attribute, index, offset) {
  29631. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29632. return this.fromBufferAttribute(attribute, index, offset);
  29633. },
  29634. distanceToManhattan: function (v) {
  29635. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29636. return this.manhattanDistanceTo(v);
  29637. },
  29638. lengthManhattan: function () {
  29639. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29640. return this.manhattanLength();
  29641. }
  29642. });
  29643. Object.assign(Vector3.prototype, {
  29644. setEulerFromRotationMatrix: function () {
  29645. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29646. },
  29647. setEulerFromQuaternion: function () {
  29648. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29649. },
  29650. getPositionFromMatrix: function (m) {
  29651. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29652. return this.setFromMatrixPosition(m);
  29653. },
  29654. getScaleFromMatrix: function (m) {
  29655. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29656. return this.setFromMatrixScale(m);
  29657. },
  29658. getColumnFromMatrix: function (index, matrix) {
  29659. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29660. return this.setFromMatrixColumn(matrix, index);
  29661. },
  29662. applyProjection: function (m) {
  29663. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29664. return this.applyMatrix4(m);
  29665. },
  29666. fromAttribute: function (attribute, index, offset) {
  29667. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29668. return this.fromBufferAttribute(attribute, index, offset);
  29669. },
  29670. distanceToManhattan: function (v) {
  29671. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29672. return this.manhattanDistanceTo(v);
  29673. },
  29674. lengthManhattan: function () {
  29675. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29676. return this.manhattanLength();
  29677. }
  29678. });
  29679. Object.assign(Vector4.prototype, {
  29680. fromAttribute: function (attribute, index, offset) {
  29681. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29682. return this.fromBufferAttribute(attribute, index, offset);
  29683. },
  29684. lengthManhattan: function () {
  29685. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29686. return this.manhattanLength();
  29687. }
  29688. }); //
  29689. Object.assign(Geometry.prototype, {
  29690. computeTangents: function () {
  29691. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29692. },
  29693. computeLineDistances: function () {
  29694. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29695. }
  29696. });
  29697. Object.assign(Object3D.prototype, {
  29698. getChildByName: function (name) {
  29699. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29700. return this.getObjectByName(name);
  29701. },
  29702. renderDepth: function () {
  29703. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29704. },
  29705. translate: function (distance, axis) {
  29706. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29707. return this.translateOnAxis(axis, distance);
  29708. },
  29709. getWorldRotation: function () {
  29710. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29711. }
  29712. });
  29713. Object.defineProperties(Object3D.prototype, {
  29714. eulerOrder: {
  29715. get: function () {
  29716. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29717. return this.rotation.order;
  29718. },
  29719. set: function (value) {
  29720. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29721. this.rotation.order = value;
  29722. }
  29723. },
  29724. useQuaternion: {
  29725. get: function () {
  29726. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29727. },
  29728. set: function () {
  29729. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29730. }
  29731. }
  29732. });
  29733. Object.defineProperties(LOD.prototype, {
  29734. objects: {
  29735. get: function () {
  29736. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29737. return this.levels;
  29738. }
  29739. }
  29740. });
  29741. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  29742. get: function () {
  29743. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29744. },
  29745. set: function () {
  29746. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29747. }
  29748. });
  29749. SkinnedMesh.prototype.initBones = function () {
  29750. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  29751. };
  29752. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  29753. get: function () {
  29754. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29755. return this.arcLengthDivisions;
  29756. },
  29757. set: function (value) {
  29758. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29759. this.arcLengthDivisions = value;
  29760. }
  29761. }); //
  29762. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  29763. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  29764. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  29765. this.setFocalLength(focalLength);
  29766. }; //
  29767. Object.defineProperties(Light.prototype, {
  29768. onlyShadow: {
  29769. set: function () {
  29770. console.warn('THREE.Light: .onlyShadow has been removed.');
  29771. }
  29772. },
  29773. shadowCameraFov: {
  29774. set: function (value) {
  29775. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  29776. this.shadow.camera.fov = value;
  29777. }
  29778. },
  29779. shadowCameraLeft: {
  29780. set: function (value) {
  29781. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  29782. this.shadow.camera.left = value;
  29783. }
  29784. },
  29785. shadowCameraRight: {
  29786. set: function (value) {
  29787. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  29788. this.shadow.camera.right = value;
  29789. }
  29790. },
  29791. shadowCameraTop: {
  29792. set: function (value) {
  29793. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  29794. this.shadow.camera.top = value;
  29795. }
  29796. },
  29797. shadowCameraBottom: {
  29798. set: function (value) {
  29799. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  29800. this.shadow.camera.bottom = value;
  29801. }
  29802. },
  29803. shadowCameraNear: {
  29804. set: function (value) {
  29805. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  29806. this.shadow.camera.near = value;
  29807. }
  29808. },
  29809. shadowCameraFar: {
  29810. set: function (value) {
  29811. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  29812. this.shadow.camera.far = value;
  29813. }
  29814. },
  29815. shadowCameraVisible: {
  29816. set: function () {
  29817. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  29818. }
  29819. },
  29820. shadowBias: {
  29821. set: function (value) {
  29822. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  29823. this.shadow.bias = value;
  29824. }
  29825. },
  29826. shadowDarkness: {
  29827. set: function () {
  29828. console.warn('THREE.Light: .shadowDarkness has been removed.');
  29829. }
  29830. },
  29831. shadowMapWidth: {
  29832. set: function (value) {
  29833. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  29834. this.shadow.mapSize.width = value;
  29835. }
  29836. },
  29837. shadowMapHeight: {
  29838. set: function (value) {
  29839. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  29840. this.shadow.mapSize.height = value;
  29841. }
  29842. }
  29843. }); //
  29844. Object.defineProperties(BufferAttribute.prototype, {
  29845. length: {
  29846. get: function () {
  29847. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  29848. return this.array.length;
  29849. }
  29850. }
  29851. });
  29852. Object.assign(BufferAttribute.prototype, {
  29853. copyIndicesArray: function ()
  29854. /* indices */
  29855. {
  29856. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  29857. },
  29858. setArray: function (array) {
  29859. console.warn('THREE.BufferAttribute: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29860. this.count = array !== undefined ? array.length / this.itemSize : 0;
  29861. this.array = array;
  29862. return this;
  29863. }
  29864. });
  29865. Object.assign(BufferGeometry.prototype, {
  29866. addIndex: function (index) {
  29867. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  29868. this.setIndex(index);
  29869. },
  29870. addDrawCall: function (start, count, indexOffset) {
  29871. if (indexOffset !== undefined) {
  29872. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  29873. }
  29874. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  29875. this.addGroup(start, count);
  29876. },
  29877. clearDrawCalls: function () {
  29878. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  29879. this.clearGroups();
  29880. },
  29881. computeTangents: function () {
  29882. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  29883. },
  29884. computeOffsets: function () {
  29885. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  29886. }
  29887. });
  29888. Object.defineProperties(BufferGeometry.prototype, {
  29889. drawcalls: {
  29890. get: function () {
  29891. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  29892. return this.groups;
  29893. }
  29894. },
  29895. offsets: {
  29896. get: function () {
  29897. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  29898. return this.groups;
  29899. }
  29900. }
  29901. });
  29902. Object.assign(InterleavedBuffer.prototype, {
  29903. setArray: function (array) {
  29904. console.warn('THREE.InterleavedBuffer: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29905. this.count = array !== undefined ? array.length / this.stride : 0;
  29906. this.array = array;
  29907. return this;
  29908. }
  29909. }); //
  29910. Object.assign(ExtrudeBufferGeometry.prototype, {
  29911. getArrays: function () {
  29912. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  29913. },
  29914. addShapeList: function () {
  29915. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  29916. },
  29917. addShape: function () {
  29918. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  29919. }
  29920. }); //
  29921. Object.defineProperties(Uniform.prototype, {
  29922. dynamic: {
  29923. set: function () {
  29924. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  29925. }
  29926. },
  29927. onUpdate: {
  29928. value: function () {
  29929. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  29930. return this;
  29931. }
  29932. }
  29933. }); //
  29934. Object.defineProperties(Material.prototype, {
  29935. wrapAround: {
  29936. get: function () {
  29937. console.warn('THREE.Material: .wrapAround has been removed.');
  29938. },
  29939. set: function () {
  29940. console.warn('THREE.Material: .wrapAround has been removed.');
  29941. }
  29942. },
  29943. overdraw: {
  29944. get: function () {
  29945. console.warn('THREE.Material: .overdraw has been removed.');
  29946. },
  29947. set: function () {
  29948. console.warn('THREE.Material: .overdraw has been removed.');
  29949. }
  29950. },
  29951. wrapRGB: {
  29952. get: function () {
  29953. console.warn('THREE.Material: .wrapRGB has been removed.');
  29954. return new Color();
  29955. }
  29956. },
  29957. shading: {
  29958. get: function () {
  29959. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29960. },
  29961. set: function (value) {
  29962. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29963. this.flatShading = value === FlatShading;
  29964. }
  29965. },
  29966. stencilMask: {
  29967. get: function () {
  29968. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29969. return this.stencilFuncMask;
  29970. },
  29971. set: function (value) {
  29972. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29973. this.stencilFuncMask = value;
  29974. }
  29975. }
  29976. });
  29977. Object.defineProperties(MeshPhongMaterial.prototype, {
  29978. metal: {
  29979. get: function () {
  29980. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  29981. return false;
  29982. },
  29983. set: function () {
  29984. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  29985. }
  29986. }
  29987. });
  29988. Object.defineProperties(ShaderMaterial.prototype, {
  29989. derivatives: {
  29990. get: function () {
  29991. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29992. return this.extensions.derivatives;
  29993. },
  29994. set: function (value) {
  29995. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29996. this.extensions.derivatives = value;
  29997. }
  29998. }
  29999. }); //
  30000. Object.assign(WebGLRenderer.prototype, {
  30001. clearTarget: function (renderTarget, color, depth, stencil) {
  30002. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  30003. this.setRenderTarget(renderTarget);
  30004. this.clear(color, depth, stencil);
  30005. },
  30006. animate: function (callback) {
  30007. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  30008. this.setAnimationLoop(callback);
  30009. },
  30010. getCurrentRenderTarget: function () {
  30011. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  30012. return this.getRenderTarget();
  30013. },
  30014. getMaxAnisotropy: function () {
  30015. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  30016. return this.capabilities.getMaxAnisotropy();
  30017. },
  30018. getPrecision: function () {
  30019. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  30020. return this.capabilities.precision;
  30021. },
  30022. resetGLState: function () {
  30023. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  30024. return this.state.reset();
  30025. },
  30026. supportsFloatTextures: function () {
  30027. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  30028. return this.extensions.get('OES_texture_float');
  30029. },
  30030. supportsHalfFloatTextures: function () {
  30031. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  30032. return this.extensions.get('OES_texture_half_float');
  30033. },
  30034. supportsStandardDerivatives: function () {
  30035. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  30036. return this.extensions.get('OES_standard_derivatives');
  30037. },
  30038. supportsCompressedTextureS3TC: function () {
  30039. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  30040. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  30041. },
  30042. supportsCompressedTexturePVRTC: function () {
  30043. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  30044. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  30045. },
  30046. supportsBlendMinMax: function () {
  30047. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  30048. return this.extensions.get('EXT_blend_minmax');
  30049. },
  30050. supportsVertexTextures: function () {
  30051. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  30052. return this.capabilities.vertexTextures;
  30053. },
  30054. supportsInstancedArrays: function () {
  30055. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  30056. return this.extensions.get('ANGLE_instanced_arrays');
  30057. },
  30058. enableScissorTest: function (boolean) {
  30059. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  30060. this.setScissorTest(boolean);
  30061. },
  30062. initMaterial: function () {
  30063. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  30064. },
  30065. addPrePlugin: function () {
  30066. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  30067. },
  30068. addPostPlugin: function () {
  30069. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  30070. },
  30071. updateShadowMap: function () {
  30072. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  30073. },
  30074. setFaceCulling: function () {
  30075. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  30076. },
  30077. allocTextureUnit: function () {
  30078. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  30079. },
  30080. setTexture: function () {
  30081. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  30082. },
  30083. setTexture2D: function () {
  30084. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  30085. },
  30086. setTextureCube: function () {
  30087. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  30088. },
  30089. getActiveMipMapLevel: function () {
  30090. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  30091. return this.getActiveMipmapLevel();
  30092. }
  30093. });
  30094. Object.defineProperties(WebGLRenderer.prototype, {
  30095. shadowMapEnabled: {
  30096. get: function () {
  30097. return this.shadowMap.enabled;
  30098. },
  30099. set: function (value) {
  30100. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  30101. this.shadowMap.enabled = value;
  30102. }
  30103. },
  30104. shadowMapType: {
  30105. get: function () {
  30106. return this.shadowMap.type;
  30107. },
  30108. set: function (value) {
  30109. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  30110. this.shadowMap.type = value;
  30111. }
  30112. },
  30113. shadowMapCullFace: {
  30114. get: function () {
  30115. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30116. return undefined;
  30117. },
  30118. set: function ()
  30119. /* value */
  30120. {
  30121. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30122. }
  30123. },
  30124. context: {
  30125. get: function () {
  30126. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  30127. return this.getContext();
  30128. }
  30129. }
  30130. });
  30131. Object.defineProperties(WebGLShadowMap.prototype, {
  30132. cullFace: {
  30133. get: function () {
  30134. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30135. return undefined;
  30136. },
  30137. set: function ()
  30138. /* cullFace */
  30139. {
  30140. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30141. }
  30142. },
  30143. renderReverseSided: {
  30144. get: function () {
  30145. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30146. return undefined;
  30147. },
  30148. set: function () {
  30149. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30150. }
  30151. },
  30152. renderSingleSided: {
  30153. get: function () {
  30154. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30155. return undefined;
  30156. },
  30157. set: function () {
  30158. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30159. }
  30160. }
  30161. }); //
  30162. Object.defineProperties(WebGLRenderTargetCube.prototype, {
  30163. activeCubeFace: {
  30164. set: function ()
  30165. /* value */
  30166. {
  30167. console.warn('THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().');
  30168. }
  30169. },
  30170. activeMipMapLevel: {
  30171. set: function ()
  30172. /* value */
  30173. {
  30174. console.warn('THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().');
  30175. }
  30176. }
  30177. }); //
  30178. Object.defineProperties(WebGLRenderTarget.prototype, {
  30179. wrapS: {
  30180. get: function () {
  30181. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30182. return this.texture.wrapS;
  30183. },
  30184. set: function (value) {
  30185. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30186. this.texture.wrapS = value;
  30187. }
  30188. },
  30189. wrapT: {
  30190. get: function () {
  30191. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30192. return this.texture.wrapT;
  30193. },
  30194. set: function (value) {
  30195. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30196. this.texture.wrapT = value;
  30197. }
  30198. },
  30199. magFilter: {
  30200. get: function () {
  30201. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30202. return this.texture.magFilter;
  30203. },
  30204. set: function (value) {
  30205. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30206. this.texture.magFilter = value;
  30207. }
  30208. },
  30209. minFilter: {
  30210. get: function () {
  30211. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30212. return this.texture.minFilter;
  30213. },
  30214. set: function (value) {
  30215. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30216. this.texture.minFilter = value;
  30217. }
  30218. },
  30219. anisotropy: {
  30220. get: function () {
  30221. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30222. return this.texture.anisotropy;
  30223. },
  30224. set: function (value) {
  30225. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30226. this.texture.anisotropy = value;
  30227. }
  30228. },
  30229. offset: {
  30230. get: function () {
  30231. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30232. return this.texture.offset;
  30233. },
  30234. set: function (value) {
  30235. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30236. this.texture.offset = value;
  30237. }
  30238. },
  30239. repeat: {
  30240. get: function () {
  30241. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30242. return this.texture.repeat;
  30243. },
  30244. set: function (value) {
  30245. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30246. this.texture.repeat = value;
  30247. }
  30248. },
  30249. format: {
  30250. get: function () {
  30251. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30252. return this.texture.format;
  30253. },
  30254. set: function (value) {
  30255. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30256. this.texture.format = value;
  30257. }
  30258. },
  30259. type: {
  30260. get: function () {
  30261. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30262. return this.texture.type;
  30263. },
  30264. set: function (value) {
  30265. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30266. this.texture.type = value;
  30267. }
  30268. },
  30269. generateMipmaps: {
  30270. get: function () {
  30271. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30272. return this.texture.generateMipmaps;
  30273. },
  30274. set: function (value) {
  30275. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30276. this.texture.generateMipmaps = value;
  30277. }
  30278. }
  30279. }); //
  30280. Object.defineProperties(WebVRManager.prototype, {
  30281. standing: {
  30282. set: function ()
  30283. /* value */
  30284. {
  30285. console.warn('THREE.WebVRManager: .standing has been removed.');
  30286. }
  30287. },
  30288. userHeight: {
  30289. set: function ()
  30290. /* value */
  30291. {
  30292. console.warn('THREE.WebVRManager: .userHeight has been removed.');
  30293. }
  30294. }
  30295. }); //
  30296. Audio.prototype.load = function (file) {
  30297. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30298. var scope = this;
  30299. var audioLoader = new AudioLoader();
  30300. audioLoader.load(file, function (buffer) {
  30301. scope.setBuffer(buffer);
  30302. });
  30303. return this;
  30304. };
  30305. AudioAnalyser.prototype.getData = function () {
  30306. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30307. return this.getFrequencyData();
  30308. }; //
  30309. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30310. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30311. return this.update(renderer, scene);
  30312. }; //
  30313. var GeometryUtils = {
  30314. merge: function (geometry1, geometry2, materialIndexOffset) {
  30315. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30316. var matrix;
  30317. if (geometry2.isMesh) {
  30318. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30319. matrix = geometry2.matrix;
  30320. geometry2 = geometry2.geometry;
  30321. }
  30322. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30323. },
  30324. center: function (geometry) {
  30325. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30326. return geometry.center();
  30327. }
  30328. };
  30329. exports.GeometryUtils = GeometryUtils;
  30330. ImageUtils.crossOrigin = undefined;
  30331. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30332. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30333. var loader = new TextureLoader();
  30334. loader.setCrossOrigin(this.crossOrigin);
  30335. var texture = loader.load(url, onLoad, undefined, onError);
  30336. if (mapping) texture.mapping = mapping;
  30337. return texture;
  30338. };
  30339. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30340. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30341. var loader = new CubeTextureLoader();
  30342. loader.setCrossOrigin(this.crossOrigin);
  30343. var texture = loader.load(urls, onLoad, undefined, onError);
  30344. if (mapping) texture.mapping = mapping;
  30345. return texture;
  30346. };
  30347. ImageUtils.loadCompressedTexture = function () {
  30348. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30349. };
  30350. ImageUtils.loadCompressedTextureCube = function () {
  30351. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30352. }; //
  30353. function CanvasRenderer() {
  30354. console.error('THREE.CanvasRenderer has been removed');
  30355. } //
  30356. function JSONLoader() {
  30357. console.error('THREE.JSONLoader has been removed.');
  30358. } //
  30359. var SceneUtils = {
  30360. createMultiMaterialObject: function ()
  30361. /* geometry, materials */
  30362. {
  30363. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30364. },
  30365. detach: function ()
  30366. /* child, parent, scene */
  30367. {
  30368. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30369. },
  30370. attach: function ()
  30371. /* child, scene, parent */
  30372. {
  30373. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30374. }
  30375. }; //
  30376. exports.SceneUtils = SceneUtils;
  30377. function LensFlare() {
  30378. console.error('THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js');
  30379. }
  30380. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30381. /* eslint-disable no-undef */
  30382. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30383. detail: {
  30384. revision: REVISION
  30385. }
  30386. }));
  30387. /* eslint-enable no-undef */
  30388. }
  30389. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  30390. "use strict";
  30391. Object.defineProperty(exports, "__esModule", {
  30392. value: true
  30393. });
  30394. exports.GLTFLoader = void 0;
  30395. var _threeModule = require("../../../build/three.module.js");
  30396. /**
  30397. * @author Rich Tibbett / https://github.com/richtr
  30398. * @author mrdoob / http://mrdoob.com/
  30399. * @author Tony Parisi / http://www.tonyparisi.com/
  30400. * @author Takahiro / https://github.com/takahirox
  30401. * @author Don McCurdy / https://www.donmccurdy.com
  30402. */
  30403. var GLTFLoader = function () {
  30404. function GLTFLoader(manager) {
  30405. _threeModule.Loader.call(this, manager);
  30406. this.dracoLoader = null;
  30407. this.ddsLoader = null;
  30408. }
  30409. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  30410. constructor: GLTFLoader,
  30411. load: function (url, onLoad, onProgress, onError) {
  30412. var scope = this;
  30413. var resourcePath;
  30414. if (this.resourcePath !== '') {
  30415. resourcePath = this.resourcePath;
  30416. } else if (this.path !== '') {
  30417. resourcePath = this.path;
  30418. } else {
  30419. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  30420. } // Tells the LoadingManager to track an extra item, which resolves after
  30421. // the model is fully loaded. This means the count of items loaded will
  30422. // be incorrect, but ensures manager.onLoad() does not fire early.
  30423. scope.manager.itemStart(url);
  30424. var _onError = function (e) {
  30425. if (onError) {
  30426. onError(e);
  30427. } else {
  30428. console.error(e);
  30429. }
  30430. scope.manager.itemError(url);
  30431. scope.manager.itemEnd(url);
  30432. };
  30433. var loader = new _threeModule.FileLoader(scope.manager);
  30434. loader.setPath(this.path);
  30435. loader.setResponseType('arraybuffer');
  30436. if (scope.crossOrigin === 'use-credentials') {
  30437. loader.setWithCredentials(true);
  30438. }
  30439. loader.load(url, function (data) {
  30440. try {
  30441. scope.parse(data, resourcePath, function (gltf) {
  30442. onLoad(gltf);
  30443. scope.manager.itemEnd(url);
  30444. }, _onError);
  30445. } catch (e) {
  30446. _onError(e);
  30447. }
  30448. }, onProgress, _onError);
  30449. },
  30450. setDRACOLoader: function (dracoLoader) {
  30451. this.dracoLoader = dracoLoader;
  30452. return this;
  30453. },
  30454. setDDSLoader: function (ddsLoader) {
  30455. this.ddsLoader = ddsLoader;
  30456. return this;
  30457. },
  30458. parse: function (data, path, onLoad, onError) {
  30459. var content;
  30460. var extensions = {};
  30461. if (typeof data === 'string') {
  30462. content = data;
  30463. } else {
  30464. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  30465. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  30466. try {
  30467. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  30468. } catch (error) {
  30469. if (onError) onError(error);
  30470. return;
  30471. }
  30472. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  30473. } else {
  30474. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  30475. }
  30476. }
  30477. var json = JSON.parse(content);
  30478. if (json.asset === undefined || json.asset.version[0] < 2) {
  30479. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.'));
  30480. return;
  30481. }
  30482. if (json.extensionsUsed) {
  30483. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  30484. var extensionName = json.extensionsUsed[i];
  30485. var extensionsRequired = json.extensionsRequired || [];
  30486. switch (extensionName) {
  30487. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  30488. extensions[extensionName] = new GLTFLightsExtension(json);
  30489. break;
  30490. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  30491. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  30492. break;
  30493. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  30494. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  30495. break;
  30496. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  30497. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  30498. break;
  30499. case EXTENSIONS.MSFT_TEXTURE_DDS:
  30500. extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = new GLTFTextureDDSExtension(this.ddsLoader);
  30501. break;
  30502. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  30503. extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = new GLTFTextureTransformExtension();
  30504. break;
  30505. default:
  30506. if (extensionsRequired.indexOf(extensionName) >= 0) {
  30507. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  30508. }
  30509. }
  30510. }
  30511. }
  30512. var parser = new GLTFParser(json, extensions, {
  30513. path: path || this.resourcePath || '',
  30514. crossOrigin: this.crossOrigin,
  30515. manager: this.manager
  30516. });
  30517. parser.parse(onLoad, onError);
  30518. }
  30519. });
  30520. /* GLTFREGISTRY */
  30521. function GLTFRegistry() {
  30522. var objects = {};
  30523. return {
  30524. get: function (key) {
  30525. return objects[key];
  30526. },
  30527. add: function (key, object) {
  30528. objects[key] = object;
  30529. },
  30530. remove: function (key) {
  30531. delete objects[key];
  30532. },
  30533. removeAll: function () {
  30534. objects = {};
  30535. }
  30536. };
  30537. }
  30538. /*********************************/
  30539. /********** EXTENSIONS ***********/
  30540. /*********************************/
  30541. var EXTENSIONS = {
  30542. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  30543. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  30544. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  30545. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  30546. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  30547. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  30548. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  30549. };
  30550. /**
  30551. * DDS Texture Extension
  30552. *
  30553. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  30554. *
  30555. */
  30556. function GLTFTextureDDSExtension(ddsLoader) {
  30557. if (!ddsLoader) {
  30558. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  30559. }
  30560. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  30561. this.ddsLoader = ddsLoader;
  30562. }
  30563. /**
  30564. * Punctual Lights Extension
  30565. *
  30566. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  30567. */
  30568. function GLTFLightsExtension(json) {
  30569. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  30570. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  30571. this.lightDefs = extension.lights || [];
  30572. }
  30573. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  30574. var lightDef = this.lightDefs[lightIndex];
  30575. var lightNode;
  30576. var color = new _threeModule.Color(0xffffff);
  30577. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  30578. var range = lightDef.range !== undefined ? lightDef.range : 0;
  30579. switch (lightDef.type) {
  30580. case 'directional':
  30581. lightNode = new _threeModule.DirectionalLight(color);
  30582. lightNode.target.position.set(0, 0, -1);
  30583. lightNode.add(lightNode.target);
  30584. break;
  30585. case 'point':
  30586. lightNode = new _threeModule.PointLight(color);
  30587. lightNode.distance = range;
  30588. break;
  30589. case 'spot':
  30590. lightNode = new _threeModule.SpotLight(color);
  30591. lightNode.distance = range; // Handle spotlight properties.
  30592. lightDef.spot = lightDef.spot || {};
  30593. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  30594. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  30595. lightNode.angle = lightDef.spot.outerConeAngle;
  30596. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  30597. lightNode.target.position.set(0, 0, -1);
  30598. lightNode.add(lightNode.target);
  30599. break;
  30600. default:
  30601. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  30602. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  30603. // here, because node-level parsing will only override position if explicitly specified.
  30604. lightNode.position.set(0, 0, 0);
  30605. lightNode.decay = 2;
  30606. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  30607. lightNode.name = lightDef.name || 'light_' + lightIndex;
  30608. return Promise.resolve(lightNode);
  30609. };
  30610. /**
  30611. * Unlit Materials Extension
  30612. *
  30613. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  30614. */
  30615. function GLTFMaterialsUnlitExtension() {
  30616. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  30617. }
  30618. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  30619. return _threeModule.MeshBasicMaterial;
  30620. };
  30621. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  30622. var pending = [];
  30623. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30624. materialParams.opacity = 1.0;
  30625. var metallicRoughness = materialDef.pbrMetallicRoughness;
  30626. if (metallicRoughness) {
  30627. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  30628. var array = metallicRoughness.baseColorFactor;
  30629. materialParams.color.fromArray(array);
  30630. materialParams.opacity = array[3];
  30631. }
  30632. if (metallicRoughness.baseColorTexture !== undefined) {
  30633. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  30634. }
  30635. }
  30636. return Promise.all(pending);
  30637. };
  30638. /* BINARY EXTENSION */
  30639. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  30640. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  30641. var BINARY_EXTENSION_CHUNK_TYPES = {
  30642. JSON: 0x4E4F534A,
  30643. BIN: 0x004E4942
  30644. };
  30645. function GLTFBinaryExtension(data) {
  30646. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  30647. this.content = null;
  30648. this.body = null;
  30649. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  30650. this.header = {
  30651. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  30652. version: headerView.getUint32(4, true),
  30653. length: headerView.getUint32(8, true)
  30654. };
  30655. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  30656. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  30657. } else if (this.header.version < 2.0) {
  30658. throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.');
  30659. }
  30660. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  30661. var chunkIndex = 0;
  30662. while (chunkIndex < chunkView.byteLength) {
  30663. var chunkLength = chunkView.getUint32(chunkIndex, true);
  30664. chunkIndex += 4;
  30665. var chunkType = chunkView.getUint32(chunkIndex, true);
  30666. chunkIndex += 4;
  30667. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  30668. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  30669. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  30670. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  30671. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  30672. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  30673. } // Clients must ignore chunks with unknown types.
  30674. chunkIndex += chunkLength;
  30675. }
  30676. if (this.content === null) {
  30677. throw new Error('THREE.GLTFLoader: JSON content not found.');
  30678. }
  30679. }
  30680. /**
  30681. * DRACO Mesh Compression Extension
  30682. *
  30683. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  30684. */
  30685. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  30686. if (!dracoLoader) {
  30687. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  30688. }
  30689. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  30690. this.json = json;
  30691. this.dracoLoader = dracoLoader;
  30692. }
  30693. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  30694. var json = this.json;
  30695. var dracoLoader = this.dracoLoader;
  30696. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  30697. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  30698. var threeAttributeMap = {};
  30699. var attributeNormalizedMap = {};
  30700. var attributeTypeMap = {};
  30701. for (var attributeName in gltfAttributeMap) {
  30702. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30703. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  30704. }
  30705. for (attributeName in primitive.attributes) {
  30706. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30707. if (gltfAttributeMap[attributeName] !== undefined) {
  30708. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  30709. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  30710. attributeTypeMap[threeAttributeName] = componentType;
  30711. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  30712. }
  30713. }
  30714. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  30715. return new Promise(function (resolve) {
  30716. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  30717. for (var attributeName in geometry.attributes) {
  30718. var attribute = geometry.attributes[attributeName];
  30719. var normalized = attributeNormalizedMap[attributeName];
  30720. if (normalized !== undefined) attribute.normalized = normalized;
  30721. }
  30722. resolve(geometry);
  30723. }, threeAttributeMap, attributeTypeMap);
  30724. });
  30725. });
  30726. };
  30727. /**
  30728. * Texture Transform Extension
  30729. *
  30730. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  30731. */
  30732. function GLTFTextureTransformExtension() {
  30733. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  30734. }
  30735. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  30736. texture = texture.clone();
  30737. if (transform.offset !== undefined) {
  30738. texture.offset.fromArray(transform.offset);
  30739. }
  30740. if (transform.rotation !== undefined) {
  30741. texture.rotation = transform.rotation;
  30742. }
  30743. if (transform.scale !== undefined) {
  30744. texture.repeat.fromArray(transform.scale);
  30745. }
  30746. if (transform.texCoord !== undefined) {
  30747. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  30748. }
  30749. texture.needsUpdate = true;
  30750. return texture;
  30751. };
  30752. /**
  30753. * Specular-Glossiness Extension
  30754. *
  30755. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  30756. */
  30757. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  30758. return {
  30759. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  30760. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  30761. getMaterialType: function () {
  30762. return _threeModule.ShaderMaterial;
  30763. },
  30764. extendParams: function (materialParams, materialDef, parser) {
  30765. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  30766. var shader = _threeModule.ShaderLib['standard'];
  30767. var uniforms = _threeModule.UniformsUtils.clone(shader.uniforms);
  30768. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  30769. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  30770. 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');
  30771. 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');
  30772. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n');
  30773. var fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;').replace('uniform float metalness;', 'uniform float glossiness;').replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk).replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk).replace('#include <roughnessmap_fragment>', specularMapFragmentChunk).replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk).replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk);
  30774. delete uniforms.roughness;
  30775. delete uniforms.metalness;
  30776. delete uniforms.roughnessMap;
  30777. delete uniforms.metalnessMap;
  30778. uniforms.specular = {
  30779. value: new _threeModule.Color().setHex(0x111111)
  30780. };
  30781. uniforms.glossiness = {
  30782. value: 0.5
  30783. };
  30784. uniforms.specularMap = {
  30785. value: null
  30786. };
  30787. uniforms.glossinessMap = {
  30788. value: null
  30789. };
  30790. materialParams.vertexShader = shader.vertexShader;
  30791. materialParams.fragmentShader = fragmentShader;
  30792. materialParams.uniforms = uniforms;
  30793. materialParams.defines = {
  30794. 'STANDARD': ''
  30795. };
  30796. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30797. materialParams.opacity = 1.0;
  30798. var pending = [];
  30799. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  30800. var array = pbrSpecularGlossiness.diffuseFactor;
  30801. materialParams.color.fromArray(array);
  30802. materialParams.opacity = array[3];
  30803. }
  30804. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  30805. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  30806. }
  30807. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  30808. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  30809. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  30810. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  30811. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  30812. }
  30813. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  30814. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  30815. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  30816. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  30817. }
  30818. return Promise.all(pending);
  30819. },
  30820. createMaterial: function (params) {
  30821. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  30822. var material = new _threeModule.ShaderMaterial({
  30823. defines: params.defines,
  30824. vertexShader: params.vertexShader,
  30825. fragmentShader: params.fragmentShader,
  30826. uniforms: params.uniforms,
  30827. fog: true,
  30828. lights: true,
  30829. opacity: params.opacity,
  30830. transparent: params.transparent
  30831. });
  30832. material.isGLTFSpecularGlossinessMaterial = true;
  30833. material.color = params.color;
  30834. material.map = params.map === undefined ? null : params.map;
  30835. material.lightMap = null;
  30836. material.lightMapIntensity = 1.0;
  30837. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  30838. material.aoMapIntensity = 1.0;
  30839. material.emissive = params.emissive;
  30840. material.emissiveIntensity = 1.0;
  30841. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  30842. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  30843. material.bumpScale = 1;
  30844. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  30845. if (params.normalScale) material.normalScale = params.normalScale;
  30846. material.displacementMap = null;
  30847. material.displacementScale = 1;
  30848. material.displacementBias = 0;
  30849. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  30850. material.specular = params.specular;
  30851. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  30852. material.glossiness = params.glossiness;
  30853. material.alphaMap = null;
  30854. material.envMap = params.envMap === undefined ? null : params.envMap;
  30855. material.envMapIntensity = 1.0;
  30856. material.refractionRatio = 0.98;
  30857. material.extensions.derivatives = true;
  30858. return material;
  30859. },
  30860. /**
  30861. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  30862. * copy only properties it knows about or inherits, and misses many properties that would
  30863. * normally be defined by MeshStandardMaterial.
  30864. *
  30865. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  30866. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  30867. * AND also updating `.onBeforeRender` on the parent mesh.
  30868. *
  30869. * @param {ShaderMaterial} source
  30870. * @return {ShaderMaterial}
  30871. */
  30872. cloneMaterial: function (source) {
  30873. var target = source.clone();
  30874. target.isGLTFSpecularGlossinessMaterial = true;
  30875. var params = this.specularGlossinessParams;
  30876. for (var i = 0, il = params.length; i < il; i++) {
  30877. var value = source[params[i]];
  30878. target[params[i]] = value && value.isColor ? value.clone() : value;
  30879. }
  30880. return target;
  30881. },
  30882. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  30883. refreshUniforms: function (renderer, scene, camera, geometry, material) {
  30884. if (material.isGLTFSpecularGlossinessMaterial !== true) {
  30885. return;
  30886. }
  30887. var uniforms = material.uniforms;
  30888. var defines = material.defines;
  30889. uniforms.opacity.value = material.opacity;
  30890. uniforms.diffuse.value.copy(material.color);
  30891. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  30892. uniforms.map.value = material.map;
  30893. uniforms.specularMap.value = material.specularMap;
  30894. uniforms.alphaMap.value = material.alphaMap;
  30895. uniforms.lightMap.value = material.lightMap;
  30896. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  30897. uniforms.aoMap.value = material.aoMap;
  30898. uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities
  30899. // 1. color map
  30900. // 2. specular map
  30901. // 3. normal map
  30902. // 4. bump map
  30903. // 5. alpha map
  30904. // 6. emissive map
  30905. var uvScaleMap;
  30906. if (material.map) {
  30907. uvScaleMap = material.map;
  30908. } else if (material.specularMap) {
  30909. uvScaleMap = material.specularMap;
  30910. } else if (material.displacementMap) {
  30911. uvScaleMap = material.displacementMap;
  30912. } else if (material.normalMap) {
  30913. uvScaleMap = material.normalMap;
  30914. } else if (material.bumpMap) {
  30915. uvScaleMap = material.bumpMap;
  30916. } else if (material.glossinessMap) {
  30917. uvScaleMap = material.glossinessMap;
  30918. } else if (material.alphaMap) {
  30919. uvScaleMap = material.alphaMap;
  30920. } else if (material.emissiveMap) {
  30921. uvScaleMap = material.emissiveMap;
  30922. }
  30923. if (uvScaleMap !== undefined) {
  30924. // backwards compatibility
  30925. if (uvScaleMap.isWebGLRenderTarget) {
  30926. uvScaleMap = uvScaleMap.texture;
  30927. }
  30928. if (uvScaleMap.matrixAutoUpdate === true) {
  30929. uvScaleMap.updateMatrix();
  30930. }
  30931. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  30932. }
  30933. if (material.envMap) {
  30934. uniforms.envMap.value = material.envMap;
  30935. uniforms.envMapIntensity.value = material.envMapIntensity; // don't flip CubeTexture envMaps, flip everything else:
  30936. // WebGLRenderTargetCube will be flipped for backwards compatibility
  30937. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  30938. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  30939. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  30940. uniforms.reflectivity.value = material.reflectivity;
  30941. uniforms.refractionRatio.value = material.refractionRatio;
  30942. uniforms.maxMipLevel.value = renderer.properties.get(material.envMap).__maxMipLevel;
  30943. }
  30944. uniforms.specular.value.copy(material.specular);
  30945. uniforms.glossiness.value = material.glossiness;
  30946. uniforms.glossinessMap.value = material.glossinessMap;
  30947. uniforms.emissiveMap.value = material.emissiveMap;
  30948. uniforms.bumpMap.value = material.bumpMap;
  30949. uniforms.normalMap.value = material.normalMap;
  30950. uniforms.displacementMap.value = material.displacementMap;
  30951. uniforms.displacementScale.value = material.displacementScale;
  30952. uniforms.displacementBias.value = material.displacementBias;
  30953. if (uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined) {
  30954. defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  30955. defines.USE_ROUGHNESSMAP = '';
  30956. }
  30957. if (uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined) {
  30958. delete defines.USE_GLOSSINESSMAP;
  30959. delete defines.USE_ROUGHNESSMAP;
  30960. }
  30961. }
  30962. };
  30963. }
  30964. /*********************************/
  30965. /********** INTERPOLATION ********/
  30966. /*********************************/
  30967. // Spline Interpolation
  30968. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  30969. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  30970. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  30971. }
  30972. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  30973. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  30974. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  30975. // Copies a sample value to the result buffer. See description of glTF
  30976. // CUBICSPLINE values layout in interpolate_() function below.
  30977. var result = this.resultBuffer,
  30978. values = this.sampleValues,
  30979. valueSize = this.valueSize,
  30980. offset = index * valueSize * 3 + valueSize;
  30981. for (var i = 0; i !== valueSize; i++) {
  30982. result[i] = values[offset + i];
  30983. }
  30984. return result;
  30985. };
  30986. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30987. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30988. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  30989. var result = this.resultBuffer;
  30990. var values = this.sampleValues;
  30991. var stride = this.valueSize;
  30992. var stride2 = stride * 2;
  30993. var stride3 = stride * 3;
  30994. var td = t1 - t0;
  30995. var p = (t - t0) / td;
  30996. var pp = p * p;
  30997. var ppp = pp * p;
  30998. var offset1 = i1 * stride3;
  30999. var offset0 = offset1 - stride3;
  31000. var s2 = -2 * ppp + 3 * pp;
  31001. var s3 = ppp - pp;
  31002. var s0 = 1 - s2;
  31003. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  31004. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  31005. for (var i = 0; i !== stride; i++) {
  31006. var p0 = values[offset0 + i + stride]; // splineVertex_k
  31007. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  31008. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  31009. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  31010. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  31011. }
  31012. return result;
  31013. };
  31014. /*********************************/
  31015. /********** INTERNALS ************/
  31016. /*********************************/
  31017. /* CONSTANTS */
  31018. var WEBGL_CONSTANTS = {
  31019. FLOAT: 5126,
  31020. //FLOAT_MAT2: 35674,
  31021. FLOAT_MAT3: 35675,
  31022. FLOAT_MAT4: 35676,
  31023. FLOAT_VEC2: 35664,
  31024. FLOAT_VEC3: 35665,
  31025. FLOAT_VEC4: 35666,
  31026. LINEAR: 9729,
  31027. REPEAT: 10497,
  31028. SAMPLER_2D: 35678,
  31029. POINTS: 0,
  31030. LINES: 1,
  31031. LINE_LOOP: 2,
  31032. LINE_STRIP: 3,
  31033. TRIANGLES: 4,
  31034. TRIANGLE_STRIP: 5,
  31035. TRIANGLE_FAN: 6,
  31036. UNSIGNED_BYTE: 5121,
  31037. UNSIGNED_SHORT: 5123
  31038. };
  31039. var WEBGL_COMPONENT_TYPES = {
  31040. 5120: Int8Array,
  31041. 5121: Uint8Array,
  31042. 5122: Int16Array,
  31043. 5123: Uint16Array,
  31044. 5125: Uint32Array,
  31045. 5126: Float32Array
  31046. };
  31047. var WEBGL_FILTERS = {
  31048. 9728: _threeModule.NearestFilter,
  31049. 9729: _threeModule.LinearFilter,
  31050. 9984: _threeModule.NearestMipmapNearestFilter,
  31051. 9985: _threeModule.LinearMipmapNearestFilter,
  31052. 9986: _threeModule.NearestMipmapLinearFilter,
  31053. 9987: _threeModule.LinearMipmapLinearFilter
  31054. };
  31055. var WEBGL_WRAPPINGS = {
  31056. 33071: _threeModule.ClampToEdgeWrapping,
  31057. 33648: _threeModule.MirroredRepeatWrapping,
  31058. 10497: _threeModule.RepeatWrapping
  31059. };
  31060. var WEBGL_TYPE_SIZES = {
  31061. 'SCALAR': 1,
  31062. 'VEC2': 2,
  31063. 'VEC3': 3,
  31064. 'VEC4': 4,
  31065. 'MAT2': 4,
  31066. 'MAT3': 9,
  31067. 'MAT4': 16
  31068. };
  31069. var ATTRIBUTES = {
  31070. POSITION: 'position',
  31071. NORMAL: 'normal',
  31072. TANGENT: 'tangent',
  31073. TEXCOORD_0: 'uv',
  31074. TEXCOORD_1: 'uv2',
  31075. COLOR_0: 'color',
  31076. WEIGHTS_0: 'skinWeight',
  31077. JOINTS_0: 'skinIndex'
  31078. };
  31079. var PATH_PROPERTIES = {
  31080. scale: 'scale',
  31081. translation: 'position',
  31082. rotation: 'quaternion',
  31083. weights: 'morphTargetInfluences'
  31084. };
  31085. var INTERPOLATION = {
  31086. CUBICSPLINE: undefined,
  31087. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  31088. // keyframe track will be initialized with a default interpolation type, then modified.
  31089. LINEAR: _threeModule.InterpolateLinear,
  31090. STEP: _threeModule.InterpolateDiscrete
  31091. };
  31092. var ALPHA_MODES = {
  31093. OPAQUE: 'OPAQUE',
  31094. MASK: 'MASK',
  31095. BLEND: 'BLEND'
  31096. };
  31097. var MIME_TYPE_FORMATS = {
  31098. 'image/png': _threeModule.RGBAFormat,
  31099. 'image/jpeg': _threeModule.RGBFormat
  31100. };
  31101. /* UTILITY FUNCTIONS */
  31102. function resolveURL(url, path) {
  31103. // Invalid URL
  31104. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  31105. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  31106. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  31107. } // Absolute URL http://,https://,//
  31108. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  31109. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  31110. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  31111. return path + url;
  31112. }
  31113. var defaultMaterial;
  31114. /**
  31115. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  31116. */
  31117. function createDefaultMaterial() {
  31118. defaultMaterial = defaultMaterial || new _threeModule.MeshStandardMaterial({
  31119. color: 0xFFFFFF,
  31120. emissive: 0x000000,
  31121. metalness: 1,
  31122. roughness: 1,
  31123. transparent: false,
  31124. depthTest: true,
  31125. side: _threeModule.FrontSide
  31126. });
  31127. return defaultMaterial;
  31128. }
  31129. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  31130. // Add unknown glTF extensions to an object's userData.
  31131. for (var name in objectDef.extensions) {
  31132. if (knownExtensions[name] === undefined) {
  31133. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  31134. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  31135. }
  31136. }
  31137. }
  31138. /**
  31139. * @param {Object3D|Material|BufferGeometry} object
  31140. * @param {GLTF.definition} gltfDef
  31141. */
  31142. function assignExtrasToUserData(object, gltfDef) {
  31143. if (gltfDef.extras !== undefined) {
  31144. if (typeof gltfDef.extras === 'object') {
  31145. Object.assign(object.userData, gltfDef.extras);
  31146. } else {
  31147. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  31148. }
  31149. }
  31150. }
  31151. /**
  31152. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  31153. *
  31154. * @param {BufferGeometry} geometry
  31155. * @param {Array<GLTF.Target>} targets
  31156. * @param {GLTFParser} parser
  31157. * @return {Promise<BufferGeometry>}
  31158. */
  31159. function addMorphTargets(geometry, targets, parser) {
  31160. var hasMorphPosition = false;
  31161. var hasMorphNormal = false;
  31162. for (var i = 0, il = targets.length; i < il; i++) {
  31163. var target = targets[i];
  31164. if (target.POSITION !== undefined) hasMorphPosition = true;
  31165. if (target.NORMAL !== undefined) hasMorphNormal = true;
  31166. if (hasMorphPosition && hasMorphNormal) break;
  31167. }
  31168. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  31169. var pendingPositionAccessors = [];
  31170. var pendingNormalAccessors = [];
  31171. for (var i = 0, il = targets.length; i < il; i++) {
  31172. var target = targets[i];
  31173. if (hasMorphPosition) {
  31174. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  31175. pendingPositionAccessors.push(pendingAccessor);
  31176. }
  31177. if (hasMorphNormal) {
  31178. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  31179. pendingNormalAccessors.push(pendingAccessor);
  31180. }
  31181. }
  31182. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  31183. var morphPositions = accessors[0];
  31184. var morphNormals = accessors[1]; // Clone morph target accessors before modifying them.
  31185. for (var i = 0, il = morphPositions.length; i < il; i++) {
  31186. if (geometry.attributes.position === morphPositions[i]) continue;
  31187. morphPositions[i] = cloneBufferAttribute(morphPositions[i]);
  31188. }
  31189. for (var i = 0, il = morphNormals.length; i < il; i++) {
  31190. if (geometry.attributes.normal === morphNormals[i]) continue;
  31191. morphNormals[i] = cloneBufferAttribute(morphNormals[i]);
  31192. }
  31193. for (var i = 0, il = targets.length; i < il; i++) {
  31194. var target = targets[i];
  31195. var attributeName = 'morphTarget' + i;
  31196. if (hasMorphPosition) {
  31197. // Three.js morph position is absolute value. The formula is
  31198. // basePosition
  31199. // + weight0 * ( morphPosition0 - basePosition )
  31200. // + weight1 * ( morphPosition1 - basePosition )
  31201. // ...
  31202. // while the glTF one is relative
  31203. // basePosition
  31204. // + weight0 * glTFmorphPosition0
  31205. // + weight1 * glTFmorphPosition1
  31206. // ...
  31207. // then we need to convert from relative to absolute here.
  31208. if (target.POSITION !== undefined) {
  31209. var positionAttribute = morphPositions[i];
  31210. positionAttribute.name = attributeName;
  31211. var position = geometry.attributes.position;
  31212. for (var j = 0, jl = positionAttribute.count; j < jl; j++) {
  31213. positionAttribute.setXYZ(j, positionAttribute.getX(j) + position.getX(j), positionAttribute.getY(j) + position.getY(j), positionAttribute.getZ(j) + position.getZ(j));
  31214. }
  31215. }
  31216. }
  31217. if (hasMorphNormal) {
  31218. // see target.POSITION's comment
  31219. if (target.NORMAL !== undefined) {
  31220. var normalAttribute = morphNormals[i];
  31221. normalAttribute.name = attributeName;
  31222. var normal = geometry.attributes.normal;
  31223. for (var j = 0, jl = normalAttribute.count; j < jl; j++) {
  31224. normalAttribute.setXYZ(j, normalAttribute.getX(j) + normal.getX(j), normalAttribute.getY(j) + normal.getY(j), normalAttribute.getZ(j) + normal.getZ(j));
  31225. }
  31226. }
  31227. }
  31228. }
  31229. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  31230. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  31231. return geometry;
  31232. });
  31233. }
  31234. /**
  31235. * @param {Mesh} mesh
  31236. * @param {GLTF.Mesh} meshDef
  31237. */
  31238. function updateMorphTargets(mesh, meshDef) {
  31239. mesh.updateMorphTargets();
  31240. if (meshDef.weights !== undefined) {
  31241. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  31242. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  31243. }
  31244. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  31245. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  31246. var targetNames = meshDef.extras.targetNames;
  31247. if (mesh.morphTargetInfluences.length === targetNames.length) {
  31248. mesh.morphTargetDictionary = {};
  31249. for (var i = 0, il = targetNames.length; i < il; i++) {
  31250. mesh.morphTargetDictionary[targetNames[i]] = i;
  31251. }
  31252. } else {
  31253. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  31254. }
  31255. }
  31256. }
  31257. function createPrimitiveKey(primitiveDef) {
  31258. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  31259. var geometryKey;
  31260. if (dracoExtension) {
  31261. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  31262. } else {
  31263. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  31264. }
  31265. return geometryKey;
  31266. }
  31267. function createAttributesKey(attributes) {
  31268. var attributesKey = '';
  31269. var keys = Object.keys(attributes).sort();
  31270. for (var i = 0, il = keys.length; i < il; i++) {
  31271. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  31272. }
  31273. return attributesKey;
  31274. }
  31275. function cloneBufferAttribute(attribute) {
  31276. if (attribute.isInterleavedBufferAttribute) {
  31277. var count = attribute.count;
  31278. var itemSize = attribute.itemSize;
  31279. var array = attribute.array.slice(0, count * itemSize);
  31280. for (var i = 0, j = 0; i < count; ++i) {
  31281. array[j++] = attribute.getX(i);
  31282. if (itemSize >= 2) array[j++] = attribute.getY(i);
  31283. if (itemSize >= 3) array[j++] = attribute.getZ(i);
  31284. if (itemSize >= 4) array[j++] = attribute.getW(i);
  31285. }
  31286. return new _threeModule.BufferAttribute(array, itemSize, attribute.normalized);
  31287. }
  31288. return attribute.clone();
  31289. }
  31290. /* GLTF PARSER */
  31291. function GLTFParser(json, extensions, options) {
  31292. this.json = json || {};
  31293. this.extensions = extensions || {};
  31294. this.options = options || {}; // loader object cache
  31295. this.cache = new GLTFRegistry(); // BufferGeometry caching
  31296. this.primitiveCache = {};
  31297. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  31298. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  31299. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  31300. this.fileLoader.setResponseType('arraybuffer');
  31301. if (this.options.crossOrigin === 'use-credentials') {
  31302. this.fileLoader.setWithCredentials(true);
  31303. }
  31304. }
  31305. GLTFParser.prototype.parse = function (onLoad, onError) {
  31306. var parser = this;
  31307. var json = this.json;
  31308. var extensions = this.extensions; // Clear the loader cache
  31309. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  31310. this.markDefs();
  31311. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  31312. var result = {
  31313. scene: dependencies[0][json.scene || 0],
  31314. scenes: dependencies[0],
  31315. animations: dependencies[1],
  31316. cameras: dependencies[2],
  31317. asset: json.asset,
  31318. parser: parser,
  31319. userData: {}
  31320. };
  31321. addUnknownExtensionsToUserData(extensions, result, json);
  31322. assignExtrasToUserData(result, json);
  31323. onLoad(result);
  31324. }).catch(onError);
  31325. };
  31326. /**
  31327. * Marks the special nodes/meshes in json for efficient parse.
  31328. */
  31329. GLTFParser.prototype.markDefs = function () {
  31330. var nodeDefs = this.json.nodes || [];
  31331. var skinDefs = this.json.skins || [];
  31332. var meshDefs = this.json.meshes || [];
  31333. var meshReferences = {};
  31334. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  31335. // Object3D. Use the skins' joint references to mark bones.
  31336. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  31337. var joints = skinDefs[skinIndex].joints;
  31338. for (var i = 0, il = joints.length; i < il; i++) {
  31339. nodeDefs[joints[i]].isBone = true;
  31340. }
  31341. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  31342. // avoid having more than one Mesh with the same name, count
  31343. // references and rename instances below.
  31344. //
  31345. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  31346. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  31347. var nodeDef = nodeDefs[nodeIndex];
  31348. if (nodeDef.mesh !== undefined) {
  31349. if (meshReferences[nodeDef.mesh] === undefined) {
  31350. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  31351. }
  31352. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  31353. // a SkinnedMesh or Mesh. Use the node's mesh reference
  31354. // to mark SkinnedMesh if node has skin.
  31355. if (nodeDef.skin !== undefined) {
  31356. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  31357. }
  31358. }
  31359. }
  31360. this.json.meshReferences = meshReferences;
  31361. this.json.meshUses = meshUses;
  31362. };
  31363. /**
  31364. * Requests the specified dependency asynchronously, with caching.
  31365. * @param {string} type
  31366. * @param {number} index
  31367. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  31368. */
  31369. GLTFParser.prototype.getDependency = function (type, index) {
  31370. var cacheKey = type + ':' + index;
  31371. var dependency = this.cache.get(cacheKey);
  31372. if (!dependency) {
  31373. switch (type) {
  31374. case 'scene':
  31375. dependency = this.loadScene(index);
  31376. break;
  31377. case 'node':
  31378. dependency = this.loadNode(index);
  31379. break;
  31380. case 'mesh':
  31381. dependency = this.loadMesh(index);
  31382. break;
  31383. case 'accessor':
  31384. dependency = this.loadAccessor(index);
  31385. break;
  31386. case 'bufferView':
  31387. dependency = this.loadBufferView(index);
  31388. break;
  31389. case 'buffer':
  31390. dependency = this.loadBuffer(index);
  31391. break;
  31392. case 'material':
  31393. dependency = this.loadMaterial(index);
  31394. break;
  31395. case 'texture':
  31396. dependency = this.loadTexture(index);
  31397. break;
  31398. case 'skin':
  31399. dependency = this.loadSkin(index);
  31400. break;
  31401. case 'animation':
  31402. dependency = this.loadAnimation(index);
  31403. break;
  31404. case 'camera':
  31405. dependency = this.loadCamera(index);
  31406. break;
  31407. case 'light':
  31408. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  31409. break;
  31410. default:
  31411. throw new Error('Unknown type: ' + type);
  31412. }
  31413. this.cache.add(cacheKey, dependency);
  31414. }
  31415. return dependency;
  31416. };
  31417. /**
  31418. * Requests all dependencies of the specified type asynchronously, with caching.
  31419. * @param {string} type
  31420. * @return {Promise<Array<Object>>}
  31421. */
  31422. GLTFParser.prototype.getDependencies = function (type) {
  31423. var dependencies = this.cache.get(type);
  31424. if (!dependencies) {
  31425. var parser = this;
  31426. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  31427. dependencies = Promise.all(defs.map(function (def, index) {
  31428. return parser.getDependency(type, index);
  31429. }));
  31430. this.cache.add(type, dependencies);
  31431. }
  31432. return dependencies;
  31433. };
  31434. /**
  31435. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31436. * @param {number} bufferIndex
  31437. * @return {Promise<ArrayBuffer>}
  31438. */
  31439. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  31440. var bufferDef = this.json.buffers[bufferIndex];
  31441. var loader = this.fileLoader;
  31442. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  31443. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  31444. } // If present, GLB container is required to be the first buffer.
  31445. if (bufferDef.uri === undefined && bufferIndex === 0) {
  31446. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  31447. }
  31448. var options = this.options;
  31449. return new Promise(function (resolve, reject) {
  31450. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  31451. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  31452. });
  31453. });
  31454. };
  31455. /**
  31456. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31457. * @param {number} bufferViewIndex
  31458. * @return {Promise<ArrayBuffer>}
  31459. */
  31460. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  31461. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  31462. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  31463. var byteLength = bufferViewDef.byteLength || 0;
  31464. var byteOffset = bufferViewDef.byteOffset || 0;
  31465. return buffer.slice(byteOffset, byteOffset + byteLength);
  31466. });
  31467. };
  31468. /**
  31469. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  31470. * @param {number} accessorIndex
  31471. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  31472. */
  31473. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  31474. var parser = this;
  31475. var json = this.json;
  31476. var accessorDef = this.json.accessors[accessorIndex];
  31477. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  31478. // Ignore empty accessors, which may be used to declare runtime
  31479. // information about attributes coming from another source (e.g. Draco
  31480. // compression extension).
  31481. return Promise.resolve(null);
  31482. }
  31483. var pendingBufferViews = [];
  31484. if (accessorDef.bufferView !== undefined) {
  31485. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  31486. } else {
  31487. pendingBufferViews.push(null);
  31488. }
  31489. if (accessorDef.sparse !== undefined) {
  31490. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  31491. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  31492. }
  31493. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  31494. var bufferView = bufferViews[0];
  31495. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  31496. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  31497. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  31498. var itemBytes = elementBytes * itemSize;
  31499. var byteOffset = accessorDef.byteOffset || 0;
  31500. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  31501. var normalized = accessorDef.normalized === true;
  31502. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  31503. if (byteStride && byteStride !== itemBytes) {
  31504. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  31505. // This makes sure that IBA.count reflects accessor.count properly
  31506. var ibSlice = Math.floor(byteOffset / byteStride);
  31507. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  31508. var ib = parser.cache.get(ibCacheKey);
  31509. if (!ib) {
  31510. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  31511. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  31512. parser.cache.add(ibCacheKey, ib);
  31513. }
  31514. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  31515. } else {
  31516. if (bufferView === null) {
  31517. array = new TypedArray(accessorDef.count * itemSize);
  31518. } else {
  31519. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  31520. }
  31521. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  31522. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  31523. if (accessorDef.sparse !== undefined) {
  31524. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  31525. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  31526. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  31527. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  31528. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  31529. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  31530. if (bufferView !== null) {
  31531. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  31532. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  31533. }
  31534. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  31535. var index = sparseIndices[i];
  31536. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  31537. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  31538. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  31539. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  31540. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  31541. }
  31542. }
  31543. return bufferAttribute;
  31544. });
  31545. };
  31546. /**
  31547. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  31548. * @param {number} textureIndex
  31549. * @return {Promise<THREE.Texture>}
  31550. */
  31551. GLTFParser.prototype.loadTexture = function (textureIndex) {
  31552. var parser = this;
  31553. var json = this.json;
  31554. var options = this.options;
  31555. var textureLoader = this.textureLoader;
  31556. var URL = window.URL || window.webkitURL;
  31557. var textureDef = json.textures[textureIndex];
  31558. var textureExtensions = textureDef.extensions || {};
  31559. var source;
  31560. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  31561. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  31562. } else {
  31563. source = json.images[textureDef.source];
  31564. }
  31565. var sourceURI = source.uri;
  31566. var isObjectURL = false;
  31567. if (source.bufferView !== undefined) {
  31568. // Load binary image data from bufferView, if provided.
  31569. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  31570. isObjectURL = true;
  31571. var blob = new Blob([bufferView], {
  31572. type: source.mimeType
  31573. });
  31574. sourceURI = URL.createObjectURL(blob);
  31575. return sourceURI;
  31576. });
  31577. }
  31578. return Promise.resolve(sourceURI).then(function (sourceURI) {
  31579. // Load Texture resource.
  31580. var loader = options.manager.getHandler(sourceURI);
  31581. if (!loader) {
  31582. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  31583. }
  31584. return new Promise(function (resolve, reject) {
  31585. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  31586. });
  31587. }).then(function (texture) {
  31588. // Clean up resources and configure Texture.
  31589. if (isObjectURL === true) {
  31590. URL.revokeObjectURL(sourceURI);
  31591. }
  31592. texture.flipY = false;
  31593. if (textureDef.name !== undefined) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  31594. if (source.mimeType in MIME_TYPE_FORMATS) {
  31595. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  31596. }
  31597. var samplers = json.samplers || {};
  31598. var sampler = samplers[textureDef.sampler] || {};
  31599. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  31600. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  31601. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  31602. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  31603. return texture;
  31604. });
  31605. };
  31606. /**
  31607. * Asynchronously assigns a texture to the given material parameters.
  31608. * @param {Object} materialParams
  31609. * @param {string} mapName
  31610. * @param {Object} mapDef
  31611. * @return {Promise}
  31612. */
  31613. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  31614. var parser = this;
  31615. return this.getDependency('texture', mapDef.index).then(function (texture) {
  31616. if (!texture.isCompressedTexture) {
  31617. switch (mapName) {
  31618. case 'aoMap':
  31619. case 'emissiveMap':
  31620. case 'metalnessMap':
  31621. case 'normalMap':
  31622. case 'roughnessMap':
  31623. texture.format = _threeModule.RGBFormat;
  31624. break;
  31625. }
  31626. }
  31627. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  31628. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  31629. if (transform) {
  31630. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  31631. }
  31632. }
  31633. materialParams[mapName] = texture;
  31634. });
  31635. };
  31636. /**
  31637. * Assigns final material to a Mesh, Line, or Points instance. The instance
  31638. * already has a material (generated from the glTF material options alone)
  31639. * but reuse of the same glTF material may require multiple threejs materials
  31640. * to accomodate different primitive types, defines, etc. New materials will
  31641. * be created if necessary, and reused from a cache.
  31642. * @param {Object3D} mesh Mesh, Line, or Points instance.
  31643. */
  31644. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  31645. var geometry = mesh.geometry;
  31646. var material = mesh.material;
  31647. var extensions = this.extensions;
  31648. var useVertexTangents = geometry.attributes.tangent !== undefined;
  31649. var useVertexColors = geometry.attributes.color !== undefined;
  31650. var useFlatShading = geometry.attributes.normal === undefined;
  31651. var useSkinning = mesh.isSkinnedMesh === true;
  31652. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  31653. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  31654. if (mesh.isPoints) {
  31655. var cacheKey = 'PointsMaterial:' + material.uuid;
  31656. var pointsMaterial = this.cache.get(cacheKey);
  31657. if (!pointsMaterial) {
  31658. pointsMaterial = new _threeModule.PointsMaterial();
  31659. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  31660. pointsMaterial.color.copy(material.color);
  31661. pointsMaterial.map = material.map;
  31662. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  31663. this.cache.add(cacheKey, pointsMaterial);
  31664. }
  31665. material = pointsMaterial;
  31666. } else if (mesh.isLine) {
  31667. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  31668. var lineMaterial = this.cache.get(cacheKey);
  31669. if (!lineMaterial) {
  31670. lineMaterial = new _threeModule.LineBasicMaterial();
  31671. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  31672. lineMaterial.color.copy(material.color);
  31673. this.cache.add(cacheKey, lineMaterial);
  31674. }
  31675. material = lineMaterial;
  31676. } // Clone the material if it will be modified
  31677. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  31678. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  31679. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  31680. if (useSkinning) cacheKey += 'skinning:';
  31681. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  31682. if (useVertexColors) cacheKey += 'vertex-colors:';
  31683. if (useFlatShading) cacheKey += 'flat-shading:';
  31684. if (useMorphTargets) cacheKey += 'morph-targets:';
  31685. if (useMorphNormals) cacheKey += 'morph-normals:';
  31686. var cachedMaterial = this.cache.get(cacheKey);
  31687. if (!cachedMaterial) {
  31688. cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].cloneMaterial(material) : material.clone();
  31689. if (useSkinning) cachedMaterial.skinning = true;
  31690. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  31691. if (useVertexColors) cachedMaterial.vertexColors = _threeModule.VertexColors;
  31692. if (useFlatShading) cachedMaterial.flatShading = true;
  31693. if (useMorphTargets) cachedMaterial.morphTargets = true;
  31694. if (useMorphNormals) cachedMaterial.morphNormals = true;
  31695. this.cache.add(cacheKey, cachedMaterial);
  31696. }
  31697. material = cachedMaterial;
  31698. } // workarounds for mesh and geometry
  31699. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  31700. console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.');
  31701. geometry.addAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  31702. }
  31703. if (material.isGLTFSpecularGlossinessMaterial) {
  31704. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  31705. mesh.onBeforeRender = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].refreshUniforms;
  31706. }
  31707. mesh.material = material;
  31708. };
  31709. /**
  31710. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  31711. * @param {number} materialIndex
  31712. * @return {Promise<Material>}
  31713. */
  31714. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  31715. var parser = this;
  31716. var json = this.json;
  31717. var extensions = this.extensions;
  31718. var materialDef = json.materials[materialIndex];
  31719. var materialType;
  31720. var materialParams = {};
  31721. var materialExtensions = materialDef.extensions || {};
  31722. var pending = [];
  31723. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  31724. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  31725. materialType = sgExtension.getMaterialType();
  31726. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  31727. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  31728. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  31729. materialType = kmuExtension.getMaterialType();
  31730. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  31731. } else {
  31732. // Specification:
  31733. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  31734. materialType = _threeModule.MeshStandardMaterial;
  31735. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  31736. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31737. materialParams.opacity = 1.0;
  31738. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31739. var array = metallicRoughness.baseColorFactor;
  31740. materialParams.color.fromArray(array);
  31741. materialParams.opacity = array[3];
  31742. }
  31743. if (metallicRoughness.baseColorTexture !== undefined) {
  31744. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31745. }
  31746. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  31747. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  31748. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  31749. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  31750. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  31751. }
  31752. }
  31753. if (materialDef.doubleSided === true) {
  31754. materialParams.side = _threeModule.DoubleSide;
  31755. }
  31756. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  31757. if (alphaMode === ALPHA_MODES.BLEND) {
  31758. materialParams.transparent = true;
  31759. } else {
  31760. materialParams.transparent = false;
  31761. if (alphaMode === ALPHA_MODES.MASK) {
  31762. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  31763. }
  31764. }
  31765. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31766. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  31767. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  31768. if (materialDef.normalTexture.scale !== undefined) {
  31769. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  31770. }
  31771. }
  31772. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31773. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  31774. if (materialDef.occlusionTexture.strength !== undefined) {
  31775. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  31776. }
  31777. }
  31778. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31779. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  31780. }
  31781. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31782. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  31783. }
  31784. return Promise.all(pending).then(function () {
  31785. var material;
  31786. if (materialType === _threeModule.ShaderMaterial) {
  31787. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  31788. } else {
  31789. material = new materialType(materialParams);
  31790. }
  31791. if (materialDef.name !== undefined) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  31792. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  31793. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  31794. if (material.specularMap) material.specularMap.encoding = _threeModule.sRGBEncoding;
  31795. assignExtrasToUserData(material, materialDef);
  31796. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  31797. return material;
  31798. });
  31799. };
  31800. /**
  31801. * @param {BufferGeometry} geometry
  31802. * @param {GLTF.Primitive} primitiveDef
  31803. * @param {GLTFParser} parser
  31804. * @return {Promise<BufferGeometry>}
  31805. */
  31806. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  31807. var attributes = primitiveDef.attributes;
  31808. var pending = [];
  31809. function assignAttributeAccessor(accessorIndex, attributeName) {
  31810. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  31811. geometry.addAttribute(attributeName, accessor);
  31812. });
  31813. }
  31814. for (var gltfAttributeName in attributes) {
  31815. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  31816. if (threeAttributeName in geometry.attributes) continue;
  31817. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  31818. }
  31819. if (primitiveDef.indices !== undefined && !geometry.index) {
  31820. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  31821. geometry.setIndex(accessor);
  31822. });
  31823. pending.push(accessor);
  31824. }
  31825. assignExtrasToUserData(geometry, primitiveDef);
  31826. return Promise.all(pending).then(function () {
  31827. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  31828. });
  31829. }
  31830. /**
  31831. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  31832. *
  31833. * Creates BufferGeometries from primitives.
  31834. *
  31835. * @param {Array<GLTF.Primitive>} primitives
  31836. * @return {Promise<Array<BufferGeometry>>}
  31837. */
  31838. GLTFParser.prototype.loadGeometries = function (primitives) {
  31839. var parser = this;
  31840. var extensions = this.extensions;
  31841. var cache = this.primitiveCache;
  31842. function createDracoPrimitive(primitive) {
  31843. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  31844. return addPrimitiveAttributes(geometry, primitive, parser);
  31845. });
  31846. }
  31847. var pending = [];
  31848. for (var i = 0, il = primitives.length; i < il; i++) {
  31849. var primitive = primitives[i];
  31850. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  31851. var cached = cache[cacheKey];
  31852. if (cached) {
  31853. // Use the cached geometry if it exists
  31854. pending.push(cached.promise);
  31855. } else {
  31856. var geometryPromise;
  31857. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  31858. // Use DRACO geometry if available
  31859. geometryPromise = createDracoPrimitive(primitive);
  31860. } else {
  31861. // Otherwise create a new geometry
  31862. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  31863. } // Cache this geometry
  31864. cache[cacheKey] = {
  31865. primitive: primitive,
  31866. promise: geometryPromise
  31867. };
  31868. pending.push(geometryPromise);
  31869. }
  31870. }
  31871. return Promise.all(pending);
  31872. };
  31873. /**
  31874. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  31875. * @param {number} meshIndex
  31876. * @return {Promise<Group|Mesh|SkinnedMesh>}
  31877. */
  31878. GLTFParser.prototype.loadMesh = function (meshIndex) {
  31879. var parser = this;
  31880. var json = this.json;
  31881. var meshDef = json.meshes[meshIndex];
  31882. var primitives = meshDef.primitives;
  31883. var pending = [];
  31884. for (var i = 0, il = primitives.length; i < il; i++) {
  31885. var material = primitives[i].material === undefined ? createDefaultMaterial() : this.getDependency('material', primitives[i].material);
  31886. pending.push(material);
  31887. }
  31888. return Promise.all(pending).then(function (originalMaterials) {
  31889. return parser.loadGeometries(primitives).then(function (geometries) {
  31890. var meshes = [];
  31891. for (var i = 0, il = geometries.length; i < il; i++) {
  31892. var geometry = geometries[i];
  31893. var primitive = primitives[i]; // 1. create Mesh
  31894. var mesh;
  31895. var material = originalMaterials[i];
  31896. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  31897. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  31898. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  31899. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  31900. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  31901. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  31902. mesh.normalizeSkinWeights();
  31903. }
  31904. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  31905. mesh.drawMode = _threeModule.TriangleStripDrawMode;
  31906. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  31907. mesh.drawMode = _threeModule.TriangleFanDrawMode;
  31908. }
  31909. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  31910. mesh = new _threeModule.LineSegments(geometry, material);
  31911. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  31912. mesh = new _threeModule.Line(geometry, material);
  31913. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  31914. mesh = new _threeModule.LineLoop(geometry, material);
  31915. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  31916. mesh = new _threeModule.Points(geometry, material);
  31917. } else {
  31918. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  31919. }
  31920. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  31921. updateMorphTargets(mesh, meshDef);
  31922. }
  31923. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  31924. if (geometries.length > 1) mesh.name += '_' + i;
  31925. assignExtrasToUserData(mesh, meshDef);
  31926. parser.assignFinalMaterial(mesh);
  31927. meshes.push(mesh);
  31928. }
  31929. if (meshes.length === 1) {
  31930. return meshes[0];
  31931. }
  31932. var group = new _threeModule.Group();
  31933. for (var i = 0, il = meshes.length; i < il; i++) {
  31934. group.add(meshes[i]);
  31935. }
  31936. return group;
  31937. });
  31938. });
  31939. };
  31940. /**
  31941. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  31942. * @param {number} cameraIndex
  31943. * @return {Promise<THREE.Camera>}
  31944. */
  31945. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  31946. var camera;
  31947. var cameraDef = this.json.cameras[cameraIndex];
  31948. var params = cameraDef[cameraDef.type];
  31949. if (!params) {
  31950. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  31951. return;
  31952. }
  31953. if (cameraDef.type === 'perspective') {
  31954. camera = new _threeModule.PerspectiveCamera(_threeModule.Math.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  31955. } else if (cameraDef.type === 'orthographic') {
  31956. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  31957. }
  31958. if (cameraDef.name !== undefined) camera.name = cameraDef.name;
  31959. assignExtrasToUserData(camera, cameraDef);
  31960. return Promise.resolve(camera);
  31961. };
  31962. /**
  31963. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  31964. * @param {number} skinIndex
  31965. * @return {Promise<Object>}
  31966. */
  31967. GLTFParser.prototype.loadSkin = function (skinIndex) {
  31968. var skinDef = this.json.skins[skinIndex];
  31969. var skinEntry = {
  31970. joints: skinDef.joints
  31971. };
  31972. if (skinDef.inverseBindMatrices === undefined) {
  31973. return Promise.resolve(skinEntry);
  31974. }
  31975. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  31976. skinEntry.inverseBindMatrices = accessor;
  31977. return skinEntry;
  31978. });
  31979. };
  31980. /**
  31981. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  31982. * @param {number} animationIndex
  31983. * @return {Promise<AnimationClip>}
  31984. */
  31985. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  31986. var json = this.json;
  31987. var animationDef = json.animations[animationIndex];
  31988. var pendingNodes = [];
  31989. var pendingInputAccessors = [];
  31990. var pendingOutputAccessors = [];
  31991. var pendingSamplers = [];
  31992. var pendingTargets = [];
  31993. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  31994. var channel = animationDef.channels[i];
  31995. var sampler = animationDef.samplers[channel.sampler];
  31996. var target = channel.target;
  31997. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  31998. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  31999. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  32000. pendingNodes.push(this.getDependency('node', name));
  32001. pendingInputAccessors.push(this.getDependency('accessor', input));
  32002. pendingOutputAccessors.push(this.getDependency('accessor', output));
  32003. pendingSamplers.push(sampler);
  32004. pendingTargets.push(target);
  32005. }
  32006. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  32007. var nodes = dependencies[0];
  32008. var inputAccessors = dependencies[1];
  32009. var outputAccessors = dependencies[2];
  32010. var samplers = dependencies[3];
  32011. var targets = dependencies[4];
  32012. var tracks = [];
  32013. for (var i = 0, il = nodes.length; i < il; i++) {
  32014. var node = nodes[i];
  32015. var inputAccessor = inputAccessors[i];
  32016. var outputAccessor = outputAccessors[i];
  32017. var sampler = samplers[i];
  32018. var target = targets[i];
  32019. if (node === undefined) continue;
  32020. node.updateMatrix();
  32021. node.matrixAutoUpdate = true;
  32022. var TypedKeyframeTrack;
  32023. switch (PATH_PROPERTIES[target.path]) {
  32024. case PATH_PROPERTIES.weights:
  32025. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  32026. break;
  32027. case PATH_PROPERTIES.rotation:
  32028. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  32029. break;
  32030. case PATH_PROPERTIES.position:
  32031. case PATH_PROPERTIES.scale:
  32032. default:
  32033. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  32034. break;
  32035. }
  32036. var targetName = node.name ? node.name : node.uuid;
  32037. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  32038. var targetNames = [];
  32039. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  32040. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  32041. node.traverse(function (object) {
  32042. if (object.isMesh === true && object.morphTargetInfluences) {
  32043. targetNames.push(object.name ? object.name : object.uuid);
  32044. }
  32045. });
  32046. } else {
  32047. targetNames.push(targetName);
  32048. }
  32049. var outputArray = outputAccessor.array;
  32050. if (outputAccessor.normalized) {
  32051. var scale;
  32052. if (outputArray.constructor === Int8Array) {
  32053. scale = 1 / 127;
  32054. } else if (outputArray.constructor === Uint8Array) {
  32055. scale = 1 / 255;
  32056. } else if (outputArray.constructor == Int16Array) {
  32057. scale = 1 / 32767;
  32058. } else if (outputArray.constructor === Uint16Array) {
  32059. scale = 1 / 65535;
  32060. } else {
  32061. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  32062. }
  32063. var scaled = new Float32Array(outputArray.length);
  32064. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  32065. scaled[j] = outputArray[j] * scale;
  32066. }
  32067. outputArray = scaled;
  32068. }
  32069. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  32070. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  32071. if (sampler.interpolation === 'CUBICSPLINE') {
  32072. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  32073. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  32074. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  32075. // must be divided by three to get the interpolant's sampleSize argument.
  32076. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  32077. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  32078. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  32079. }
  32080. tracks.push(track);
  32081. }
  32082. }
  32083. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  32084. return new _threeModule.AnimationClip(name, undefined, tracks);
  32085. });
  32086. };
  32087. /**
  32088. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  32089. * @param {number} nodeIndex
  32090. * @return {Promise<Object3D>}
  32091. */
  32092. GLTFParser.prototype.loadNode = function (nodeIndex) {
  32093. var json = this.json;
  32094. var extensions = this.extensions;
  32095. var parser = this;
  32096. var meshReferences = json.meshReferences;
  32097. var meshUses = json.meshUses;
  32098. var nodeDef = json.nodes[nodeIndex];
  32099. return function () {
  32100. var pending = [];
  32101. if (nodeDef.mesh !== undefined) {
  32102. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  32103. var node;
  32104. if (meshReferences[nodeDef.mesh] > 1) {
  32105. var instanceNum = meshUses[nodeDef.mesh]++;
  32106. node = mesh.clone();
  32107. node.name += '_instance_' + instanceNum; // onBeforeRender copy for Specular-Glossiness
  32108. node.onBeforeRender = mesh.onBeforeRender;
  32109. for (var i = 0, il = node.children.length; i < il; i++) {
  32110. node.children[i].name += '_instance_' + instanceNum;
  32111. node.children[i].onBeforeRender = mesh.children[i].onBeforeRender;
  32112. }
  32113. } else {
  32114. node = mesh;
  32115. } // if weights are provided on the node, override weights on the mesh.
  32116. if (nodeDef.weights !== undefined) {
  32117. node.traverse(function (o) {
  32118. if (!o.isMesh) return;
  32119. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  32120. o.morphTargetInfluences[i] = nodeDef.weights[i];
  32121. }
  32122. });
  32123. }
  32124. return node;
  32125. }));
  32126. }
  32127. if (nodeDef.camera !== undefined) {
  32128. pending.push(parser.getDependency('camera', nodeDef.camera));
  32129. }
  32130. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  32131. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  32132. }
  32133. return Promise.all(pending);
  32134. }().then(function (objects) {
  32135. var node; // .isBone isn't in glTF spec. See .markDefs
  32136. if (nodeDef.isBone === true) {
  32137. node = new _threeModule.Bone();
  32138. } else if (objects.length > 1) {
  32139. node = new _threeModule.Group();
  32140. } else if (objects.length === 1) {
  32141. node = objects[0];
  32142. } else {
  32143. node = new _threeModule.Object3D();
  32144. }
  32145. if (node !== objects[0]) {
  32146. for (var i = 0, il = objects.length; i < il; i++) {
  32147. node.add(objects[i]);
  32148. }
  32149. }
  32150. if (nodeDef.name !== undefined) {
  32151. node.userData.name = nodeDef.name;
  32152. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  32153. }
  32154. assignExtrasToUserData(node, nodeDef);
  32155. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  32156. if (nodeDef.matrix !== undefined) {
  32157. var matrix = new _threeModule.Matrix4();
  32158. matrix.fromArray(nodeDef.matrix);
  32159. node.applyMatrix(matrix);
  32160. } else {
  32161. if (nodeDef.translation !== undefined) {
  32162. node.position.fromArray(nodeDef.translation);
  32163. }
  32164. if (nodeDef.rotation !== undefined) {
  32165. node.quaternion.fromArray(nodeDef.rotation);
  32166. }
  32167. if (nodeDef.scale !== undefined) {
  32168. node.scale.fromArray(nodeDef.scale);
  32169. }
  32170. }
  32171. return node;
  32172. });
  32173. };
  32174. /**
  32175. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  32176. * @param {number} sceneIndex
  32177. * @return {Promise<Scene>}
  32178. */
  32179. GLTFParser.prototype.loadScene = function () {
  32180. // scene node hierachy builder
  32181. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  32182. var nodeDef = json.nodes[nodeId];
  32183. return parser.getDependency('node', nodeId).then(function (node) {
  32184. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  32185. var skinEntry;
  32186. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  32187. skinEntry = skin;
  32188. var pendingJoints = [];
  32189. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  32190. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  32191. }
  32192. return Promise.all(pendingJoints);
  32193. }).then(function (jointNodes) {
  32194. node.traverse(function (mesh) {
  32195. if (!mesh.isMesh) return;
  32196. var bones = [];
  32197. var boneInverses = [];
  32198. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  32199. var jointNode = jointNodes[j];
  32200. if (jointNode) {
  32201. bones.push(jointNode);
  32202. var mat = new _threeModule.Matrix4();
  32203. if (skinEntry.inverseBindMatrices !== undefined) {
  32204. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  32205. }
  32206. boneInverses.push(mat);
  32207. } else {
  32208. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  32209. }
  32210. }
  32211. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  32212. });
  32213. return node;
  32214. });
  32215. }).then(function (node) {
  32216. // build node hierachy
  32217. parentObject.add(node);
  32218. var pending = [];
  32219. if (nodeDef.children) {
  32220. var children = nodeDef.children;
  32221. for (var i = 0, il = children.length; i < il; i++) {
  32222. var child = children[i];
  32223. pending.push(buildNodeHierachy(child, node, json, parser));
  32224. }
  32225. }
  32226. return Promise.all(pending);
  32227. });
  32228. }
  32229. return function loadScene(sceneIndex) {
  32230. var json = this.json;
  32231. var extensions = this.extensions;
  32232. var sceneDef = this.json.scenes[sceneIndex];
  32233. var parser = this;
  32234. var scene = new _threeModule.Scene();
  32235. if (sceneDef.name !== undefined) scene.name = sceneDef.name;
  32236. assignExtrasToUserData(scene, sceneDef);
  32237. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  32238. var nodeIds = sceneDef.nodes || [];
  32239. var pending = [];
  32240. for (var i = 0, il = nodeIds.length; i < il; i++) {
  32241. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  32242. }
  32243. return Promise.all(pending).then(function () {
  32244. return scene;
  32245. });
  32246. };
  32247. }();
  32248. return GLTFLoader;
  32249. }();
  32250. exports.GLTFLoader = GLTFLoader;
  32251. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/B3DMLoader.js":[function(require,module,exports) {
  32252. "use strict";
  32253. Object.defineProperty(exports, "__esModule", {
  32254. value: true
  32255. });
  32256. exports.B3DMLoader = void 0;
  32257. var _B3DMLoaderBase = require("../base/B3DMLoaderBase.js");
  32258. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  32259. class B3DMLoader extends _B3DMLoaderBase.B3DMLoaderBase {
  32260. parse(buffer) {
  32261. const b3dm = super.parse(buffer);
  32262. const gltfBuffer = b3dm.glbBytes.slice().buffer;
  32263. return new Promise((resolve, reject) => {
  32264. new _GLTFLoader.GLTFLoader().parse(gltfBuffer, null, resolve, reject);
  32265. });
  32266. }
  32267. }
  32268. exports.B3DMLoader = B3DMLoader;
  32269. },{"../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) {
  32270. "use strict";
  32271. Object.defineProperty(exports, "__esModule", {
  32272. value: true
  32273. });
  32274. exports.TilesGroup = void 0;
  32275. var _three = require("three");
  32276. // Specialization of "Group" that only updates world matrices of children if
  32277. // the transform has changed since the last update and ignores the "force"
  32278. // parameter under the assumption that the children tiles will not move.
  32279. const tempMat = new _three.Matrix4();
  32280. class TilesGroup extends _three.Group {
  32281. constructor(tilesRenderer) {
  32282. super();
  32283. this.tilesRenderer = tilesRenderer;
  32284. }
  32285. raycast(raycaster, intersects) {
  32286. this.tilesRenderer.raycast(raycaster, intersects);
  32287. }
  32288. updateMatrixWorld(force) {
  32289. if (this.matrixAutoUpdate) {
  32290. this.updateMatrix();
  32291. }
  32292. if (this.matrixWorldNeedsUpdate || force) {
  32293. if (this.parent === null) {
  32294. tempMat.copy(this.matrix);
  32295. } else {
  32296. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  32297. }
  32298. this.matrixWorldNeedsUpdate = false;
  32299. const elA = tempMat.elements;
  32300. const elB = this.matrixWorld.elements;
  32301. let isDifferent = false;
  32302. for (let i = 0; i < 16; i++) {
  32303. const itemA = elA[i];
  32304. const itemB = elB[i];
  32305. const diff = Math.abs(itemA - itemB);
  32306. if (diff > Number.EPSILON) {
  32307. isDifferent = true;
  32308. break;
  32309. }
  32310. }
  32311. if (isDifferent) {
  32312. this.matrixWorld.copy(tempMat); // update children
  32313. // the children will not have to change unless the parent group has updated
  32314. const children = this.children;
  32315. for (let i = 0, l = children.length; i < l; i++) {
  32316. children[i].updateMatrixWorld();
  32317. }
  32318. }
  32319. }
  32320. }
  32321. }
  32322. exports.TilesGroup = TilesGroup;
  32323. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/raycastTraverse.js":[function(require,module,exports) {
  32324. "use strict";
  32325. Object.defineProperty(exports, "__esModule", {
  32326. value: true
  32327. });
  32328. exports.raycastTraverseFirstHit = raycastTraverseFirstHit;
  32329. exports.raycastTraverse = raycastTraverse;
  32330. var _three = require("three");
  32331. const _sphere = new _three.Sphere();
  32332. const _mat = new _three.Matrix4();
  32333. const _vec = new _three.Vector3();
  32334. const _vec2 = new _three.Vector3();
  32335. const _ray = new _three.Ray();
  32336. const _hitArray = [];
  32337. function distanceSort(a, b) {
  32338. return a.distance - b.distance;
  32339. }
  32340. function intersectTileScene(scene, raycaster, intersects) {
  32341. // Don't intersect the box3 helpers because those are used for debugging
  32342. scene.traverse(c => {
  32343. if (!(c instanceof _three.Box3Helper)) {
  32344. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  32345. }
  32346. });
  32347. } // Returns the closest hit when traversing the tree
  32348. function raycastTraverseFirstHit(root, group, activeSet, raycaster) {
  32349. // If the root is active make sure we've checked it
  32350. if (activeSet.has(root.cached.scene)) {
  32351. intersectTileScene(root.cached.scene, raycaster, _hitArray);
  32352. if (_hitArray.length > 0) {
  32353. if (_hitArray.length > 1) {
  32354. _hitArray.sort(distanceSort);
  32355. }
  32356. _hitArray.length = 0;
  32357. return _hitArray[0];
  32358. } else {
  32359. return null;
  32360. }
  32361. } // TODO: see if we can avoid creating a new array here every time to save on memory
  32362. const array = [];
  32363. const children = root.children;
  32364. for (let i = 0, l = children.length; i < l; i++) {
  32365. const tile = children[i];
  32366. const cached = tile.cached;
  32367. const groupMatrixWorld = group.matrixWorld;
  32368. const transformMat = cached.transform;
  32369. _mat.copy(groupMatrixWorld);
  32370. _mat.multiply(transformMat); // if we don't hit the sphere then early out
  32371. const sphere = cached.sphere;
  32372. if (sphere) {
  32373. _sphere.copy(sphere);
  32374. _sphere.applyMatrix4(_mat);
  32375. if (!raycaster.ray.intersectsSphere(_sphere)) {
  32376. continue;
  32377. }
  32378. } // TODO: check region
  32379. const boundingBox = cached.box;
  32380. const obbMat = cached.boxTransform;
  32381. if (boundingBox) {
  32382. _mat.multiply(obbMat);
  32383. _mat.getInverse(_mat);
  32384. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  32385. if (_ray.intersectBox(boundingBox, _vec)) {
  32386. // account for tile scale
  32387. let invScale;
  32388. _vec2.setFromMatrixScale(_mat);
  32389. invScale = _vec2.x;
  32390. if (Math.abs(Math.max(_vec2.x - _vec2.y, _vec2.x - _vec2.z)) > 1e-6) {
  32391. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when raycasting.');
  32392. } // if we intersect the box save the distance to the tile bounds
  32393. let data = {
  32394. distance: Infinity,
  32395. tile: null
  32396. };
  32397. array.push(data);
  32398. data.distance = _vec.distanceToSquared(_ray.origin) * invScale * invScale;
  32399. data.tile = tile;
  32400. } else {
  32401. continue;
  32402. }
  32403. }
  32404. } // sort them by ascending distance
  32405. array.sort(distanceSort); // traverse until we find the best hit and early out if a tile bounds
  32406. // couldn't possible include a best hit
  32407. let bestDistanceSquared = Infinity;
  32408. let bestHit = null;
  32409. for (let i = 0, l = array.length; i < l; i++) {
  32410. const data = array[i];
  32411. const distanceSquared = data.distance;
  32412. if (distanceSquared > bestDistanceSquared) {
  32413. break;
  32414. } else {
  32415. const tile = data.tile;
  32416. const scene = tile.cached.scene;
  32417. let hit = null;
  32418. if (activeSet.has(scene)) {
  32419. // save the hit if it's closer
  32420. intersectTileScene(scene, raycaster, _hitArray);
  32421. if (_hitArray.length > 0) {
  32422. if (_hitArray.length > 1) {
  32423. _hitArray.sort(distanceSort);
  32424. }
  32425. hit = _hitArray[0];
  32426. }
  32427. } else {
  32428. hit = raycastTraverseFirstHit(tile, group, activeSet, raycaster);
  32429. }
  32430. if (hit) {
  32431. const hitDistanceSquared = hit.distance * hit.distance;
  32432. if (hitDistanceSquared < bestDistanceSquared) {
  32433. bestDistanceSquared = hitDistanceSquared;
  32434. bestHit = hit;
  32435. }
  32436. _hitArray.length = 0;
  32437. }
  32438. }
  32439. }
  32440. return bestHit;
  32441. }
  32442. function raycastTraverse(tile, group, activeSet, raycaster, intersects) {
  32443. const cached = tile.cached;
  32444. const groupMatrixWorld = group.matrixWorld;
  32445. const transformMat = cached.transform;
  32446. _mat.copy(groupMatrixWorld);
  32447. _mat.multiply(transformMat);
  32448. const sphere = cached.sphere;
  32449. if (sphere) {
  32450. _sphere.copy(sphere);
  32451. _sphere.applyMatrix4(_mat);
  32452. if (!raycaster.ray.intersectsSphere(_sphere)) {
  32453. return;
  32454. }
  32455. }
  32456. const boundingBox = cached.box;
  32457. const obbMat = cached.boxTransform;
  32458. if (boundingBox) {
  32459. _mat.multiply(obbMat);
  32460. _mat.getInverse(_mat);
  32461. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  32462. if (!_ray.intersectsBox(boundingBox)) {
  32463. return;
  32464. }
  32465. } // TODO: check region
  32466. const scene = cached.scene;
  32467. if (activeSet.has(scene)) {
  32468. scene.traverse(c => {
  32469. if (!(c instanceof _three.Box3Helper)) {
  32470. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  32471. }
  32472. });
  32473. return;
  32474. }
  32475. const children = tile.children;
  32476. for (let i = 0, l = children.length; i < l; i++) {
  32477. raycastTraverse(children[i], group, activeSet, raycaster, intersects);
  32478. }
  32479. }
  32480. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/TilesRenderer.js":[function(require,module,exports) {
  32481. "use strict";
  32482. Object.defineProperty(exports, "__esModule", {
  32483. value: true
  32484. });
  32485. exports.TilesRenderer = void 0;
  32486. var _TilesRendererBase = require("../base/TilesRendererBase.js");
  32487. var _B3DMLoader = require("./B3DMLoader.js");
  32488. var _TilesGroup = require("./TilesGroup.js");
  32489. var _three = require("three");
  32490. var _raycastTraverse = require("./raycastTraverse.js");
  32491. const DEG2RAD = _three.Math.DEG2RAD;
  32492. const tempMat = new _three.Matrix4();
  32493. const tempQuaternion = new _three.Quaternion();
  32494. const tempVector = new _three.Vector3();
  32495. const resVector = new _three.Vector2();
  32496. const vecX = new _three.Vector3();
  32497. const vecY = new _three.Vector3();
  32498. const vecZ = new _three.Vector3();
  32499. const _sphere = new _three.Sphere();
  32500. function emptyRaycast() {}
  32501. class TilesRenderer extends _TilesRendererBase.TilesRendererBase {
  32502. get displayBounds() {
  32503. return this._displayBounds;
  32504. }
  32505. set displayBounds(val) {
  32506. if (val !== this.displayBounds) {
  32507. this._displayBounds = val;
  32508. this.traverse(t => {
  32509. const scene = t.cached.scene;
  32510. const boxHelper = t.cached.boxHelperGroup;
  32511. if (scene) {
  32512. if (val) {
  32513. scene.add(boxHelper);
  32514. boxHelper.updateMatrixWorld(true);
  32515. } else {
  32516. scene.remove(boxHelper);
  32517. }
  32518. }
  32519. });
  32520. }
  32521. }
  32522. constructor(url, cameras, renderer) {
  32523. super(url);
  32524. this.group = new _TilesGroup.TilesGroup(this);
  32525. this.cameras = Array.isArray(cameras) ? cameras : [cameras];
  32526. this.frustums = [];
  32527. this.renderer = renderer;
  32528. this.activeSet = new Set();
  32529. this.visibleSet = new Set();
  32530. }
  32531. /* Public API */
  32532. getBounds(box) {
  32533. if (!this.root) {
  32534. return false;
  32535. }
  32536. const cached = this.root.cached;
  32537. const boundingBox = cached.box;
  32538. const obbMat = cached.boxTransform;
  32539. const transformMat = cached.transform;
  32540. box.copy(boundingBox);
  32541. tempMat.multiplyMatrices(transformMat, obbMat);
  32542. box.applyMatrix4(tempMat);
  32543. return true;
  32544. }
  32545. raycast(raycaster, intersects) {
  32546. if (!this.root) return;
  32547. if (raycaster.firstHitOnly) {
  32548. const hit = (0, _raycastTraverse.raycastTraverseFirstHit)(this.root, this.group, this.activeSet, raycaster, intersects);
  32549. if (hit) {
  32550. intersects.push(hit);
  32551. }
  32552. } else {
  32553. (0, _raycastTraverse.raycastTraverse)(this.root, this.group, this.activeSet, raycaster, intersects);
  32554. }
  32555. }
  32556. /* Overriden */
  32557. update() {
  32558. const group = this.group;
  32559. const renderer = this.renderer;
  32560. const cameras = this.cameras;
  32561. const frustums = this.frustums; // automatically scale the array of frustums to match the cameras
  32562. while (frustums.length > cameras.length) {
  32563. frustums.pop();
  32564. }
  32565. while (frustums.length < cameras.length) {
  32566. frustums.push(new _three.Frustum());
  32567. } // store the camera frustums in the 3d tiles root frame
  32568. for (let i = 0, l = frustums.length; i < l; i++) {
  32569. const camera = cameras[i];
  32570. const frustum = frustums[i];
  32571. tempMat.copy(group.matrixWorld);
  32572. tempMat.premultiply(camera.matrixWorldInverse);
  32573. tempMat.premultiply(camera.projectionMatrix);
  32574. frustum.setFromMatrix(tempMat);
  32575. } // store the resolution of the render
  32576. renderer.getSize(resVector);
  32577. resVector.multiplyScalar(renderer.getPixelRatio());
  32578. super.update();
  32579. }
  32580. preprocessNode(tile, parentTile, tileSetDir) {
  32581. super.preprocessNode(tile, parentTile, tileSetDir);
  32582. const transform = new _three.Matrix4();
  32583. if (tile.transform) {
  32584. const transformArr = tile.transform;
  32585. for (let i = 0; i < 16; i++) {
  32586. transform.elements[i] = transformArr[i];
  32587. }
  32588. } else {
  32589. transform.identity();
  32590. }
  32591. if (parentTile) {
  32592. transform.multiply(parentTile.cached.transform);
  32593. }
  32594. let box = null;
  32595. let boxTransform = null;
  32596. if ('box' in tile.boundingVolume) {
  32597. const data = tile.boundingVolume.box;
  32598. box = new _three.Box3();
  32599. boxTransform = new _three.Matrix4(); // get the extents of the bounds in each axis
  32600. vecX.set(data[3], data[4], data[5]);
  32601. vecY.set(data[6], data[7], data[8]);
  32602. vecZ.set(data[9], data[10], data[11]);
  32603. const scaleX = vecX.length();
  32604. const scaleY = vecY.length();
  32605. const scaleZ = vecZ.length();
  32606. vecX.normalize();
  32607. vecY.normalize();
  32608. vecZ.normalize(); // create the oriented frame that the box exists in
  32609. boxTransform.set(vecX.x, vecY.x, vecZ.x, data[0], vecX.y, vecY.y, vecZ.y, data[1], vecX.z, vecY.z, vecZ.z, data[2], 0, 0, 0, 1); // scale the box by the extents
  32610. box.min.set(-scaleX, -scaleY, -scaleZ);
  32611. box.max.set(scaleX, scaleY, scaleZ);
  32612. }
  32613. let sphere = null;
  32614. if ('sphere' in tile.boundingVolume) {
  32615. const data = tile.boundingVolume.sphere;
  32616. sphere = new _three.Sphere();
  32617. sphere.center.set(data[0], data[1], data[2]);
  32618. sphere.radius = data[3];
  32619. } else if ('box' in tile.boundingVolume) {
  32620. sphere = new _three.Sphere();
  32621. box.getBoundingSphere(sphere);
  32622. boxTransform.decompose(sphere.center, tempQuaternion, tempVector);
  32623. }
  32624. let region = null;
  32625. if ('region' in tile.boundingVolume) {
  32626. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  32627. }
  32628. tile.cached = {
  32629. loadIndex: 0,
  32630. transform,
  32631. active: false,
  32632. box,
  32633. boxTransform,
  32634. sphere,
  32635. region,
  32636. boxHelper: null,
  32637. scene: null
  32638. };
  32639. }
  32640. parseTile(buffer, tile) {
  32641. tile._loadIndex = tile._loadIndex || 0;
  32642. tile._loadIndex++; // TODO: 90 degree rotation must be applied to GLTF file to resolve "up"
  32643. const loadIndex = tile._loadIndex;
  32644. return new _B3DMLoader.B3DMLoader().parse(buffer).then(res => {
  32645. if (tile._loadIndex !== loadIndex) {
  32646. return;
  32647. }
  32648. const cached = tile.cached;
  32649. const cachedBox = cached.box;
  32650. const cachedBoxMat = cached.boxTransform; // add a helper group to represent the obb rotation matrix
  32651. const boxHelper = new _three.Box3Helper(cachedBox);
  32652. const boxHelperGroup = new _three.Group();
  32653. cachedBoxMat.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  32654. boxHelperGroup.add(boxHelper);
  32655. boxHelperGroup.updateMatrixWorld(true);
  32656. const scene = res.scene;
  32657. cached.transform.decompose(scene.position, scene.quaternion, scene.scale);
  32658. scene.traverse(c => c.frustumCulled = false);
  32659. cached.boxHelperGroup = boxHelperGroup;
  32660. cached.scene = res.scene;
  32661. if (this.displayBounds) {
  32662. cached.scene.add(cached.boxHelperGroup);
  32663. } // We handle raycasting in a custom way so remove it from here
  32664. boxHelper.raycast = emptyRaycast;
  32665. scene.traverse(c => {
  32666. c.raycast = emptyRaycast;
  32667. });
  32668. });
  32669. }
  32670. disposeTile(tile) {
  32671. const cached = tile.cached;
  32672. if (cached.scene) {
  32673. const scene = cached.scene;
  32674. if (scene.parent) {
  32675. scene.parent.remove(scene);
  32676. }
  32677. scene.traverse(c => {
  32678. if (c.geometry) {
  32679. c.geometry.dispose();
  32680. }
  32681. if (c.material) {
  32682. c.material.dispose(); // TODO: dispose textures
  32683. }
  32684. });
  32685. cached.scene = null;
  32686. cached.boxHelperGroup = null;
  32687. }
  32688. tile._loadIndex++;
  32689. }
  32690. setTileVisible(tile, visible) {
  32691. const scene = tile.cached.scene;
  32692. const visibleSet = this.visibleSet;
  32693. const group = this.group;
  32694. if (visible) {
  32695. if (scene && !scene.parent) {
  32696. group.add(scene);
  32697. visibleSet.add(scene);
  32698. scene.updateMatrixWorld(true);
  32699. }
  32700. } else {
  32701. group.remove(scene);
  32702. visibleSet.delete(scene);
  32703. }
  32704. }
  32705. setTileActive(tile, active) {
  32706. const cached = tile.cached;
  32707. const activeSet = this.activeSet;
  32708. if (active !== cached.active) {
  32709. cached.active = active;
  32710. if (active) {
  32711. activeSet.add(cached.scene);
  32712. } else {
  32713. activeSet.delete(cached.scene);
  32714. }
  32715. }
  32716. }
  32717. calculateError(tile) {
  32718. const cached = tile.cached;
  32719. const cameras = this.cameras; // TODO: Use the content bounding volume here?
  32720. const boundingVolume = tile.boundingVolume;
  32721. const transformMat = cached.transform;
  32722. if ('box' in boundingVolume) {
  32723. const group = this.group;
  32724. const boundingBox = cached.box;
  32725. const obbMat = cached.boxTransform; // TODO: these can likely be cached? Or the world transform mat can be used
  32726. // transformMat can be rolled into oobMat
  32727. tempMat.copy(group.matrixWorld);
  32728. tempMat.multiply(transformMat);
  32729. tempMat.multiply(obbMat);
  32730. tempMat.getInverse(tempMat); // NOTE: scale is inverted here.
  32731. // assume the scales on all axes are uniform.
  32732. let invScale; // account for tile scale.
  32733. tempVector.setFromMatrixScale(tempMat);
  32734. invScale = tempVector.x;
  32735. if (Math.abs(Math.max(tempVector.x - tempVector.y, tempVector.x - tempVector.z)) > 1e-6) {
  32736. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.');
  32737. }
  32738. let minError = Infinity;
  32739. for (let i = 0, l = cameras.length; i < l; i++) {
  32740. // transform camera position into local frame of the tile bounding box
  32741. const cam = cameras[i];
  32742. tempVector.copy(cam.position);
  32743. tempVector.applyMatrix4(tempMat);
  32744. let error;
  32745. if (cam.isOrthographicCamera) {
  32746. const w = cam.right - cam.left;
  32747. const h = cam.top - cam.bottom;
  32748. const pixelSize = Math.max(h / resVector.height, w / resVector.width);
  32749. error = tile.geometricError / (pixelSize * invScale);
  32750. } else {
  32751. const distance = boundingBox.distanceToPoint(tempVector);
  32752. const scaledDistance = distance * invScale;
  32753. const sseDenominator = 2 * Math.tan(0.5 * cam.fov * DEG2RAD);
  32754. error = tile.geometricError * resVector.height / (scaledDistance * sseDenominator);
  32755. }
  32756. minError = Math.min(minError, error);
  32757. }
  32758. return minError;
  32759. } else if ('sphere' in boundingVolume) {
  32760. // const sphere = cached.sphere;
  32761. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  32762. } else if ('region' in boundingVolume) {
  32763. // unsupported
  32764. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  32765. }
  32766. return Infinity;
  32767. }
  32768. tileInView(tile) {
  32769. // TODO: we should use the more precise bounding volumes here if possible
  32770. // cache the root-space planes
  32771. const sphere = tile.cached.sphere;
  32772. if (sphere) {
  32773. _sphere.copy(sphere);
  32774. _sphere.applyMatrix4(tile.cached.transform);
  32775. const frustums = this.frustums;
  32776. for (let i = 0, l = frustums.length; i < l; i++) {
  32777. const frustum = frustums[i];
  32778. if (frustum.intersectsSphere(_sphere)) {
  32779. return true;
  32780. }
  32781. }
  32782. return false;
  32783. }
  32784. return true;
  32785. }
  32786. }
  32787. exports.TilesRenderer = TilesRenderer;
  32788. },{"../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/index.js":[function(require,module,exports) {
  32789. "use strict";
  32790. Object.defineProperty(exports, "__esModule", {
  32791. value: true
  32792. });
  32793. Object.defineProperty(exports, "TilesRenderer", {
  32794. enumerable: true,
  32795. get: function () {
  32796. return _TilesRenderer.TilesRenderer;
  32797. }
  32798. });
  32799. Object.defineProperty(exports, "B3DMLoader", {
  32800. enumerable: true,
  32801. get: function () {
  32802. return _B3DMLoader.B3DMLoader;
  32803. }
  32804. });
  32805. Object.defineProperty(exports, "TilesRendererBase", {
  32806. enumerable: true,
  32807. get: function () {
  32808. return _TilesRendererBase.TilesRendererBase;
  32809. }
  32810. });
  32811. Object.defineProperty(exports, "B3DMLoaderBase", {
  32812. enumerable: true,
  32813. get: function () {
  32814. return _B3DMLoaderBase.B3DMLoaderBase;
  32815. }
  32816. });
  32817. Object.defineProperty(exports, "LRUCache", {
  32818. enumerable: true,
  32819. get: function () {
  32820. return _LRUCache.LRUCache;
  32821. }
  32822. });
  32823. Object.defineProperty(exports, "PriorityQueue", {
  32824. enumerable: true,
  32825. get: function () {
  32826. return _PriorityQueue.PriorityQueue;
  32827. }
  32828. });
  32829. var _TilesRenderer = require("./three/TilesRenderer.js");
  32830. var _B3DMLoader = require("./three/B3DMLoader.js");
  32831. var _TilesRendererBase = require("./base/TilesRendererBase.js");
  32832. var _B3DMLoaderBase = require("./base/B3DMLoaderBase.js");
  32833. var _LRUCache = require("./utilities/LRUCache.js");
  32834. var _PriorityQueue = require("./utilities/PriorityQueue.js");
  32835. },{"./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) {
  32836. "use strict";
  32837. Object.defineProperty(exports, "__esModule", {
  32838. value: true
  32839. });
  32840. exports.MapControls = exports.OrbitControls = void 0;
  32841. var _threeModule = require("../../../build/three.module.js");
  32842. /**
  32843. * @author qiao / https://github.com/qiao
  32844. * @author mrdoob / http://mrdoob.com
  32845. * @author alteredq / http://alteredqualia.com/
  32846. * @author WestLangley / http://github.com/WestLangley
  32847. * @author erich666 / http://erichaines.com
  32848. * @author ScieCode / http://github.com/sciecode
  32849. */
  32850. // This set of controls performs orbiting, dollying (zooming), and panning.
  32851. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  32852. //
  32853. // Orbit - left mouse / touch: one-finger move
  32854. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  32855. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  32856. var OrbitControls = function (object, domElement) {
  32857. this.object = object;
  32858. this.domElement = domElement !== undefined ? domElement : document; // Set to false to disable this control
  32859. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  32860. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  32861. this.minDistance = 0;
  32862. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  32863. this.minZoom = 0;
  32864. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  32865. // Range is 0 to Math.PI radians.
  32866. this.minPolarAngle = 0; // radians
  32867. this.maxPolarAngle = Math.PI; // radians
  32868. // How far you can orbit horizontally, upper and lower limits.
  32869. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  32870. this.minAzimuthAngle = -Infinity; // radians
  32871. this.maxAzimuthAngle = Infinity; // radians
  32872. // Set to true to enable damping (inertia)
  32873. // If damping is enabled, you must call controls.update() in your animation loop
  32874. this.enableDamping = false;
  32875. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  32876. // Set to false to disable zooming
  32877. this.enableZoom = true;
  32878. this.zoomSpeed = 1.0; // Set to false to disable rotating
  32879. this.enableRotate = true;
  32880. this.rotateSpeed = 1.0; // Set to false to disable panning
  32881. this.enablePan = true;
  32882. this.panSpeed = 1.0;
  32883. this.screenSpacePanning = false; // if true, pan in screen-space
  32884. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  32885. // Set to true to automatically rotate around the target
  32886. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  32887. this.autoRotate = false;
  32888. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  32889. // Set to false to disable use of the keys
  32890. this.enableKeys = true; // The four arrow keys
  32891. this.keys = {
  32892. LEFT: 37,
  32893. UP: 38,
  32894. RIGHT: 39,
  32895. BOTTOM: 40
  32896. }; // Mouse buttons
  32897. this.mouseButtons = {
  32898. LEFT: _threeModule.MOUSE.ROTATE,
  32899. MIDDLE: _threeModule.MOUSE.DOLLY,
  32900. RIGHT: _threeModule.MOUSE.PAN
  32901. }; // Touch fingers
  32902. this.touches = {
  32903. ONE: _threeModule.TOUCH.ROTATE,
  32904. TWO: _threeModule.TOUCH.DOLLY_PAN
  32905. }; // for reset
  32906. this.target0 = this.target.clone();
  32907. this.position0 = this.object.position.clone();
  32908. this.zoom0 = this.object.zoom; //
  32909. // public methods
  32910. //
  32911. this.getPolarAngle = function () {
  32912. return spherical.phi;
  32913. };
  32914. this.getAzimuthalAngle = function () {
  32915. return spherical.theta;
  32916. };
  32917. this.saveState = function () {
  32918. scope.target0.copy(scope.target);
  32919. scope.position0.copy(scope.object.position);
  32920. scope.zoom0 = scope.object.zoom;
  32921. };
  32922. this.reset = function () {
  32923. scope.target.copy(scope.target0);
  32924. scope.object.position.copy(scope.position0);
  32925. scope.object.zoom = scope.zoom0;
  32926. scope.object.updateProjectionMatrix();
  32927. scope.dispatchEvent(changeEvent);
  32928. scope.update();
  32929. state = STATE.NONE;
  32930. }; // this method is exposed, but perhaps it would be better if we can make it private...
  32931. this.update = function () {
  32932. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  32933. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  32934. var quatInverse = quat.clone().inverse();
  32935. var lastPosition = new _threeModule.Vector3();
  32936. var lastQuaternion = new _threeModule.Quaternion();
  32937. return function update() {
  32938. var position = scope.object.position;
  32939. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  32940. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  32941. spherical.setFromVector3(offset);
  32942. if (scope.autoRotate && state === STATE.NONE) {
  32943. rotateLeft(getAutoRotationAngle());
  32944. }
  32945. if (scope.enableDamping) {
  32946. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  32947. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  32948. } else {
  32949. spherical.theta += sphericalDelta.theta;
  32950. spherical.phi += sphericalDelta.phi;
  32951. } // restrict theta to be between desired limits
  32952. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  32953. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  32954. spherical.makeSafe();
  32955. spherical.radius *= scale; // restrict radius to be between desired limits
  32956. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  32957. if (scope.enableDamping === true) {
  32958. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  32959. } else {
  32960. scope.target.add(panOffset);
  32961. }
  32962. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  32963. offset.applyQuaternion(quatInverse);
  32964. position.copy(scope.target).add(offset);
  32965. scope.object.lookAt(scope.target);
  32966. if (scope.enableDamping === true) {
  32967. sphericalDelta.theta *= 1 - scope.dampingFactor;
  32968. sphericalDelta.phi *= 1 - scope.dampingFactor;
  32969. panOffset.multiplyScalar(1 - scope.dampingFactor);
  32970. } else {
  32971. sphericalDelta.set(0, 0, 0);
  32972. panOffset.set(0, 0, 0);
  32973. }
  32974. scale = 1; // update condition is:
  32975. // min(camera displacement, camera rotation in radians)^2 > EPS
  32976. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  32977. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  32978. scope.dispatchEvent(changeEvent);
  32979. lastPosition.copy(scope.object.position);
  32980. lastQuaternion.copy(scope.object.quaternion);
  32981. zoomChanged = false;
  32982. return true;
  32983. }
  32984. return false;
  32985. };
  32986. }();
  32987. this.dispose = function () {
  32988. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  32989. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  32990. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  32991. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  32992. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  32993. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  32994. document.removeEventListener('mousemove', onMouseMove, false);
  32995. document.removeEventListener('mouseup', onMouseUp, false);
  32996. window.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  32997. }; //
  32998. // internals
  32999. //
  33000. var scope = this;
  33001. var changeEvent = {
  33002. type: 'change'
  33003. };
  33004. var startEvent = {
  33005. type: 'start'
  33006. };
  33007. var endEvent = {
  33008. type: 'end'
  33009. };
  33010. var STATE = {
  33011. NONE: -1,
  33012. ROTATE: 0,
  33013. DOLLY: 1,
  33014. PAN: 2,
  33015. TOUCH_ROTATE: 3,
  33016. TOUCH_PAN: 4,
  33017. TOUCH_DOLLY_PAN: 5,
  33018. TOUCH_DOLLY_ROTATE: 6
  33019. };
  33020. var state = STATE.NONE;
  33021. var EPS = 0.000001; // current position in spherical coordinates
  33022. var spherical = new _threeModule.Spherical();
  33023. var sphericalDelta = new _threeModule.Spherical();
  33024. var scale = 1;
  33025. var panOffset = new _threeModule.Vector3();
  33026. var zoomChanged = false;
  33027. var rotateStart = new _threeModule.Vector2();
  33028. var rotateEnd = new _threeModule.Vector2();
  33029. var rotateDelta = new _threeModule.Vector2();
  33030. var panStart = new _threeModule.Vector2();
  33031. var panEnd = new _threeModule.Vector2();
  33032. var panDelta = new _threeModule.Vector2();
  33033. var dollyStart = new _threeModule.Vector2();
  33034. var dollyEnd = new _threeModule.Vector2();
  33035. var dollyDelta = new _threeModule.Vector2();
  33036. function getAutoRotationAngle() {
  33037. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  33038. }
  33039. function getZoomScale() {
  33040. return Math.pow(0.95, scope.zoomSpeed);
  33041. }
  33042. function rotateLeft(angle) {
  33043. sphericalDelta.theta -= angle;
  33044. }
  33045. function rotateUp(angle) {
  33046. sphericalDelta.phi -= angle;
  33047. }
  33048. var panLeft = function () {
  33049. var v = new _threeModule.Vector3();
  33050. return function panLeft(distance, objectMatrix) {
  33051. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  33052. v.multiplyScalar(-distance);
  33053. panOffset.add(v);
  33054. };
  33055. }();
  33056. var panUp = function () {
  33057. var v = new _threeModule.Vector3();
  33058. return function panUp(distance, objectMatrix) {
  33059. if (scope.screenSpacePanning === true) {
  33060. v.setFromMatrixColumn(objectMatrix, 1);
  33061. } else {
  33062. v.setFromMatrixColumn(objectMatrix, 0);
  33063. v.crossVectors(scope.object.up, v);
  33064. }
  33065. v.multiplyScalar(distance);
  33066. panOffset.add(v);
  33067. };
  33068. }(); // deltaX and deltaY are in pixels; right and down are positive
  33069. var pan = function () {
  33070. var offset = new _threeModule.Vector3();
  33071. return function pan(deltaX, deltaY) {
  33072. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33073. if (scope.object.isPerspectiveCamera) {
  33074. // perspective
  33075. var position = scope.object.position;
  33076. offset.copy(position).sub(scope.target);
  33077. var targetDistance = offset.length(); // half of the fov is center to top of screen
  33078. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  33079. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  33080. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  33081. } else if (scope.object.isOrthographicCamera) {
  33082. // orthographic
  33083. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  33084. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  33085. } else {
  33086. // camera neither orthographic nor perspective
  33087. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  33088. scope.enablePan = false;
  33089. }
  33090. };
  33091. }();
  33092. function dollyIn(dollyScale) {
  33093. if (scope.object.isPerspectiveCamera) {
  33094. scale /= dollyScale;
  33095. } else if (scope.object.isOrthographicCamera) {
  33096. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  33097. scope.object.updateProjectionMatrix();
  33098. zoomChanged = true;
  33099. } else {
  33100. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  33101. scope.enableZoom = false;
  33102. }
  33103. }
  33104. function dollyOut(dollyScale) {
  33105. if (scope.object.isPerspectiveCamera) {
  33106. scale *= dollyScale;
  33107. } else if (scope.object.isOrthographicCamera) {
  33108. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  33109. scope.object.updateProjectionMatrix();
  33110. zoomChanged = true;
  33111. } else {
  33112. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  33113. scope.enableZoom = false;
  33114. }
  33115. } //
  33116. // event callbacks - update the object state
  33117. //
  33118. function handleMouseDownRotate(event) {
  33119. rotateStart.set(event.clientX, event.clientY);
  33120. }
  33121. function handleMouseDownDolly(event) {
  33122. dollyStart.set(event.clientX, event.clientY);
  33123. }
  33124. function handleMouseDownPan(event) {
  33125. panStart.set(event.clientX, event.clientY);
  33126. }
  33127. function handleMouseMoveRotate(event) {
  33128. rotateEnd.set(event.clientX, event.clientY);
  33129. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  33130. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33131. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  33132. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  33133. rotateStart.copy(rotateEnd);
  33134. scope.update();
  33135. }
  33136. function handleMouseMoveDolly(event) {
  33137. dollyEnd.set(event.clientX, event.clientY);
  33138. dollyDelta.subVectors(dollyEnd, dollyStart);
  33139. if (dollyDelta.y > 0) {
  33140. dollyIn(getZoomScale());
  33141. } else if (dollyDelta.y < 0) {
  33142. dollyOut(getZoomScale());
  33143. }
  33144. dollyStart.copy(dollyEnd);
  33145. scope.update();
  33146. }
  33147. function handleMouseMovePan(event) {
  33148. panEnd.set(event.clientX, event.clientY);
  33149. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  33150. pan(panDelta.x, panDelta.y);
  33151. panStart.copy(panEnd);
  33152. scope.update();
  33153. }
  33154. function handleMouseUp()
  33155. /*event*/
  33156. {// no-op
  33157. }
  33158. function handleMouseWheel(event) {
  33159. if (event.deltaY < 0) {
  33160. dollyOut(getZoomScale());
  33161. } else if (event.deltaY > 0) {
  33162. dollyIn(getZoomScale());
  33163. }
  33164. scope.update();
  33165. }
  33166. function handleKeyDown(event) {
  33167. var needsUpdate = false;
  33168. switch (event.keyCode) {
  33169. case scope.keys.UP:
  33170. pan(0, scope.keyPanSpeed);
  33171. needsUpdate = true;
  33172. break;
  33173. case scope.keys.BOTTOM:
  33174. pan(0, -scope.keyPanSpeed);
  33175. needsUpdate = true;
  33176. break;
  33177. case scope.keys.LEFT:
  33178. pan(scope.keyPanSpeed, 0);
  33179. needsUpdate = true;
  33180. break;
  33181. case scope.keys.RIGHT:
  33182. pan(-scope.keyPanSpeed, 0);
  33183. needsUpdate = true;
  33184. break;
  33185. }
  33186. if (needsUpdate) {
  33187. // prevent the browser from scrolling on cursor keys
  33188. event.preventDefault();
  33189. scope.update();
  33190. }
  33191. }
  33192. function handleTouchStartRotate(event) {
  33193. if (event.touches.length == 1) {
  33194. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  33195. } else {
  33196. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33197. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33198. rotateStart.set(x, y);
  33199. }
  33200. }
  33201. function handleTouchStartPan(event) {
  33202. if (event.touches.length == 1) {
  33203. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  33204. } else {
  33205. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33206. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33207. panStart.set(x, y);
  33208. }
  33209. }
  33210. function handleTouchStartDolly(event) {
  33211. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33212. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33213. var distance = Math.sqrt(dx * dx + dy * dy);
  33214. dollyStart.set(0, distance);
  33215. }
  33216. function handleTouchStartDollyPan(event) {
  33217. if (scope.enableZoom) handleTouchStartDolly(event);
  33218. if (scope.enablePan) handleTouchStartPan(event);
  33219. }
  33220. function handleTouchStartDollyRotate(event) {
  33221. if (scope.enableZoom) handleTouchStartDolly(event);
  33222. if (scope.enableRotate) handleTouchStartRotate(event);
  33223. }
  33224. function handleTouchMoveRotate(event) {
  33225. if (event.touches.length == 1) {
  33226. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33227. } else {
  33228. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33229. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33230. rotateEnd.set(x, y);
  33231. }
  33232. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  33233. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  33234. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  33235. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  33236. rotateStart.copy(rotateEnd);
  33237. }
  33238. function handleTouchMovePan(event) {
  33239. if (event.touches.length == 1) {
  33240. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  33241. } else {
  33242. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  33243. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  33244. panEnd.set(x, y);
  33245. }
  33246. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  33247. pan(panDelta.x, panDelta.y);
  33248. panStart.copy(panEnd);
  33249. }
  33250. function handleTouchMoveDolly(event) {
  33251. var dx = event.touches[0].pageX - event.touches[1].pageX;
  33252. var dy = event.touches[0].pageY - event.touches[1].pageY;
  33253. var distance = Math.sqrt(dx * dx + dy * dy);
  33254. dollyEnd.set(0, distance);
  33255. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  33256. dollyIn(dollyDelta.y);
  33257. dollyStart.copy(dollyEnd);
  33258. }
  33259. function handleTouchMoveDollyPan(event) {
  33260. if (scope.enableZoom) handleTouchMoveDolly(event);
  33261. if (scope.enablePan) handleTouchMovePan(event);
  33262. }
  33263. function handleTouchMoveDollyRotate(event) {
  33264. if (scope.enableZoom) handleTouchMoveDolly(event);
  33265. if (scope.enableRotate) handleTouchMoveRotate(event);
  33266. }
  33267. function handleTouchEnd()
  33268. /*event*/
  33269. {} // no-op
  33270. //
  33271. // event handlers - FSM: listen for events and reset state
  33272. //
  33273. function onMouseDown(event) {
  33274. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  33275. event.preventDefault(); // Manually set the focus since calling preventDefault above
  33276. // prevents the browser from setting it automatically.
  33277. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  33278. switch (event.button) {
  33279. case 0:
  33280. switch (scope.mouseButtons.LEFT) {
  33281. case _threeModule.MOUSE.ROTATE:
  33282. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33283. if (scope.enablePan === false) return;
  33284. handleMouseDownPan(event);
  33285. state = STATE.PAN;
  33286. } else {
  33287. if (scope.enableRotate === false) return;
  33288. handleMouseDownRotate(event);
  33289. state = STATE.ROTATE;
  33290. }
  33291. break;
  33292. case _threeModule.MOUSE.PAN:
  33293. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33294. if (scope.enableRotate === false) return;
  33295. handleMouseDownRotate(event);
  33296. state = STATE.ROTATE;
  33297. } else {
  33298. if (scope.enablePan === false) return;
  33299. handleMouseDownPan(event);
  33300. state = STATE.PAN;
  33301. }
  33302. break;
  33303. default:
  33304. state = STATE.NONE;
  33305. }
  33306. break;
  33307. case 1:
  33308. switch (scope.mouseButtons.MIDDLE) {
  33309. case _threeModule.MOUSE.DOLLY:
  33310. if (scope.enableZoom === false) return;
  33311. handleMouseDownDolly(event);
  33312. state = STATE.DOLLY;
  33313. break;
  33314. default:
  33315. state = STATE.NONE;
  33316. }
  33317. break;
  33318. case 2:
  33319. switch (scope.mouseButtons.RIGHT) {
  33320. case _threeModule.MOUSE.ROTATE:
  33321. if (scope.enableRotate === false) return;
  33322. handleMouseDownRotate(event);
  33323. state = STATE.ROTATE;
  33324. break;
  33325. case _threeModule.MOUSE.PAN:
  33326. if (scope.enablePan === false) return;
  33327. handleMouseDownPan(event);
  33328. state = STATE.PAN;
  33329. break;
  33330. default:
  33331. state = STATE.NONE;
  33332. }
  33333. break;
  33334. }
  33335. if (state !== STATE.NONE) {
  33336. document.addEventListener('mousemove', onMouseMove, false);
  33337. document.addEventListener('mouseup', onMouseUp, false);
  33338. scope.dispatchEvent(startEvent);
  33339. }
  33340. }
  33341. function onMouseMove(event) {
  33342. if (scope.enabled === false) return;
  33343. event.preventDefault();
  33344. switch (state) {
  33345. case STATE.ROTATE:
  33346. if (scope.enableRotate === false) return;
  33347. handleMouseMoveRotate(event);
  33348. break;
  33349. case STATE.DOLLY:
  33350. if (scope.enableZoom === false) return;
  33351. handleMouseMoveDolly(event);
  33352. break;
  33353. case STATE.PAN:
  33354. if (scope.enablePan === false) return;
  33355. handleMouseMovePan(event);
  33356. break;
  33357. }
  33358. }
  33359. function onMouseUp(event) {
  33360. if (scope.enabled === false) return;
  33361. handleMouseUp(event);
  33362. document.removeEventListener('mousemove', onMouseMove, false);
  33363. document.removeEventListener('mouseup', onMouseUp, false);
  33364. scope.dispatchEvent(endEvent);
  33365. state = STATE.NONE;
  33366. }
  33367. function onMouseWheel(event) {
  33368. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  33369. event.preventDefault();
  33370. event.stopPropagation();
  33371. scope.dispatchEvent(startEvent);
  33372. handleMouseWheel(event);
  33373. scope.dispatchEvent(endEvent);
  33374. }
  33375. function onKeyDown(event) {
  33376. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  33377. handleKeyDown(event);
  33378. }
  33379. function onTouchStart(event) {
  33380. if (scope.enabled === false) return;
  33381. event.preventDefault();
  33382. switch (event.touches.length) {
  33383. case 1:
  33384. switch (scope.touches.ONE) {
  33385. case _threeModule.TOUCH.ROTATE:
  33386. if (scope.enableRotate === false) return;
  33387. handleTouchStartRotate(event);
  33388. state = STATE.TOUCH_ROTATE;
  33389. break;
  33390. case _threeModule.TOUCH.PAN:
  33391. if (scope.enablePan === false) return;
  33392. handleTouchStartPan(event);
  33393. state = STATE.TOUCH_PAN;
  33394. break;
  33395. default:
  33396. state = STATE.NONE;
  33397. }
  33398. break;
  33399. case 2:
  33400. switch (scope.touches.TWO) {
  33401. case _threeModule.TOUCH.DOLLY_PAN:
  33402. if (scope.enableZoom === false && scope.enablePan === false) return;
  33403. handleTouchStartDollyPan(event);
  33404. state = STATE.TOUCH_DOLLY_PAN;
  33405. break;
  33406. case _threeModule.TOUCH.DOLLY_ROTATE:
  33407. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33408. handleTouchStartDollyRotate(event);
  33409. state = STATE.TOUCH_DOLLY_ROTATE;
  33410. break;
  33411. default:
  33412. state = STATE.NONE;
  33413. }
  33414. break;
  33415. default:
  33416. state = STATE.NONE;
  33417. }
  33418. if (state !== STATE.NONE) {
  33419. scope.dispatchEvent(startEvent);
  33420. }
  33421. }
  33422. function onTouchMove(event) {
  33423. if (scope.enabled === false) return;
  33424. event.preventDefault();
  33425. event.stopPropagation();
  33426. switch (state) {
  33427. case STATE.TOUCH_ROTATE:
  33428. if (scope.enableRotate === false) return;
  33429. handleTouchMoveRotate(event);
  33430. scope.update();
  33431. break;
  33432. case STATE.TOUCH_PAN:
  33433. if (scope.enablePan === false) return;
  33434. handleTouchMovePan(event);
  33435. scope.update();
  33436. break;
  33437. case STATE.TOUCH_DOLLY_PAN:
  33438. if (scope.enableZoom === false && scope.enablePan === false) return;
  33439. handleTouchMoveDollyPan(event);
  33440. scope.update();
  33441. break;
  33442. case STATE.TOUCH_DOLLY_ROTATE:
  33443. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33444. handleTouchMoveDollyRotate(event);
  33445. scope.update();
  33446. break;
  33447. default:
  33448. state = STATE.NONE;
  33449. }
  33450. }
  33451. function onTouchEnd(event) {
  33452. if (scope.enabled === false) return;
  33453. handleTouchEnd(event);
  33454. scope.dispatchEvent(endEvent);
  33455. state = STATE.NONE;
  33456. }
  33457. function onContextMenu(event) {
  33458. if (scope.enabled === false) return;
  33459. event.preventDefault();
  33460. } //
  33461. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  33462. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  33463. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  33464. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  33465. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  33466. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  33467. window.addEventListener('keydown', onKeyDown, false); // force an update at start
  33468. this.update();
  33469. };
  33470. exports.OrbitControls = OrbitControls;
  33471. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33472. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  33473. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  33474. // This is very similar to OrbitControls, another set of touch behavior
  33475. //
  33476. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  33477. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  33478. // Pan - left mouse, or arrow keys / touch: one-finger move
  33479. var MapControls = function (object, domElement) {
  33480. OrbitControls.call(this, object, domElement);
  33481. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  33482. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  33483. this.touches.ONE = _threeModule.TOUCH.PAN;
  33484. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  33485. };
  33486. exports.MapControls = MapControls;
  33487. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33488. MapControls.prototype.constructor = MapControls;
  33489. },{"../../../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) {
  33490. "use strict";
  33491. Object.defineProperty(exports, "__esModule", {
  33492. value: true
  33493. });
  33494. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  33495. /**
  33496. * dat-gui JavaScript Controller Library
  33497. * http://code.google.com/p/dat-gui
  33498. *
  33499. * Copyright 2011 Data Arts Team, Google Creative Lab
  33500. *
  33501. * Licensed under the Apache License, Version 2.0 (the "License");
  33502. * you may not use this file except in compliance with the License.
  33503. * You may obtain a copy of the License at
  33504. *
  33505. * http://www.apache.org/licenses/LICENSE-2.0
  33506. */
  33507. function ___$insertStyle(css) {
  33508. if (!css) {
  33509. return;
  33510. }
  33511. if (typeof window === 'undefined') {
  33512. return;
  33513. }
  33514. var style = document.createElement('style');
  33515. style.setAttribute('type', 'text/css');
  33516. style.innerHTML = css;
  33517. document.head.appendChild(style);
  33518. return css;
  33519. }
  33520. function colorToString(color, forceCSSHex) {
  33521. var colorFormat = color.__state.conversionName.toString();
  33522. var r = Math.round(color.r);
  33523. var g = Math.round(color.g);
  33524. var b = Math.round(color.b);
  33525. var a = color.a;
  33526. var h = Math.round(color.h);
  33527. var s = color.s.toFixed(1);
  33528. var v = color.v.toFixed(1);
  33529. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  33530. var str = color.hex.toString(16);
  33531. while (str.length < 6) {
  33532. str = '0' + str;
  33533. }
  33534. return '#' + str;
  33535. } else if (colorFormat === 'CSS_RGB') {
  33536. return 'rgb(' + r + ',' + g + ',' + b + ')';
  33537. } else if (colorFormat === 'CSS_RGBA') {
  33538. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  33539. } else if (colorFormat === 'HEX') {
  33540. return '0x' + color.hex.toString(16);
  33541. } else if (colorFormat === 'RGB_ARRAY') {
  33542. return '[' + r + ',' + g + ',' + b + ']';
  33543. } else if (colorFormat === 'RGBA_ARRAY') {
  33544. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  33545. } else if (colorFormat === 'RGB_OBJ') {
  33546. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  33547. } else if (colorFormat === 'RGBA_OBJ') {
  33548. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  33549. } else if (colorFormat === 'HSV_OBJ') {
  33550. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  33551. } else if (colorFormat === 'HSVA_OBJ') {
  33552. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  33553. }
  33554. return 'unknown format';
  33555. }
  33556. var ARR_EACH = Array.prototype.forEach;
  33557. var ARR_SLICE = Array.prototype.slice;
  33558. var Common = {
  33559. BREAK: {},
  33560. extend: function extend(target) {
  33561. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33562. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33563. keys.forEach(function (key) {
  33564. if (!this.isUndefined(obj[key])) {
  33565. target[key] = obj[key];
  33566. }
  33567. }.bind(this));
  33568. }, this);
  33569. return target;
  33570. },
  33571. defaults: function defaults(target) {
  33572. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33573. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33574. keys.forEach(function (key) {
  33575. if (this.isUndefined(target[key])) {
  33576. target[key] = obj[key];
  33577. }
  33578. }.bind(this));
  33579. }, this);
  33580. return target;
  33581. },
  33582. compose: function compose() {
  33583. var toCall = ARR_SLICE.call(arguments);
  33584. return function () {
  33585. var args = ARR_SLICE.call(arguments);
  33586. for (var i = toCall.length - 1; i >= 0; i--) {
  33587. args = [toCall[i].apply(this, args)];
  33588. }
  33589. return args[0];
  33590. };
  33591. },
  33592. each: function each(obj, itr, scope) {
  33593. if (!obj) {
  33594. return;
  33595. }
  33596. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  33597. obj.forEach(itr, scope);
  33598. } else if (obj.length === obj.length + 0) {
  33599. var key = void 0;
  33600. var l = void 0;
  33601. for (key = 0, l = obj.length; key < l; key++) {
  33602. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  33603. return;
  33604. }
  33605. }
  33606. } else {
  33607. for (var _key in obj) {
  33608. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  33609. return;
  33610. }
  33611. }
  33612. }
  33613. },
  33614. defer: function defer(fnc) {
  33615. setTimeout(fnc, 0);
  33616. },
  33617. debounce: function debounce(func, threshold, callImmediately) {
  33618. var timeout = void 0;
  33619. return function () {
  33620. var obj = this;
  33621. var args = arguments;
  33622. function delayed() {
  33623. timeout = null;
  33624. if (!callImmediately) func.apply(obj, args);
  33625. }
  33626. var callNow = callImmediately || !timeout;
  33627. clearTimeout(timeout);
  33628. timeout = setTimeout(delayed, threshold);
  33629. if (callNow) {
  33630. func.apply(obj, args);
  33631. }
  33632. };
  33633. },
  33634. toArray: function toArray(obj) {
  33635. if (obj.toArray) return obj.toArray();
  33636. return ARR_SLICE.call(obj);
  33637. },
  33638. isUndefined: function isUndefined(obj) {
  33639. return obj === undefined;
  33640. },
  33641. isNull: function isNull(obj) {
  33642. return obj === null;
  33643. },
  33644. isNaN: function (_isNaN) {
  33645. function isNaN() {
  33646. return _isNaN.apply(this, arguments);
  33647. }
  33648. isNaN.toString = function () {
  33649. return _isNaN.toString();
  33650. };
  33651. return isNaN;
  33652. }(function (obj) {
  33653. return isNaN(obj);
  33654. }),
  33655. isArray: Array.isArray || function (obj) {
  33656. return obj.constructor === Array;
  33657. },
  33658. isObject: function isObject(obj) {
  33659. return obj === Object(obj);
  33660. },
  33661. isNumber: function isNumber(obj) {
  33662. return obj === obj + 0;
  33663. },
  33664. isString: function isString(obj) {
  33665. return obj === obj + '';
  33666. },
  33667. isBoolean: function isBoolean(obj) {
  33668. return obj === false || obj === true;
  33669. },
  33670. isFunction: function isFunction(obj) {
  33671. return Object.prototype.toString.call(obj) === '[object Function]';
  33672. }
  33673. };
  33674. var INTERPRETATIONS = [{
  33675. litmus: Common.isString,
  33676. conversions: {
  33677. THREE_CHAR_HEX: {
  33678. read: function read(original) {
  33679. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  33680. if (test === null) {
  33681. return false;
  33682. }
  33683. return {
  33684. space: 'HEX',
  33685. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  33686. };
  33687. },
  33688. write: colorToString
  33689. },
  33690. SIX_CHAR_HEX: {
  33691. read: function read(original) {
  33692. var test = original.match(/^#([A-F0-9]{6})$/i);
  33693. if (test === null) {
  33694. return false;
  33695. }
  33696. return {
  33697. space: 'HEX',
  33698. hex: parseInt('0x' + test[1].toString(), 0)
  33699. };
  33700. },
  33701. write: colorToString
  33702. },
  33703. CSS_RGB: {
  33704. read: function read(original) {
  33705. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33706. if (test === null) {
  33707. return false;
  33708. }
  33709. return {
  33710. space: 'RGB',
  33711. r: parseFloat(test[1]),
  33712. g: parseFloat(test[2]),
  33713. b: parseFloat(test[3])
  33714. };
  33715. },
  33716. write: colorToString
  33717. },
  33718. CSS_RGBA: {
  33719. read: function read(original) {
  33720. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33721. if (test === null) {
  33722. return false;
  33723. }
  33724. return {
  33725. space: 'RGB',
  33726. r: parseFloat(test[1]),
  33727. g: parseFloat(test[2]),
  33728. b: parseFloat(test[3]),
  33729. a: parseFloat(test[4])
  33730. };
  33731. },
  33732. write: colorToString
  33733. }
  33734. }
  33735. }, {
  33736. litmus: Common.isNumber,
  33737. conversions: {
  33738. HEX: {
  33739. read: function read(original) {
  33740. return {
  33741. space: 'HEX',
  33742. hex: original,
  33743. conversionName: 'HEX'
  33744. };
  33745. },
  33746. write: function write(color) {
  33747. return color.hex;
  33748. }
  33749. }
  33750. }
  33751. }, {
  33752. litmus: Common.isArray,
  33753. conversions: {
  33754. RGB_ARRAY: {
  33755. read: function read(original) {
  33756. if (original.length !== 3) {
  33757. return false;
  33758. }
  33759. return {
  33760. space: 'RGB',
  33761. r: original[0],
  33762. g: original[1],
  33763. b: original[2]
  33764. };
  33765. },
  33766. write: function write(color) {
  33767. return [color.r, color.g, color.b];
  33768. }
  33769. },
  33770. RGBA_ARRAY: {
  33771. read: function read(original) {
  33772. if (original.length !== 4) return false;
  33773. return {
  33774. space: 'RGB',
  33775. r: original[0],
  33776. g: original[1],
  33777. b: original[2],
  33778. a: original[3]
  33779. };
  33780. },
  33781. write: function write(color) {
  33782. return [color.r, color.g, color.b, color.a];
  33783. }
  33784. }
  33785. }
  33786. }, {
  33787. litmus: Common.isObject,
  33788. conversions: {
  33789. RGBA_OBJ: {
  33790. read: function read(original) {
  33791. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  33792. return {
  33793. space: 'RGB',
  33794. r: original.r,
  33795. g: original.g,
  33796. b: original.b,
  33797. a: original.a
  33798. };
  33799. }
  33800. return false;
  33801. },
  33802. write: function write(color) {
  33803. return {
  33804. r: color.r,
  33805. g: color.g,
  33806. b: color.b,
  33807. a: color.a
  33808. };
  33809. }
  33810. },
  33811. RGB_OBJ: {
  33812. read: function read(original) {
  33813. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  33814. return {
  33815. space: 'RGB',
  33816. r: original.r,
  33817. g: original.g,
  33818. b: original.b
  33819. };
  33820. }
  33821. return false;
  33822. },
  33823. write: function write(color) {
  33824. return {
  33825. r: color.r,
  33826. g: color.g,
  33827. b: color.b
  33828. };
  33829. }
  33830. },
  33831. HSVA_OBJ: {
  33832. read: function read(original) {
  33833. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  33834. return {
  33835. space: 'HSV',
  33836. h: original.h,
  33837. s: original.s,
  33838. v: original.v,
  33839. a: original.a
  33840. };
  33841. }
  33842. return false;
  33843. },
  33844. write: function write(color) {
  33845. return {
  33846. h: color.h,
  33847. s: color.s,
  33848. v: color.v,
  33849. a: color.a
  33850. };
  33851. }
  33852. },
  33853. HSV_OBJ: {
  33854. read: function read(original) {
  33855. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  33856. return {
  33857. space: 'HSV',
  33858. h: original.h,
  33859. s: original.s,
  33860. v: original.v
  33861. };
  33862. }
  33863. return false;
  33864. },
  33865. write: function write(color) {
  33866. return {
  33867. h: color.h,
  33868. s: color.s,
  33869. v: color.v
  33870. };
  33871. }
  33872. }
  33873. }
  33874. }];
  33875. var result = void 0;
  33876. var toReturn = void 0;
  33877. var interpret = function interpret() {
  33878. toReturn = false;
  33879. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  33880. Common.each(INTERPRETATIONS, function (family) {
  33881. if (family.litmus(original)) {
  33882. Common.each(family.conversions, function (conversion, conversionName) {
  33883. result = conversion.read(original);
  33884. if (toReturn === false && result !== false) {
  33885. toReturn = result;
  33886. result.conversionName = conversionName;
  33887. result.conversion = conversion;
  33888. return Common.BREAK;
  33889. }
  33890. });
  33891. return Common.BREAK;
  33892. }
  33893. });
  33894. return toReturn;
  33895. };
  33896. var tmpComponent = void 0;
  33897. var ColorMath = {
  33898. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  33899. var hi = Math.floor(h / 60) % 6;
  33900. var f = h / 60 - Math.floor(h / 60);
  33901. var p = v * (1.0 - s);
  33902. var q = v * (1.0 - f * s);
  33903. var t = v * (1.0 - (1.0 - f) * s);
  33904. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  33905. return {
  33906. r: c[0] * 255,
  33907. g: c[1] * 255,
  33908. b: c[2] * 255
  33909. };
  33910. },
  33911. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  33912. var min = Math.min(r, g, b);
  33913. var max = Math.max(r, g, b);
  33914. var delta = max - min;
  33915. var h = void 0;
  33916. var s = void 0;
  33917. if (max !== 0) {
  33918. s = delta / max;
  33919. } else {
  33920. return {
  33921. h: NaN,
  33922. s: 0,
  33923. v: 0
  33924. };
  33925. }
  33926. if (r === max) {
  33927. h = (g - b) / delta;
  33928. } else if (g === max) {
  33929. h = 2 + (b - r) / delta;
  33930. } else {
  33931. h = 4 + (r - g) / delta;
  33932. }
  33933. h /= 6;
  33934. if (h < 0) {
  33935. h += 1;
  33936. }
  33937. return {
  33938. h: h * 360,
  33939. s: s,
  33940. v: max / 255
  33941. };
  33942. },
  33943. rgb_to_hex: function rgb_to_hex(r, g, b) {
  33944. var hex = this.hex_with_component(0, 2, r);
  33945. hex = this.hex_with_component(hex, 1, g);
  33946. hex = this.hex_with_component(hex, 0, b);
  33947. return hex;
  33948. },
  33949. component_from_hex: function component_from_hex(hex, componentIndex) {
  33950. return hex >> componentIndex * 8 & 0xFF;
  33951. },
  33952. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  33953. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  33954. }
  33955. };
  33956. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  33957. return typeof obj;
  33958. } : function (obj) {
  33959. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  33960. };
  33961. var classCallCheck = function (instance, Constructor) {
  33962. if (!(instance instanceof Constructor)) {
  33963. throw new TypeError("Cannot call a class as a function");
  33964. }
  33965. };
  33966. var createClass = function () {
  33967. function defineProperties(target, props) {
  33968. for (var i = 0; i < props.length; i++) {
  33969. var descriptor = props[i];
  33970. descriptor.enumerable = descriptor.enumerable || false;
  33971. descriptor.configurable = true;
  33972. if ("value" in descriptor) descriptor.writable = true;
  33973. Object.defineProperty(target, descriptor.key, descriptor);
  33974. }
  33975. }
  33976. return function (Constructor, protoProps, staticProps) {
  33977. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  33978. if (staticProps) defineProperties(Constructor, staticProps);
  33979. return Constructor;
  33980. };
  33981. }();
  33982. var get = function get(object, property, receiver) {
  33983. if (object === null) object = Function.prototype;
  33984. var desc = Object.getOwnPropertyDescriptor(object, property);
  33985. if (desc === undefined) {
  33986. var parent = Object.getPrototypeOf(object);
  33987. if (parent === null) {
  33988. return undefined;
  33989. } else {
  33990. return get(parent, property, receiver);
  33991. }
  33992. } else if ("value" in desc) {
  33993. return desc.value;
  33994. } else {
  33995. var getter = desc.get;
  33996. if (getter === undefined) {
  33997. return undefined;
  33998. }
  33999. return getter.call(receiver);
  34000. }
  34001. };
  34002. var inherits = function (subClass, superClass) {
  34003. if (typeof superClass !== "function" && superClass !== null) {
  34004. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  34005. }
  34006. subClass.prototype = Object.create(superClass && superClass.prototype, {
  34007. constructor: {
  34008. value: subClass,
  34009. enumerable: false,
  34010. writable: true,
  34011. configurable: true
  34012. }
  34013. });
  34014. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  34015. };
  34016. var possibleConstructorReturn = function (self, call) {
  34017. if (!self) {
  34018. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  34019. }
  34020. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  34021. };
  34022. var Color = function () {
  34023. function Color() {
  34024. classCallCheck(this, Color);
  34025. this.__state = interpret.apply(this, arguments);
  34026. if (this.__state === false) {
  34027. throw new Error('Failed to interpret color arguments');
  34028. }
  34029. this.__state.a = this.__state.a || 1;
  34030. }
  34031. createClass(Color, [{
  34032. key: 'toString',
  34033. value: function toString() {
  34034. return colorToString(this);
  34035. }
  34036. }, {
  34037. key: 'toHexString',
  34038. value: function toHexString() {
  34039. return colorToString(this, true);
  34040. }
  34041. }, {
  34042. key: 'toOriginal',
  34043. value: function toOriginal() {
  34044. return this.__state.conversion.write(this);
  34045. }
  34046. }]);
  34047. return Color;
  34048. }();
  34049. function defineRGBComponent(target, component, componentHexIndex) {
  34050. Object.defineProperty(target, component, {
  34051. get: function get$$1() {
  34052. if (this.__state.space === 'RGB') {
  34053. return this.__state[component];
  34054. }
  34055. Color.recalculateRGB(this, component, componentHexIndex);
  34056. return this.__state[component];
  34057. },
  34058. set: function set$$1(v) {
  34059. if (this.__state.space !== 'RGB') {
  34060. Color.recalculateRGB(this, component, componentHexIndex);
  34061. this.__state.space = 'RGB';
  34062. }
  34063. this.__state[component] = v;
  34064. }
  34065. });
  34066. }
  34067. function defineHSVComponent(target, component) {
  34068. Object.defineProperty(target, component, {
  34069. get: function get$$1() {
  34070. if (this.__state.space === 'HSV') {
  34071. return this.__state[component];
  34072. }
  34073. Color.recalculateHSV(this);
  34074. return this.__state[component];
  34075. },
  34076. set: function set$$1(v) {
  34077. if (this.__state.space !== 'HSV') {
  34078. Color.recalculateHSV(this);
  34079. this.__state.space = 'HSV';
  34080. }
  34081. this.__state[component] = v;
  34082. }
  34083. });
  34084. }
  34085. Color.recalculateRGB = function (color, component, componentHexIndex) {
  34086. if (color.__state.space === 'HEX') {
  34087. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  34088. } else if (color.__state.space === 'HSV') {
  34089. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  34090. } else {
  34091. throw new Error('Corrupted color state');
  34092. }
  34093. };
  34094. Color.recalculateHSV = function (color) {
  34095. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  34096. Common.extend(color.__state, {
  34097. s: result.s,
  34098. v: result.v
  34099. });
  34100. if (!Common.isNaN(result.h)) {
  34101. color.__state.h = result.h;
  34102. } else if (Common.isUndefined(color.__state.h)) {
  34103. color.__state.h = 0;
  34104. }
  34105. };
  34106. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  34107. defineRGBComponent(Color.prototype, 'r', 2);
  34108. defineRGBComponent(Color.prototype, 'g', 1);
  34109. defineRGBComponent(Color.prototype, 'b', 0);
  34110. defineHSVComponent(Color.prototype, 'h');
  34111. defineHSVComponent(Color.prototype, 's');
  34112. defineHSVComponent(Color.prototype, 'v');
  34113. Object.defineProperty(Color.prototype, 'a', {
  34114. get: function get$$1() {
  34115. return this.__state.a;
  34116. },
  34117. set: function set$$1(v) {
  34118. this.__state.a = v;
  34119. }
  34120. });
  34121. Object.defineProperty(Color.prototype, 'hex', {
  34122. get: function get$$1() {
  34123. if (!this.__state.space !== 'HEX') {
  34124. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  34125. }
  34126. return this.__state.hex;
  34127. },
  34128. set: function set$$1(v) {
  34129. this.__state.space = 'HEX';
  34130. this.__state.hex = v;
  34131. }
  34132. });
  34133. var Controller = function () {
  34134. function Controller(object, property) {
  34135. classCallCheck(this, Controller);
  34136. this.initialValue = object[property];
  34137. this.domElement = document.createElement('div');
  34138. this.object = object;
  34139. this.property = property;
  34140. this.__onChange = undefined;
  34141. this.__onFinishChange = undefined;
  34142. }
  34143. createClass(Controller, [{
  34144. key: 'onChange',
  34145. value: function onChange(fnc) {
  34146. this.__onChange = fnc;
  34147. return this;
  34148. }
  34149. }, {
  34150. key: 'onFinishChange',
  34151. value: function onFinishChange(fnc) {
  34152. this.__onFinishChange = fnc;
  34153. return this;
  34154. }
  34155. }, {
  34156. key: 'setValue',
  34157. value: function setValue(newValue) {
  34158. this.object[this.property] = newValue;
  34159. if (this.__onChange) {
  34160. this.__onChange.call(this, newValue);
  34161. }
  34162. this.updateDisplay();
  34163. return this;
  34164. }
  34165. }, {
  34166. key: 'getValue',
  34167. value: function getValue() {
  34168. return this.object[this.property];
  34169. }
  34170. }, {
  34171. key: 'updateDisplay',
  34172. value: function updateDisplay() {
  34173. return this;
  34174. }
  34175. }, {
  34176. key: 'isModified',
  34177. value: function isModified() {
  34178. return this.initialValue !== this.getValue();
  34179. }
  34180. }]);
  34181. return Controller;
  34182. }();
  34183. var EVENT_MAP = {
  34184. HTMLEvents: ['change'],
  34185. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  34186. KeyboardEvents: ['keydown']
  34187. };
  34188. var EVENT_MAP_INV = {};
  34189. Common.each(EVENT_MAP, function (v, k) {
  34190. Common.each(v, function (e) {
  34191. EVENT_MAP_INV[e] = k;
  34192. });
  34193. });
  34194. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  34195. function cssValueToPixels(val) {
  34196. if (val === '0' || Common.isUndefined(val)) {
  34197. return 0;
  34198. }
  34199. var match = val.match(CSS_VALUE_PIXELS);
  34200. if (!Common.isNull(match)) {
  34201. return parseFloat(match[1]);
  34202. }
  34203. return 0;
  34204. }
  34205. var dom = {
  34206. makeSelectable: function makeSelectable(elem, selectable) {
  34207. if (elem === undefined || elem.style === undefined) return;
  34208. elem.onselectstart = selectable ? function () {
  34209. return false;
  34210. } : function () {};
  34211. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  34212. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  34213. elem.unselectable = selectable ? 'on' : 'off';
  34214. },
  34215. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  34216. var vertical = vert;
  34217. var horizontal = hor;
  34218. if (Common.isUndefined(horizontal)) {
  34219. horizontal = true;
  34220. }
  34221. if (Common.isUndefined(vertical)) {
  34222. vertical = true;
  34223. }
  34224. elem.style.position = 'absolute';
  34225. if (horizontal) {
  34226. elem.style.left = 0;
  34227. elem.style.right = 0;
  34228. }
  34229. if (vertical) {
  34230. elem.style.top = 0;
  34231. elem.style.bottom = 0;
  34232. }
  34233. },
  34234. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  34235. var params = pars || {};
  34236. var className = EVENT_MAP_INV[eventType];
  34237. if (!className) {
  34238. throw new Error('Event type ' + eventType + ' not supported.');
  34239. }
  34240. var evt = document.createEvent(className);
  34241. switch (className) {
  34242. case 'MouseEvents':
  34243. {
  34244. var clientX = params.x || params.clientX || 0;
  34245. var clientY = params.y || params.clientY || 0;
  34246. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  34247. break;
  34248. }
  34249. case 'KeyboardEvents':
  34250. {
  34251. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  34252. Common.defaults(params, {
  34253. cancelable: true,
  34254. ctrlKey: false,
  34255. altKey: false,
  34256. shiftKey: false,
  34257. metaKey: false,
  34258. keyCode: undefined,
  34259. charCode: undefined
  34260. });
  34261. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  34262. break;
  34263. }
  34264. default:
  34265. {
  34266. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  34267. break;
  34268. }
  34269. }
  34270. Common.defaults(evt, aux);
  34271. elem.dispatchEvent(evt);
  34272. },
  34273. bind: function bind(elem, event, func, newBool) {
  34274. var bool = newBool || false;
  34275. if (elem.addEventListener) {
  34276. elem.addEventListener(event, func, bool);
  34277. } else if (elem.attachEvent) {
  34278. elem.attachEvent('on' + event, func);
  34279. }
  34280. return dom;
  34281. },
  34282. unbind: function unbind(elem, event, func, newBool) {
  34283. var bool = newBool || false;
  34284. if (elem.removeEventListener) {
  34285. elem.removeEventListener(event, func, bool);
  34286. } else if (elem.detachEvent) {
  34287. elem.detachEvent('on' + event, func);
  34288. }
  34289. return dom;
  34290. },
  34291. addClass: function addClass(elem, className) {
  34292. if (elem.className === undefined) {
  34293. elem.className = className;
  34294. } else if (elem.className !== className) {
  34295. var classes = elem.className.split(/ +/);
  34296. if (classes.indexOf(className) === -1) {
  34297. classes.push(className);
  34298. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  34299. }
  34300. }
  34301. return dom;
  34302. },
  34303. removeClass: function removeClass(elem, className) {
  34304. if (className) {
  34305. if (elem.className === className) {
  34306. elem.removeAttribute('class');
  34307. } else {
  34308. var classes = elem.className.split(/ +/);
  34309. var index = classes.indexOf(className);
  34310. if (index !== -1) {
  34311. classes.splice(index, 1);
  34312. elem.className = classes.join(' ');
  34313. }
  34314. }
  34315. } else {
  34316. elem.className = undefined;
  34317. }
  34318. return dom;
  34319. },
  34320. hasClass: function hasClass(elem, className) {
  34321. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  34322. },
  34323. getWidth: function getWidth(elem) {
  34324. var style = getComputedStyle(elem);
  34325. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  34326. },
  34327. getHeight: function getHeight(elem) {
  34328. var style = getComputedStyle(elem);
  34329. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  34330. },
  34331. getOffset: function getOffset(el) {
  34332. var elem = el;
  34333. var offset = {
  34334. left: 0,
  34335. top: 0
  34336. };
  34337. if (elem.offsetParent) {
  34338. do {
  34339. offset.left += elem.offsetLeft;
  34340. offset.top += elem.offsetTop;
  34341. elem = elem.offsetParent;
  34342. } while (elem);
  34343. }
  34344. return offset;
  34345. },
  34346. isActive: function isActive(elem) {
  34347. return elem === document.activeElement && (elem.type || elem.href);
  34348. }
  34349. };
  34350. var BooleanController = function (_Controller) {
  34351. inherits(BooleanController, _Controller);
  34352. function BooleanController(object, property) {
  34353. classCallCheck(this, BooleanController);
  34354. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  34355. var _this = _this2;
  34356. _this2.__prev = _this2.getValue();
  34357. _this2.__checkbox = document.createElement('input');
  34358. _this2.__checkbox.setAttribute('type', 'checkbox');
  34359. function onChange() {
  34360. _this.setValue(!_this.__prev);
  34361. }
  34362. dom.bind(_this2.__checkbox, 'change', onChange, false);
  34363. _this2.domElement.appendChild(_this2.__checkbox);
  34364. _this2.updateDisplay();
  34365. return _this2;
  34366. }
  34367. createClass(BooleanController, [{
  34368. key: 'setValue',
  34369. value: function setValue(v) {
  34370. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  34371. if (this.__onFinishChange) {
  34372. this.__onFinishChange.call(this, this.getValue());
  34373. }
  34374. this.__prev = this.getValue();
  34375. return toReturn;
  34376. }
  34377. }, {
  34378. key: 'updateDisplay',
  34379. value: function updateDisplay() {
  34380. if (this.getValue() === true) {
  34381. this.__checkbox.setAttribute('checked', 'checked');
  34382. this.__checkbox.checked = true;
  34383. this.__prev = true;
  34384. } else {
  34385. this.__checkbox.checked = false;
  34386. this.__prev = false;
  34387. }
  34388. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  34389. }
  34390. }]);
  34391. return BooleanController;
  34392. }(Controller);
  34393. var OptionController = function (_Controller) {
  34394. inherits(OptionController, _Controller);
  34395. function OptionController(object, property, opts) {
  34396. classCallCheck(this, OptionController);
  34397. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  34398. var options = opts;
  34399. var _this = _this2;
  34400. _this2.__select = document.createElement('select');
  34401. if (Common.isArray(options)) {
  34402. var map = {};
  34403. Common.each(options, function (element) {
  34404. map[element] = element;
  34405. });
  34406. options = map;
  34407. }
  34408. Common.each(options, function (value, key) {
  34409. var opt = document.createElement('option');
  34410. opt.innerHTML = key;
  34411. opt.setAttribute('value', value);
  34412. _this.__select.appendChild(opt);
  34413. });
  34414. _this2.updateDisplay();
  34415. dom.bind(_this2.__select, 'change', function () {
  34416. var desiredValue = this.options[this.selectedIndex].value;
  34417. _this.setValue(desiredValue);
  34418. });
  34419. _this2.domElement.appendChild(_this2.__select);
  34420. return _this2;
  34421. }
  34422. createClass(OptionController, [{
  34423. key: 'setValue',
  34424. value: function setValue(v) {
  34425. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  34426. if (this.__onFinishChange) {
  34427. this.__onFinishChange.call(this, this.getValue());
  34428. }
  34429. return toReturn;
  34430. }
  34431. }, {
  34432. key: 'updateDisplay',
  34433. value: function updateDisplay() {
  34434. if (dom.isActive(this.__select)) return this;
  34435. this.__select.value = this.getValue();
  34436. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  34437. }
  34438. }]);
  34439. return OptionController;
  34440. }(Controller);
  34441. var StringController = function (_Controller) {
  34442. inherits(StringController, _Controller);
  34443. function StringController(object, property) {
  34444. classCallCheck(this, StringController);
  34445. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  34446. var _this = _this2;
  34447. function onChange() {
  34448. _this.setValue(_this.__input.value);
  34449. }
  34450. function onBlur() {
  34451. if (_this.__onFinishChange) {
  34452. _this.__onFinishChange.call(_this, _this.getValue());
  34453. }
  34454. }
  34455. _this2.__input = document.createElement('input');
  34456. _this2.__input.setAttribute('type', 'text');
  34457. dom.bind(_this2.__input, 'keyup', onChange);
  34458. dom.bind(_this2.__input, 'change', onChange);
  34459. dom.bind(_this2.__input, 'blur', onBlur);
  34460. dom.bind(_this2.__input, 'keydown', function (e) {
  34461. if (e.keyCode === 13) {
  34462. this.blur();
  34463. }
  34464. });
  34465. _this2.updateDisplay();
  34466. _this2.domElement.appendChild(_this2.__input);
  34467. return _this2;
  34468. }
  34469. createClass(StringController, [{
  34470. key: 'updateDisplay',
  34471. value: function updateDisplay() {
  34472. if (!dom.isActive(this.__input)) {
  34473. this.__input.value = this.getValue();
  34474. }
  34475. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  34476. }
  34477. }]);
  34478. return StringController;
  34479. }(Controller);
  34480. function numDecimals(x) {
  34481. var _x = x.toString();
  34482. if (_x.indexOf('.') > -1) {
  34483. return _x.length - _x.indexOf('.') - 1;
  34484. }
  34485. return 0;
  34486. }
  34487. var NumberController = function (_Controller) {
  34488. inherits(NumberController, _Controller);
  34489. function NumberController(object, property, params) {
  34490. classCallCheck(this, NumberController);
  34491. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  34492. var _params = params || {};
  34493. _this.__min = _params.min;
  34494. _this.__max = _params.max;
  34495. _this.__step = _params.step;
  34496. if (Common.isUndefined(_this.__step)) {
  34497. if (_this.initialValue === 0) {
  34498. _this.__impliedStep = 1;
  34499. } else {
  34500. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  34501. }
  34502. } else {
  34503. _this.__impliedStep = _this.__step;
  34504. }
  34505. _this.__precision = numDecimals(_this.__impliedStep);
  34506. return _this;
  34507. }
  34508. createClass(NumberController, [{
  34509. key: 'setValue',
  34510. value: function setValue(v) {
  34511. var _v = v;
  34512. if (this.__min !== undefined && _v < this.__min) {
  34513. _v = this.__min;
  34514. } else if (this.__max !== undefined && _v > this.__max) {
  34515. _v = this.__max;
  34516. }
  34517. if (this.__step !== undefined && _v % this.__step !== 0) {
  34518. _v = Math.round(_v / this.__step) * this.__step;
  34519. }
  34520. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  34521. }
  34522. }, {
  34523. key: 'min',
  34524. value: function min(minValue) {
  34525. this.__min = minValue;
  34526. return this;
  34527. }
  34528. }, {
  34529. key: 'max',
  34530. value: function max(maxValue) {
  34531. this.__max = maxValue;
  34532. return this;
  34533. }
  34534. }, {
  34535. key: 'step',
  34536. value: function step(stepValue) {
  34537. this.__step = stepValue;
  34538. this.__impliedStep = stepValue;
  34539. this.__precision = numDecimals(stepValue);
  34540. return this;
  34541. }
  34542. }]);
  34543. return NumberController;
  34544. }(Controller);
  34545. function roundToDecimal(value, decimals) {
  34546. var tenTo = Math.pow(10, decimals);
  34547. return Math.round(value * tenTo) / tenTo;
  34548. }
  34549. var NumberControllerBox = function (_NumberController) {
  34550. inherits(NumberControllerBox, _NumberController);
  34551. function NumberControllerBox(object, property, params) {
  34552. classCallCheck(this, NumberControllerBox);
  34553. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  34554. _this2.__truncationSuspended = false;
  34555. var _this = _this2;
  34556. var prevY = void 0;
  34557. function onChange() {
  34558. var attempted = parseFloat(_this.__input.value);
  34559. if (!Common.isNaN(attempted)) {
  34560. _this.setValue(attempted);
  34561. }
  34562. }
  34563. function onFinish() {
  34564. if (_this.__onFinishChange) {
  34565. _this.__onFinishChange.call(_this, _this.getValue());
  34566. }
  34567. }
  34568. function onBlur() {
  34569. onFinish();
  34570. }
  34571. function onMouseDrag(e) {
  34572. var diff = prevY - e.clientY;
  34573. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  34574. prevY = e.clientY;
  34575. }
  34576. function onMouseUp() {
  34577. dom.unbind(window, 'mousemove', onMouseDrag);
  34578. dom.unbind(window, 'mouseup', onMouseUp);
  34579. onFinish();
  34580. }
  34581. function onMouseDown(e) {
  34582. dom.bind(window, 'mousemove', onMouseDrag);
  34583. dom.bind(window, 'mouseup', onMouseUp);
  34584. prevY = e.clientY;
  34585. }
  34586. _this2.__input = document.createElement('input');
  34587. _this2.__input.setAttribute('type', 'text');
  34588. dom.bind(_this2.__input, 'change', onChange);
  34589. dom.bind(_this2.__input, 'blur', onBlur);
  34590. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  34591. dom.bind(_this2.__input, 'keydown', function (e) {
  34592. if (e.keyCode === 13) {
  34593. _this.__truncationSuspended = true;
  34594. this.blur();
  34595. _this.__truncationSuspended = false;
  34596. onFinish();
  34597. }
  34598. });
  34599. _this2.updateDisplay();
  34600. _this2.domElement.appendChild(_this2.__input);
  34601. return _this2;
  34602. }
  34603. createClass(NumberControllerBox, [{
  34604. key: 'updateDisplay',
  34605. value: function updateDisplay() {
  34606. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  34607. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  34608. }
  34609. }]);
  34610. return NumberControllerBox;
  34611. }(NumberController);
  34612. function map(v, i1, i2, o1, o2) {
  34613. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  34614. }
  34615. var NumberControllerSlider = function (_NumberController) {
  34616. inherits(NumberControllerSlider, _NumberController);
  34617. function NumberControllerSlider(object, property, min, max, step) {
  34618. classCallCheck(this, NumberControllerSlider);
  34619. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  34620. min: min,
  34621. max: max,
  34622. step: step
  34623. }));
  34624. var _this = _this2;
  34625. _this2.__background = document.createElement('div');
  34626. _this2.__foreground = document.createElement('div');
  34627. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  34628. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  34629. dom.addClass(_this2.__background, 'slider');
  34630. dom.addClass(_this2.__foreground, 'slider-fg');
  34631. function onMouseDown(e) {
  34632. document.activeElement.blur();
  34633. dom.bind(window, 'mousemove', onMouseDrag);
  34634. dom.bind(window, 'mouseup', onMouseUp);
  34635. onMouseDrag(e);
  34636. }
  34637. function onMouseDrag(e) {
  34638. e.preventDefault();
  34639. var bgRect = _this.__background.getBoundingClientRect();
  34640. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34641. return false;
  34642. }
  34643. function onMouseUp() {
  34644. dom.unbind(window, 'mousemove', onMouseDrag);
  34645. dom.unbind(window, 'mouseup', onMouseUp);
  34646. if (_this.__onFinishChange) {
  34647. _this.__onFinishChange.call(_this, _this.getValue());
  34648. }
  34649. }
  34650. function onTouchStart(e) {
  34651. if (e.touches.length !== 1) {
  34652. return;
  34653. }
  34654. dom.bind(window, 'touchmove', onTouchMove);
  34655. dom.bind(window, 'touchend', onTouchEnd);
  34656. onTouchMove(e);
  34657. }
  34658. function onTouchMove(e) {
  34659. var clientX = e.touches[0].clientX;
  34660. var bgRect = _this.__background.getBoundingClientRect();
  34661. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34662. }
  34663. function onTouchEnd() {
  34664. dom.unbind(window, 'touchmove', onTouchMove);
  34665. dom.unbind(window, 'touchend', onTouchEnd);
  34666. if (_this.__onFinishChange) {
  34667. _this.__onFinishChange.call(_this, _this.getValue());
  34668. }
  34669. }
  34670. _this2.updateDisplay();
  34671. _this2.__background.appendChild(_this2.__foreground);
  34672. _this2.domElement.appendChild(_this2.__background);
  34673. return _this2;
  34674. }
  34675. createClass(NumberControllerSlider, [{
  34676. key: 'updateDisplay',
  34677. value: function updateDisplay() {
  34678. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  34679. this.__foreground.style.width = pct * 100 + '%';
  34680. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  34681. }
  34682. }]);
  34683. return NumberControllerSlider;
  34684. }(NumberController);
  34685. var FunctionController = function (_Controller) {
  34686. inherits(FunctionController, _Controller);
  34687. function FunctionController(object, property, text) {
  34688. classCallCheck(this, FunctionController);
  34689. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  34690. var _this = _this2;
  34691. _this2.__button = document.createElement('div');
  34692. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  34693. dom.bind(_this2.__button, 'click', function (e) {
  34694. e.preventDefault();
  34695. _this.fire();
  34696. return false;
  34697. });
  34698. dom.addClass(_this2.__button, 'button');
  34699. _this2.domElement.appendChild(_this2.__button);
  34700. return _this2;
  34701. }
  34702. createClass(FunctionController, [{
  34703. key: 'fire',
  34704. value: function fire() {
  34705. if (this.__onChange) {
  34706. this.__onChange.call(this);
  34707. }
  34708. this.getValue().call(this.object);
  34709. if (this.__onFinishChange) {
  34710. this.__onFinishChange.call(this, this.getValue());
  34711. }
  34712. }
  34713. }]);
  34714. return FunctionController;
  34715. }(Controller);
  34716. var ColorController = function (_Controller) {
  34717. inherits(ColorController, _Controller);
  34718. function ColorController(object, property) {
  34719. classCallCheck(this, ColorController);
  34720. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  34721. _this2.__color = new Color(_this2.getValue());
  34722. _this2.__temp = new Color(0);
  34723. var _this = _this2;
  34724. _this2.domElement = document.createElement('div');
  34725. dom.makeSelectable(_this2.domElement, false);
  34726. _this2.__selector = document.createElement('div');
  34727. _this2.__selector.className = 'selector';
  34728. _this2.__saturation_field = document.createElement('div');
  34729. _this2.__saturation_field.className = 'saturation-field';
  34730. _this2.__field_knob = document.createElement('div');
  34731. _this2.__field_knob.className = 'field-knob';
  34732. _this2.__field_knob_border = '2px solid ';
  34733. _this2.__hue_knob = document.createElement('div');
  34734. _this2.__hue_knob.className = 'hue-knob';
  34735. _this2.__hue_field = document.createElement('div');
  34736. _this2.__hue_field.className = 'hue-field';
  34737. _this2.__input = document.createElement('input');
  34738. _this2.__input.type = 'text';
  34739. _this2.__input_textShadow = '0 1px 1px ';
  34740. dom.bind(_this2.__input, 'keydown', function (e) {
  34741. if (e.keyCode === 13) {
  34742. onBlur.call(this);
  34743. }
  34744. });
  34745. dom.bind(_this2.__input, 'blur', onBlur);
  34746. dom.bind(_this2.__selector, 'mousedown', function () {
  34747. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  34748. dom.removeClass(_this.__selector, 'drag');
  34749. });
  34750. });
  34751. dom.bind(_this2.__selector, 'touchstart', function () {
  34752. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  34753. dom.removeClass(_this.__selector, 'drag');
  34754. });
  34755. });
  34756. var valueField = document.createElement('div');
  34757. Common.extend(_this2.__selector.style, {
  34758. width: '122px',
  34759. height: '102px',
  34760. padding: '3px',
  34761. backgroundColor: '#222',
  34762. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  34763. });
  34764. Common.extend(_this2.__field_knob.style, {
  34765. position: 'absolute',
  34766. width: '12px',
  34767. height: '12px',
  34768. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  34769. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  34770. borderRadius: '12px',
  34771. zIndex: 1
  34772. });
  34773. Common.extend(_this2.__hue_knob.style, {
  34774. position: 'absolute',
  34775. width: '15px',
  34776. height: '2px',
  34777. borderRight: '4px solid #fff',
  34778. zIndex: 1
  34779. });
  34780. Common.extend(_this2.__saturation_field.style, {
  34781. width: '100px',
  34782. height: '100px',
  34783. border: '1px solid #555',
  34784. marginRight: '3px',
  34785. display: 'inline-block',
  34786. cursor: 'pointer'
  34787. });
  34788. Common.extend(valueField.style, {
  34789. width: '100%',
  34790. height: '100%',
  34791. background: 'none'
  34792. });
  34793. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  34794. Common.extend(_this2.__hue_field.style, {
  34795. width: '15px',
  34796. height: '100px',
  34797. border: '1px solid #555',
  34798. cursor: 'ns-resize',
  34799. position: 'absolute',
  34800. top: '3px',
  34801. right: '3px'
  34802. });
  34803. hueGradient(_this2.__hue_field);
  34804. Common.extend(_this2.__input.style, {
  34805. outline: 'none',
  34806. textAlign: 'center',
  34807. color: '#fff',
  34808. border: 0,
  34809. fontWeight: 'bold',
  34810. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  34811. });
  34812. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  34813. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  34814. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  34815. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  34816. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  34817. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  34818. function fieldDown(e) {
  34819. setSV(e);
  34820. dom.bind(window, 'mousemove', setSV);
  34821. dom.bind(window, 'touchmove', setSV);
  34822. dom.bind(window, 'mouseup', fieldUpSV);
  34823. dom.bind(window, 'touchend', fieldUpSV);
  34824. }
  34825. function fieldDownH(e) {
  34826. setH(e);
  34827. dom.bind(window, 'mousemove', setH);
  34828. dom.bind(window, 'touchmove', setH);
  34829. dom.bind(window, 'mouseup', fieldUpH);
  34830. dom.bind(window, 'touchend', fieldUpH);
  34831. }
  34832. function fieldUpSV() {
  34833. dom.unbind(window, 'mousemove', setSV);
  34834. dom.unbind(window, 'touchmove', setSV);
  34835. dom.unbind(window, 'mouseup', fieldUpSV);
  34836. dom.unbind(window, 'touchend', fieldUpSV);
  34837. onFinish();
  34838. }
  34839. function fieldUpH() {
  34840. dom.unbind(window, 'mousemove', setH);
  34841. dom.unbind(window, 'touchmove', setH);
  34842. dom.unbind(window, 'mouseup', fieldUpH);
  34843. dom.unbind(window, 'touchend', fieldUpH);
  34844. onFinish();
  34845. }
  34846. function onBlur() {
  34847. var i = interpret(this.value);
  34848. if (i !== false) {
  34849. _this.__color.__state = i;
  34850. _this.setValue(_this.__color.toOriginal());
  34851. } else {
  34852. this.value = _this.__color.toString();
  34853. }
  34854. }
  34855. function onFinish() {
  34856. if (_this.__onFinishChange) {
  34857. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  34858. }
  34859. }
  34860. _this2.__saturation_field.appendChild(valueField);
  34861. _this2.__selector.appendChild(_this2.__field_knob);
  34862. _this2.__selector.appendChild(_this2.__saturation_field);
  34863. _this2.__selector.appendChild(_this2.__hue_field);
  34864. _this2.__hue_field.appendChild(_this2.__hue_knob);
  34865. _this2.domElement.appendChild(_this2.__input);
  34866. _this2.domElement.appendChild(_this2.__selector);
  34867. _this2.updateDisplay();
  34868. function setSV(e) {
  34869. if (e.type.indexOf('touch') === -1) {
  34870. e.preventDefault();
  34871. }
  34872. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  34873. var _ref = e.touches && e.touches[0] || e,
  34874. clientX = _ref.clientX,
  34875. clientY = _ref.clientY;
  34876. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  34877. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34878. if (v > 1) {
  34879. v = 1;
  34880. } else if (v < 0) {
  34881. v = 0;
  34882. }
  34883. if (s > 1) {
  34884. s = 1;
  34885. } else if (s < 0) {
  34886. s = 0;
  34887. }
  34888. _this.__color.v = v;
  34889. _this.__color.s = s;
  34890. _this.setValue(_this.__color.toOriginal());
  34891. return false;
  34892. }
  34893. function setH(e) {
  34894. if (e.type.indexOf('touch') === -1) {
  34895. e.preventDefault();
  34896. }
  34897. var fieldRect = _this.__hue_field.getBoundingClientRect();
  34898. var _ref2 = e.touches && e.touches[0] || e,
  34899. clientY = _ref2.clientY;
  34900. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34901. if (h > 1) {
  34902. h = 1;
  34903. } else if (h < 0) {
  34904. h = 0;
  34905. }
  34906. _this.__color.h = h * 360;
  34907. _this.setValue(_this.__color.toOriginal());
  34908. return false;
  34909. }
  34910. return _this2;
  34911. }
  34912. createClass(ColorController, [{
  34913. key: 'updateDisplay',
  34914. value: function updateDisplay() {
  34915. var i = interpret(this.getValue());
  34916. if (i !== false) {
  34917. var mismatch = false;
  34918. Common.each(Color.COMPONENTS, function (component) {
  34919. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  34920. mismatch = true;
  34921. return {};
  34922. }
  34923. }, this);
  34924. if (mismatch) {
  34925. Common.extend(this.__color.__state, i);
  34926. }
  34927. }
  34928. Common.extend(this.__temp.__state, this.__color.__state);
  34929. this.__temp.a = 1;
  34930. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  34931. var _flip = 255 - flip;
  34932. Common.extend(this.__field_knob.style, {
  34933. marginLeft: 100 * this.__color.s - 7 + 'px',
  34934. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  34935. backgroundColor: this.__temp.toHexString(),
  34936. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  34937. });
  34938. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  34939. this.__temp.s = 1;
  34940. this.__temp.v = 1;
  34941. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  34942. this.__input.value = this.__color.toString();
  34943. Common.extend(this.__input.style, {
  34944. backgroundColor: this.__color.toHexString(),
  34945. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  34946. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  34947. });
  34948. }
  34949. }]);
  34950. return ColorController;
  34951. }(Controller);
  34952. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  34953. function linearGradient(elem, x, a, b) {
  34954. elem.style.background = '';
  34955. Common.each(vendors, function (vendor) {
  34956. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  34957. });
  34958. }
  34959. function hueGradient(elem) {
  34960. elem.style.background = '';
  34961. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  34962. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34963. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34964. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34965. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34966. }
  34967. var css = {
  34968. load: function load(url, indoc) {
  34969. var doc = indoc || document;
  34970. var link = doc.createElement('link');
  34971. link.type = 'text/css';
  34972. link.rel = 'stylesheet';
  34973. link.href = url;
  34974. doc.getElementsByTagName('head')[0].appendChild(link);
  34975. },
  34976. inject: function inject(cssContent, indoc) {
  34977. var doc = indoc || document;
  34978. var injected = document.createElement('style');
  34979. injected.type = 'text/css';
  34980. injected.innerHTML = cssContent;
  34981. var head = doc.getElementsByTagName('head')[0];
  34982. try {
  34983. head.appendChild(injected);
  34984. } catch (e) {}
  34985. }
  34986. };
  34987. 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>";
  34988. var ControllerFactory = function ControllerFactory(object, property) {
  34989. var initialValue = object[property];
  34990. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  34991. return new OptionController(object, property, arguments[2]);
  34992. }
  34993. if (Common.isNumber(initialValue)) {
  34994. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  34995. if (Common.isNumber(arguments[4])) {
  34996. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  34997. }
  34998. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  34999. }
  35000. if (Common.isNumber(arguments[4])) {
  35001. return new NumberControllerBox(object, property, {
  35002. min: arguments[2],
  35003. max: arguments[3],
  35004. step: arguments[4]
  35005. });
  35006. }
  35007. return new NumberControllerBox(object, property, {
  35008. min: arguments[2],
  35009. max: arguments[3]
  35010. });
  35011. }
  35012. if (Common.isString(initialValue)) {
  35013. return new StringController(object, property);
  35014. }
  35015. if (Common.isFunction(initialValue)) {
  35016. return new FunctionController(object, property, '');
  35017. }
  35018. if (Common.isBoolean(initialValue)) {
  35019. return new BooleanController(object, property);
  35020. }
  35021. return null;
  35022. };
  35023. function requestAnimationFrame(callback) {
  35024. setTimeout(callback, 1000 / 60);
  35025. }
  35026. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  35027. var CenteredDiv = function () {
  35028. function CenteredDiv() {
  35029. classCallCheck(this, CenteredDiv);
  35030. this.backgroundElement = document.createElement('div');
  35031. Common.extend(this.backgroundElement.style, {
  35032. backgroundColor: 'rgba(0,0,0,0.8)',
  35033. top: 0,
  35034. left: 0,
  35035. display: 'none',
  35036. zIndex: '1000',
  35037. opacity: 0,
  35038. WebkitTransition: 'opacity 0.2s linear',
  35039. transition: 'opacity 0.2s linear'
  35040. });
  35041. dom.makeFullscreen(this.backgroundElement);
  35042. this.backgroundElement.style.position = 'fixed';
  35043. this.domElement = document.createElement('div');
  35044. Common.extend(this.domElement.style, {
  35045. position: 'fixed',
  35046. display: 'none',
  35047. zIndex: '1001',
  35048. opacity: 0,
  35049. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  35050. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  35051. });
  35052. document.body.appendChild(this.backgroundElement);
  35053. document.body.appendChild(this.domElement);
  35054. var _this = this;
  35055. dom.bind(this.backgroundElement, 'click', function () {
  35056. _this.hide();
  35057. });
  35058. }
  35059. createClass(CenteredDiv, [{
  35060. key: 'show',
  35061. value: function show() {
  35062. var _this = this;
  35063. this.backgroundElement.style.display = 'block';
  35064. this.domElement.style.display = 'block';
  35065. this.domElement.style.opacity = 0;
  35066. this.domElement.style.webkitTransform = 'scale(1.1)';
  35067. this.layout();
  35068. Common.defer(function () {
  35069. _this.backgroundElement.style.opacity = 1;
  35070. _this.domElement.style.opacity = 1;
  35071. _this.domElement.style.webkitTransform = 'scale(1)';
  35072. });
  35073. }
  35074. }, {
  35075. key: 'hide',
  35076. value: function hide() {
  35077. var _this = this;
  35078. var hide = function hide() {
  35079. _this.domElement.style.display = 'none';
  35080. _this.backgroundElement.style.display = 'none';
  35081. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  35082. dom.unbind(_this.domElement, 'transitionend', hide);
  35083. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  35084. };
  35085. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  35086. dom.bind(this.domElement, 'transitionend', hide);
  35087. dom.bind(this.domElement, 'oTransitionEnd', hide);
  35088. this.backgroundElement.style.opacity = 0;
  35089. this.domElement.style.opacity = 0;
  35090. this.domElement.style.webkitTransform = 'scale(1.1)';
  35091. }
  35092. }, {
  35093. key: 'layout',
  35094. value: function layout() {
  35095. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  35096. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  35097. }
  35098. }]);
  35099. return CenteredDiv;
  35100. }();
  35101. 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");
  35102. css.inject(styleSheet);
  35103. var CSS_NAMESPACE = 'dg';
  35104. var HIDE_KEY_CODE = 72;
  35105. var CLOSE_BUTTON_HEIGHT = 20;
  35106. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  35107. var SUPPORTS_LOCAL_STORAGE = function () {
  35108. try {
  35109. return !!window.localStorage;
  35110. } catch (e) {
  35111. return false;
  35112. }
  35113. }();
  35114. var SAVE_DIALOGUE = void 0;
  35115. var autoPlaceVirgin = true;
  35116. var autoPlaceContainer = void 0;
  35117. var hide = false;
  35118. var hideableGuis = [];
  35119. var GUI = function GUI(pars) {
  35120. var _this = this;
  35121. var params = pars || {};
  35122. this.domElement = document.createElement('div');
  35123. this.__ul = document.createElement('ul');
  35124. this.domElement.appendChild(this.__ul);
  35125. dom.addClass(this.domElement, CSS_NAMESPACE);
  35126. this.__folders = {};
  35127. this.__controllers = [];
  35128. this.__rememberedObjects = [];
  35129. this.__rememberedObjectIndecesToControllers = [];
  35130. this.__listening = [];
  35131. params = Common.defaults(params, {
  35132. closeOnTop: false,
  35133. autoPlace: true,
  35134. width: GUI.DEFAULT_WIDTH
  35135. });
  35136. params = Common.defaults(params, {
  35137. resizable: params.autoPlace,
  35138. hideable: params.autoPlace
  35139. });
  35140. if (!Common.isUndefined(params.load)) {
  35141. if (params.preset) {
  35142. params.load.preset = params.preset;
  35143. }
  35144. } else {
  35145. params.load = {
  35146. preset: DEFAULT_DEFAULT_PRESET_NAME
  35147. };
  35148. }
  35149. if (Common.isUndefined(params.parent) && params.hideable) {
  35150. hideableGuis.push(this);
  35151. }
  35152. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  35153. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  35154. params.scrollable = true;
  35155. }
  35156. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  35157. var saveToLocalStorage = void 0;
  35158. var titleRow = void 0;
  35159. Object.defineProperties(this, {
  35160. parent: {
  35161. get: function get$$1() {
  35162. return params.parent;
  35163. }
  35164. },
  35165. scrollable: {
  35166. get: function get$$1() {
  35167. return params.scrollable;
  35168. }
  35169. },
  35170. autoPlace: {
  35171. get: function get$$1() {
  35172. return params.autoPlace;
  35173. }
  35174. },
  35175. closeOnTop: {
  35176. get: function get$$1() {
  35177. return params.closeOnTop;
  35178. }
  35179. },
  35180. preset: {
  35181. get: function get$$1() {
  35182. if (_this.parent) {
  35183. return _this.getRoot().preset;
  35184. }
  35185. return params.load.preset;
  35186. },
  35187. set: function set$$1(v) {
  35188. if (_this.parent) {
  35189. _this.getRoot().preset = v;
  35190. } else {
  35191. params.load.preset = v;
  35192. }
  35193. setPresetSelectIndex(this);
  35194. _this.revert();
  35195. }
  35196. },
  35197. width: {
  35198. get: function get$$1() {
  35199. return params.width;
  35200. },
  35201. set: function set$$1(v) {
  35202. params.width = v;
  35203. setWidth(_this, v);
  35204. }
  35205. },
  35206. name: {
  35207. get: function get$$1() {
  35208. return params.name;
  35209. },
  35210. set: function set$$1(v) {
  35211. params.name = v;
  35212. if (titleRow) {
  35213. titleRow.innerHTML = params.name;
  35214. }
  35215. }
  35216. },
  35217. closed: {
  35218. get: function get$$1() {
  35219. return params.closed;
  35220. },
  35221. set: function set$$1(v) {
  35222. params.closed = v;
  35223. if (params.closed) {
  35224. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  35225. } else {
  35226. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  35227. }
  35228. this.onResize();
  35229. if (_this.__closeButton) {
  35230. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  35231. }
  35232. }
  35233. },
  35234. load: {
  35235. get: function get$$1() {
  35236. return params.load;
  35237. }
  35238. },
  35239. useLocalStorage: {
  35240. get: function get$$1() {
  35241. return useLocalStorage;
  35242. },
  35243. set: function set$$1(bool) {
  35244. if (SUPPORTS_LOCAL_STORAGE) {
  35245. useLocalStorage = bool;
  35246. if (bool) {
  35247. dom.bind(window, 'unload', saveToLocalStorage);
  35248. } else {
  35249. dom.unbind(window, 'unload', saveToLocalStorage);
  35250. }
  35251. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  35252. }
  35253. }
  35254. }
  35255. });
  35256. if (Common.isUndefined(params.parent)) {
  35257. this.closed = params.closed || false;
  35258. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  35259. dom.makeSelectable(this.domElement, false);
  35260. if (SUPPORTS_LOCAL_STORAGE) {
  35261. if (useLocalStorage) {
  35262. _this.useLocalStorage = true;
  35263. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  35264. if (savedGui) {
  35265. params.load = JSON.parse(savedGui);
  35266. }
  35267. }
  35268. }
  35269. this.__closeButton = document.createElement('div');
  35270. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  35271. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  35272. if (params.closeOnTop) {
  35273. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  35274. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  35275. } else {
  35276. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  35277. this.domElement.appendChild(this.__closeButton);
  35278. }
  35279. dom.bind(this.__closeButton, 'click', function () {
  35280. _this.closed = !_this.closed;
  35281. });
  35282. } else {
  35283. if (params.closed === undefined) {
  35284. params.closed = true;
  35285. }
  35286. var titleRowName = document.createTextNode(params.name);
  35287. dom.addClass(titleRowName, 'controller-name');
  35288. titleRow = addRow(_this, titleRowName);
  35289. var onClickTitle = function onClickTitle(e) {
  35290. e.preventDefault();
  35291. _this.closed = !_this.closed;
  35292. return false;
  35293. };
  35294. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  35295. dom.addClass(titleRow, 'title');
  35296. dom.bind(titleRow, 'click', onClickTitle);
  35297. if (!params.closed) {
  35298. this.closed = false;
  35299. }
  35300. }
  35301. if (params.autoPlace) {
  35302. if (Common.isUndefined(params.parent)) {
  35303. if (autoPlaceVirgin) {
  35304. autoPlaceContainer = document.createElement('div');
  35305. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  35306. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  35307. document.body.appendChild(autoPlaceContainer);
  35308. autoPlaceVirgin = false;
  35309. }
  35310. autoPlaceContainer.appendChild(this.domElement);
  35311. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  35312. }
  35313. if (!this.parent) {
  35314. setWidth(_this, params.width);
  35315. }
  35316. }
  35317. this.__resizeHandler = function () {
  35318. _this.onResizeDebounced();
  35319. };
  35320. dom.bind(window, 'resize', this.__resizeHandler);
  35321. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  35322. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  35323. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  35324. this.onResize();
  35325. if (params.resizable) {
  35326. addResizeHandle(this);
  35327. }
  35328. saveToLocalStorage = function saveToLocalStorage() {
  35329. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  35330. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  35331. }
  35332. };
  35333. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  35334. function resetWidth() {
  35335. var root = _this.getRoot();
  35336. root.width += 1;
  35337. Common.defer(function () {
  35338. root.width -= 1;
  35339. });
  35340. }
  35341. if (!params.parent) {
  35342. resetWidth();
  35343. }
  35344. };
  35345. GUI.toggleHide = function () {
  35346. hide = !hide;
  35347. Common.each(hideableGuis, function (gui) {
  35348. gui.domElement.style.display = hide ? 'none' : '';
  35349. });
  35350. };
  35351. GUI.CLASS_AUTO_PLACE = 'a';
  35352. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  35353. GUI.CLASS_MAIN = 'main';
  35354. GUI.CLASS_CONTROLLER_ROW = 'cr';
  35355. GUI.CLASS_TOO_TALL = 'taller-than-window';
  35356. GUI.CLASS_CLOSED = 'closed';
  35357. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  35358. GUI.CLASS_CLOSE_TOP = 'close-top';
  35359. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  35360. GUI.CLASS_DRAG = 'drag';
  35361. GUI.DEFAULT_WIDTH = 245;
  35362. GUI.TEXT_CLOSED = 'Close Controls';
  35363. GUI.TEXT_OPEN = 'Open Controls';
  35364. GUI._keydownHandler = function (e) {
  35365. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  35366. GUI.toggleHide();
  35367. }
  35368. };
  35369. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  35370. Common.extend(GUI.prototype, {
  35371. add: function add(object, property) {
  35372. return _add(this, object, property, {
  35373. factoryArgs: Array.prototype.slice.call(arguments, 2)
  35374. });
  35375. },
  35376. addColor: function addColor(object, property) {
  35377. return _add(this, object, property, {
  35378. color: true
  35379. });
  35380. },
  35381. remove: function remove(controller) {
  35382. this.__ul.removeChild(controller.__li);
  35383. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  35384. var _this = this;
  35385. Common.defer(function () {
  35386. _this.onResize();
  35387. });
  35388. },
  35389. destroy: function destroy() {
  35390. if (this.parent) {
  35391. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  35392. }
  35393. if (this.autoPlace) {
  35394. autoPlaceContainer.removeChild(this.domElement);
  35395. }
  35396. var _this = this;
  35397. Common.each(this.__folders, function (subfolder) {
  35398. _this.removeFolder(subfolder);
  35399. });
  35400. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  35401. removeListeners(this);
  35402. },
  35403. addFolder: function addFolder(name) {
  35404. if (this.__folders[name] !== undefined) {
  35405. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  35406. }
  35407. var newGuiParams = {
  35408. name: name,
  35409. parent: this
  35410. };
  35411. newGuiParams.autoPlace = this.autoPlace;
  35412. if (this.load && this.load.folders && this.load.folders[name]) {
  35413. newGuiParams.closed = this.load.folders[name].closed;
  35414. newGuiParams.load = this.load.folders[name];
  35415. }
  35416. var gui = new GUI(newGuiParams);
  35417. this.__folders[name] = gui;
  35418. var li = addRow(this, gui.domElement);
  35419. dom.addClass(li, 'folder');
  35420. return gui;
  35421. },
  35422. removeFolder: function removeFolder(folder) {
  35423. this.__ul.removeChild(folder.domElement.parentElement);
  35424. delete this.__folders[folder.name];
  35425. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  35426. delete this.load.folders[folder.name];
  35427. }
  35428. removeListeners(folder);
  35429. var _this = this;
  35430. Common.each(folder.__folders, function (subfolder) {
  35431. folder.removeFolder(subfolder);
  35432. });
  35433. Common.defer(function () {
  35434. _this.onResize();
  35435. });
  35436. },
  35437. open: function open() {
  35438. this.closed = false;
  35439. },
  35440. close: function close() {
  35441. this.closed = true;
  35442. },
  35443. hide: function hide() {
  35444. this.domElement.style.display = 'none';
  35445. },
  35446. show: function show() {
  35447. this.domElement.style.display = '';
  35448. },
  35449. onResize: function onResize() {
  35450. var root = this.getRoot();
  35451. if (root.scrollable) {
  35452. var top = dom.getOffset(root.__ul).top;
  35453. var h = 0;
  35454. Common.each(root.__ul.childNodes, function (node) {
  35455. if (!(root.autoPlace && node === root.__save_row)) {
  35456. h += dom.getHeight(node);
  35457. }
  35458. });
  35459. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  35460. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  35461. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  35462. } else {
  35463. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  35464. root.__ul.style.height = 'auto';
  35465. }
  35466. }
  35467. if (root.__resize_handle) {
  35468. Common.defer(function () {
  35469. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  35470. });
  35471. }
  35472. if (root.__closeButton) {
  35473. root.__closeButton.style.width = root.width + 'px';
  35474. }
  35475. },
  35476. onResizeDebounced: Common.debounce(function () {
  35477. this.onResize();
  35478. }, 50),
  35479. remember: function remember() {
  35480. if (Common.isUndefined(SAVE_DIALOGUE)) {
  35481. SAVE_DIALOGUE = new CenteredDiv();
  35482. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  35483. }
  35484. if (this.parent) {
  35485. throw new Error('You can only call remember on a top level GUI.');
  35486. }
  35487. var _this = this;
  35488. Common.each(Array.prototype.slice.call(arguments), function (object) {
  35489. if (_this.__rememberedObjects.length === 0) {
  35490. addSaveMenu(_this);
  35491. }
  35492. if (_this.__rememberedObjects.indexOf(object) === -1) {
  35493. _this.__rememberedObjects.push(object);
  35494. }
  35495. });
  35496. if (this.autoPlace) {
  35497. setWidth(this, this.width);
  35498. }
  35499. },
  35500. getRoot: function getRoot() {
  35501. var gui = this;
  35502. while (gui.parent) {
  35503. gui = gui.parent;
  35504. }
  35505. return gui;
  35506. },
  35507. getSaveObject: function getSaveObject() {
  35508. var toReturn = this.load;
  35509. toReturn.closed = this.closed;
  35510. if (this.__rememberedObjects.length > 0) {
  35511. toReturn.preset = this.preset;
  35512. if (!toReturn.remembered) {
  35513. toReturn.remembered = {};
  35514. }
  35515. toReturn.remembered[this.preset] = getCurrentPreset(this);
  35516. }
  35517. toReturn.folders = {};
  35518. Common.each(this.__folders, function (element, key) {
  35519. toReturn.folders[key] = element.getSaveObject();
  35520. });
  35521. return toReturn;
  35522. },
  35523. save: function save() {
  35524. if (!this.load.remembered) {
  35525. this.load.remembered = {};
  35526. }
  35527. this.load.remembered[this.preset] = getCurrentPreset(this);
  35528. markPresetModified(this, false);
  35529. this.saveToLocalStorageIfPossible();
  35530. },
  35531. saveAs: function saveAs(presetName) {
  35532. if (!this.load.remembered) {
  35533. this.load.remembered = {};
  35534. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  35535. }
  35536. this.load.remembered[presetName] = getCurrentPreset(this);
  35537. this.preset = presetName;
  35538. addPresetOption(this, presetName, true);
  35539. this.saveToLocalStorageIfPossible();
  35540. },
  35541. revert: function revert(gui) {
  35542. Common.each(this.__controllers, function (controller) {
  35543. if (!this.getRoot().load.remembered) {
  35544. controller.setValue(controller.initialValue);
  35545. } else {
  35546. recallSavedValue(gui || this.getRoot(), controller);
  35547. }
  35548. if (controller.__onFinishChange) {
  35549. controller.__onFinishChange.call(controller, controller.getValue());
  35550. }
  35551. }, this);
  35552. Common.each(this.__folders, function (folder) {
  35553. folder.revert(folder);
  35554. });
  35555. if (!gui) {
  35556. markPresetModified(this.getRoot(), false);
  35557. }
  35558. },
  35559. listen: function listen(controller) {
  35560. var init = this.__listening.length === 0;
  35561. this.__listening.push(controller);
  35562. if (init) {
  35563. updateDisplays(this.__listening);
  35564. }
  35565. },
  35566. updateDisplay: function updateDisplay() {
  35567. Common.each(this.__controllers, function (controller) {
  35568. controller.updateDisplay();
  35569. });
  35570. Common.each(this.__folders, function (folder) {
  35571. folder.updateDisplay();
  35572. });
  35573. }
  35574. });
  35575. function addRow(gui, newDom, liBefore) {
  35576. var li = document.createElement('li');
  35577. if (newDom) {
  35578. li.appendChild(newDom);
  35579. }
  35580. if (liBefore) {
  35581. gui.__ul.insertBefore(li, liBefore);
  35582. } else {
  35583. gui.__ul.appendChild(li);
  35584. }
  35585. gui.onResize();
  35586. return li;
  35587. }
  35588. function removeListeners(gui) {
  35589. dom.unbind(window, 'resize', gui.__resizeHandler);
  35590. if (gui.saveToLocalStorageIfPossible) {
  35591. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  35592. }
  35593. }
  35594. function markPresetModified(gui, modified) {
  35595. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  35596. if (modified) {
  35597. opt.innerHTML = opt.value + '*';
  35598. } else {
  35599. opt.innerHTML = opt.value;
  35600. }
  35601. }
  35602. function augmentController(gui, li, controller) {
  35603. controller.__li = li;
  35604. controller.__gui = gui;
  35605. Common.extend(controller, {
  35606. options: function options(_options) {
  35607. if (arguments.length > 1) {
  35608. var nextSibling = controller.__li.nextElementSibling;
  35609. controller.remove();
  35610. return _add(gui, controller.object, controller.property, {
  35611. before: nextSibling,
  35612. factoryArgs: [Common.toArray(arguments)]
  35613. });
  35614. }
  35615. if (Common.isArray(_options) || Common.isObject(_options)) {
  35616. var _nextSibling = controller.__li.nextElementSibling;
  35617. controller.remove();
  35618. return _add(gui, controller.object, controller.property, {
  35619. before: _nextSibling,
  35620. factoryArgs: [_options]
  35621. });
  35622. }
  35623. },
  35624. name: function name(_name) {
  35625. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  35626. return controller;
  35627. },
  35628. listen: function listen() {
  35629. controller.__gui.listen(controller);
  35630. return controller;
  35631. },
  35632. remove: function remove() {
  35633. controller.__gui.remove(controller);
  35634. return controller;
  35635. }
  35636. });
  35637. if (controller instanceof NumberControllerSlider) {
  35638. var box = new NumberControllerBox(controller.object, controller.property, {
  35639. min: controller.__min,
  35640. max: controller.__max,
  35641. step: controller.__step
  35642. });
  35643. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  35644. var pc = controller[method];
  35645. var pb = box[method];
  35646. controller[method] = box[method] = function () {
  35647. var args = Array.prototype.slice.call(arguments);
  35648. pb.apply(box, args);
  35649. return pc.apply(controller, args);
  35650. };
  35651. });
  35652. dom.addClass(li, 'has-slider');
  35653. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  35654. } else if (controller instanceof NumberControllerBox) {
  35655. var r = function r(returned) {
  35656. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  35657. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  35658. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  35659. controller.remove();
  35660. var newController = _add(gui, controller.object, controller.property, {
  35661. before: controller.__li.nextElementSibling,
  35662. factoryArgs: [controller.__min, controller.__max, controller.__step]
  35663. });
  35664. newController.name(oldName);
  35665. if (wasListening) newController.listen();
  35666. return newController;
  35667. }
  35668. return returned;
  35669. };
  35670. controller.min = Common.compose(r, controller.min);
  35671. controller.max = Common.compose(r, controller.max);
  35672. } else if (controller instanceof BooleanController) {
  35673. dom.bind(li, 'click', function () {
  35674. dom.fakeEvent(controller.__checkbox, 'click');
  35675. });
  35676. dom.bind(controller.__checkbox, 'click', function (e) {
  35677. e.stopPropagation();
  35678. });
  35679. } else if (controller instanceof FunctionController) {
  35680. dom.bind(li, 'click', function () {
  35681. dom.fakeEvent(controller.__button, 'click');
  35682. });
  35683. dom.bind(li, 'mouseover', function () {
  35684. dom.addClass(controller.__button, 'hover');
  35685. });
  35686. dom.bind(li, 'mouseout', function () {
  35687. dom.removeClass(controller.__button, 'hover');
  35688. });
  35689. } else if (controller instanceof ColorController) {
  35690. dom.addClass(li, 'color');
  35691. controller.updateDisplay = Common.compose(function (val) {
  35692. li.style.borderLeftColor = controller.__color.toString();
  35693. return val;
  35694. }, controller.updateDisplay);
  35695. controller.updateDisplay();
  35696. }
  35697. controller.setValue = Common.compose(function (val) {
  35698. if (gui.getRoot().__preset_select && controller.isModified()) {
  35699. markPresetModified(gui.getRoot(), true);
  35700. }
  35701. return val;
  35702. }, controller.setValue);
  35703. }
  35704. function recallSavedValue(gui, controller) {
  35705. var root = gui.getRoot();
  35706. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  35707. if (matchedIndex !== -1) {
  35708. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  35709. if (controllerMap === undefined) {
  35710. controllerMap = {};
  35711. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  35712. }
  35713. controllerMap[controller.property] = controller;
  35714. if (root.load && root.load.remembered) {
  35715. var presetMap = root.load.remembered;
  35716. var preset = void 0;
  35717. if (presetMap[gui.preset]) {
  35718. preset = presetMap[gui.preset];
  35719. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  35720. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  35721. } else {
  35722. return;
  35723. }
  35724. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  35725. var value = preset[matchedIndex][controller.property];
  35726. controller.initialValue = value;
  35727. controller.setValue(value);
  35728. }
  35729. }
  35730. }
  35731. }
  35732. function _add(gui, object, property, params) {
  35733. if (object[property] === undefined) {
  35734. throw new Error('Object "' + object + '" has no property "' + property + '"');
  35735. }
  35736. var controller = void 0;
  35737. if (params.color) {
  35738. controller = new ColorController(object, property);
  35739. } else {
  35740. var factoryArgs = [object, property].concat(params.factoryArgs);
  35741. controller = ControllerFactory.apply(gui, factoryArgs);
  35742. }
  35743. if (params.before instanceof Controller) {
  35744. params.before = params.before.__li;
  35745. }
  35746. recallSavedValue(gui, controller);
  35747. dom.addClass(controller.domElement, 'c');
  35748. var name = document.createElement('span');
  35749. dom.addClass(name, 'property-name');
  35750. name.innerHTML = controller.property;
  35751. var container = document.createElement('div');
  35752. container.appendChild(name);
  35753. container.appendChild(controller.domElement);
  35754. var li = addRow(gui, container, params.before);
  35755. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  35756. if (controller instanceof ColorController) {
  35757. dom.addClass(li, 'color');
  35758. } else {
  35759. dom.addClass(li, _typeof(controller.getValue()));
  35760. }
  35761. augmentController(gui, li, controller);
  35762. gui.__controllers.push(controller);
  35763. return controller;
  35764. }
  35765. function getLocalStorageHash(gui, key) {
  35766. return document.location.href + '.' + key;
  35767. }
  35768. function addPresetOption(gui, name, setSelected) {
  35769. var opt = document.createElement('option');
  35770. opt.innerHTML = name;
  35771. opt.value = name;
  35772. gui.__preset_select.appendChild(opt);
  35773. if (setSelected) {
  35774. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  35775. }
  35776. }
  35777. function showHideExplain(gui, explain) {
  35778. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  35779. }
  35780. function addSaveMenu(gui) {
  35781. var div = gui.__save_row = document.createElement('li');
  35782. dom.addClass(gui.domElement, 'has-save');
  35783. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  35784. dom.addClass(div, 'save-row');
  35785. var gears = document.createElement('span');
  35786. gears.innerHTML = '&nbsp;';
  35787. dom.addClass(gears, 'button gears');
  35788. var button = document.createElement('span');
  35789. button.innerHTML = 'Save';
  35790. dom.addClass(button, 'button');
  35791. dom.addClass(button, 'save');
  35792. var button2 = document.createElement('span');
  35793. button2.innerHTML = 'New';
  35794. dom.addClass(button2, 'button');
  35795. dom.addClass(button2, 'save-as');
  35796. var button3 = document.createElement('span');
  35797. button3.innerHTML = 'Revert';
  35798. dom.addClass(button3, 'button');
  35799. dom.addClass(button3, 'revert');
  35800. var select = gui.__preset_select = document.createElement('select');
  35801. if (gui.load && gui.load.remembered) {
  35802. Common.each(gui.load.remembered, function (value, key) {
  35803. addPresetOption(gui, key, key === gui.preset);
  35804. });
  35805. } else {
  35806. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  35807. }
  35808. dom.bind(select, 'change', function () {
  35809. for (var index = 0; index < gui.__preset_select.length; index++) {
  35810. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  35811. }
  35812. gui.preset = this.value;
  35813. });
  35814. div.appendChild(select);
  35815. div.appendChild(gears);
  35816. div.appendChild(button);
  35817. div.appendChild(button2);
  35818. div.appendChild(button3);
  35819. if (SUPPORTS_LOCAL_STORAGE) {
  35820. var explain = document.getElementById('dg-local-explain');
  35821. var localStorageCheckBox = document.getElementById('dg-local-storage');
  35822. var saveLocally = document.getElementById('dg-save-locally');
  35823. saveLocally.style.display = 'block';
  35824. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  35825. localStorageCheckBox.setAttribute('checked', 'checked');
  35826. }
  35827. showHideExplain(gui, explain);
  35828. dom.bind(localStorageCheckBox, 'change', function () {
  35829. gui.useLocalStorage = !gui.useLocalStorage;
  35830. showHideExplain(gui, explain);
  35831. });
  35832. }
  35833. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  35834. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  35835. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  35836. SAVE_DIALOGUE.hide();
  35837. }
  35838. });
  35839. dom.bind(gears, 'click', function () {
  35840. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  35841. SAVE_DIALOGUE.show();
  35842. newConstructorTextArea.focus();
  35843. newConstructorTextArea.select();
  35844. });
  35845. dom.bind(button, 'click', function () {
  35846. gui.save();
  35847. });
  35848. dom.bind(button2, 'click', function () {
  35849. var presetName = prompt('Enter a new preset name.');
  35850. if (presetName) {
  35851. gui.saveAs(presetName);
  35852. }
  35853. });
  35854. dom.bind(button3, 'click', function () {
  35855. gui.revert();
  35856. });
  35857. }
  35858. function addResizeHandle(gui) {
  35859. var pmouseX = void 0;
  35860. gui.__resize_handle = document.createElement('div');
  35861. Common.extend(gui.__resize_handle.style, {
  35862. width: '6px',
  35863. marginLeft: '-3px',
  35864. height: '200px',
  35865. cursor: 'ew-resize',
  35866. position: 'absolute'
  35867. });
  35868. function drag(e) {
  35869. e.preventDefault();
  35870. gui.width += pmouseX - e.clientX;
  35871. gui.onResize();
  35872. pmouseX = e.clientX;
  35873. return false;
  35874. }
  35875. function dragStop() {
  35876. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  35877. dom.unbind(window, 'mousemove', drag);
  35878. dom.unbind(window, 'mouseup', dragStop);
  35879. }
  35880. function dragStart(e) {
  35881. e.preventDefault();
  35882. pmouseX = e.clientX;
  35883. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  35884. dom.bind(window, 'mousemove', drag);
  35885. dom.bind(window, 'mouseup', dragStop);
  35886. return false;
  35887. }
  35888. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  35889. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  35890. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  35891. }
  35892. function setWidth(gui, w) {
  35893. gui.domElement.style.width = w + 'px';
  35894. if (gui.__save_row && gui.autoPlace) {
  35895. gui.__save_row.style.width = w + 'px';
  35896. }
  35897. if (gui.__closeButton) {
  35898. gui.__closeButton.style.width = w + 'px';
  35899. }
  35900. }
  35901. function getCurrentPreset(gui, useInitialValues) {
  35902. var toReturn = {};
  35903. Common.each(gui.__rememberedObjects, function (val, index) {
  35904. var savedValues = {};
  35905. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  35906. Common.each(controllerMap, function (controller, property) {
  35907. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  35908. });
  35909. toReturn[index] = savedValues;
  35910. });
  35911. return toReturn;
  35912. }
  35913. function setPresetSelectIndex(gui) {
  35914. for (var index = 0; index < gui.__preset_select.length; index++) {
  35915. if (gui.__preset_select[index].value === gui.preset) {
  35916. gui.__preset_select.selectedIndex = index;
  35917. }
  35918. }
  35919. }
  35920. function updateDisplays(controllerArray) {
  35921. if (controllerArray.length !== 0) {
  35922. requestAnimationFrame$1.call(window, function () {
  35923. updateDisplays(controllerArray);
  35924. });
  35925. }
  35926. Common.each(controllerArray, function (c) {
  35927. c.updateDisplay();
  35928. });
  35929. }
  35930. var color = {
  35931. Color: Color,
  35932. math: ColorMath,
  35933. interpret: interpret
  35934. };
  35935. exports.color = color;
  35936. var controllers = {
  35937. Controller: Controller,
  35938. BooleanController: BooleanController,
  35939. OptionController: OptionController,
  35940. StringController: StringController,
  35941. NumberController: NumberController,
  35942. NumberControllerBox: NumberControllerBox,
  35943. NumberControllerSlider: NumberControllerSlider,
  35944. FunctionController: FunctionController,
  35945. ColorController: ColorController
  35946. };
  35947. exports.controllers = controllers;
  35948. var dom$1 = {
  35949. dom: dom
  35950. };
  35951. exports.dom = dom$1;
  35952. var gui = {
  35953. GUI: GUI
  35954. };
  35955. exports.gui = gui;
  35956. var GUI$1 = GUI;
  35957. exports.GUI = GUI$1;
  35958. var index = {
  35959. color: color,
  35960. controllers: controllers,
  35961. dom: dom$1,
  35962. gui: gui,
  35963. GUI: GUI$1
  35964. };
  35965. var _default = index;
  35966. exports.default = _default;
  35967. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  35968. "use strict";
  35969. Object.defineProperty(exports, "__esModule", {
  35970. value: true
  35971. });
  35972. exports.default = void 0;
  35973. /**
  35974. * @author mrdoob / http://mrdoob.com/
  35975. */
  35976. var Stats = function () {
  35977. var mode = 0;
  35978. var container = document.createElement('div');
  35979. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  35980. container.addEventListener('click', function (event) {
  35981. event.preventDefault();
  35982. showPanel(++mode % container.children.length);
  35983. }, false); //
  35984. function addPanel(panel) {
  35985. container.appendChild(panel.dom);
  35986. return panel;
  35987. }
  35988. function showPanel(id) {
  35989. for (var i = 0; i < container.children.length; i++) {
  35990. container.children[i].style.display = i === id ? 'block' : 'none';
  35991. }
  35992. mode = id;
  35993. } //
  35994. var beginTime = (performance || Date).now(),
  35995. prevTime = beginTime,
  35996. frames = 0;
  35997. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  35998. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  35999. if (self.performance && self.performance.memory) {
  36000. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  36001. }
  36002. showPanel(0);
  36003. return {
  36004. REVISION: 16,
  36005. dom: container,
  36006. addPanel: addPanel,
  36007. showPanel: showPanel,
  36008. begin: function () {
  36009. beginTime = (performance || Date).now();
  36010. },
  36011. end: function () {
  36012. frames++;
  36013. var time = (performance || Date).now();
  36014. msPanel.update(time - beginTime, 200);
  36015. if (time >= prevTime + 1000) {
  36016. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  36017. prevTime = time;
  36018. frames = 0;
  36019. if (memPanel) {
  36020. var memory = performance.memory;
  36021. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  36022. }
  36023. }
  36024. return time;
  36025. },
  36026. update: function () {
  36027. beginTime = this.end();
  36028. },
  36029. // Backwards Compatibility
  36030. domElement: container,
  36031. setMode: showPanel
  36032. };
  36033. };
  36034. Stats.Panel = function (name, fg, bg) {
  36035. var min = Infinity,
  36036. max = 0,
  36037. round = Math.round;
  36038. var PR = round(window.devicePixelRatio || 1);
  36039. var WIDTH = 80 * PR,
  36040. HEIGHT = 48 * PR,
  36041. TEXT_X = 3 * PR,
  36042. TEXT_Y = 2 * PR,
  36043. GRAPH_X = 3 * PR,
  36044. GRAPH_Y = 15 * PR,
  36045. GRAPH_WIDTH = 74 * PR,
  36046. GRAPH_HEIGHT = 30 * PR;
  36047. var canvas = document.createElement('canvas');
  36048. canvas.width = WIDTH;
  36049. canvas.height = HEIGHT;
  36050. canvas.style.cssText = 'width:80px;height:48px';
  36051. var context = canvas.getContext('2d');
  36052. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  36053. context.textBaseline = 'top';
  36054. context.fillStyle = bg;
  36055. context.fillRect(0, 0, WIDTH, HEIGHT);
  36056. context.fillStyle = fg;
  36057. context.fillText(name, TEXT_X, TEXT_Y);
  36058. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  36059. context.fillStyle = bg;
  36060. context.globalAlpha = 0.9;
  36061. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  36062. return {
  36063. dom: canvas,
  36064. update: function (value, maxValue) {
  36065. min = Math.min(min, value);
  36066. max = Math.max(max, value);
  36067. context.fillStyle = bg;
  36068. context.globalAlpha = 1;
  36069. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  36070. context.fillStyle = fg;
  36071. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  36072. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  36073. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  36074. context.fillStyle = bg;
  36075. context.globalAlpha = 0.9;
  36076. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  36077. }
  36078. };
  36079. };
  36080. var _default = Stats;
  36081. exports.default = _default;
  36082. },{}],"index.js":[function(require,module,exports) {
  36083. "use strict";
  36084. var _index = require("../src/index.js");
  36085. var _three = require("three");
  36086. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  36087. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  36088. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  36089. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36090. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  36091. 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; }
  36092. let camera, controls, scene, renderer, tiles, cameraHelper;
  36093. let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  36094. let orthoCamera, orthoCameraHelper;
  36095. let box;
  36096. let raycaster, mouse, rayIntersect;
  36097. let offsetParent;
  36098. let statsContainer, stats;
  36099. let params = {
  36100. 'orthographic': false,
  36101. 'errorTarget': 6,
  36102. 'errorThreshold': 60,
  36103. 'maxDepth': 15,
  36104. 'loadSiblings': true,
  36105. 'up': '+Y',
  36106. 'displayBounds': false,
  36107. 'showThirdPerson': true,
  36108. 'reload': reinstantiateTiles
  36109. };
  36110. init();
  36111. animate();
  36112. function reinstantiateTiles() {
  36113. const url = window.location.hash.replace(/^#/, '') || './SampleTileset/tileset.json';
  36114. if (tiles) {
  36115. offsetParent.remove(tiles.group);
  36116. }
  36117. tiles = new _index.TilesRenderer(url, camera, renderer);
  36118. offsetParent.add(tiles.group);
  36119. }
  36120. function init() {
  36121. // Third person camera view
  36122. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 3000);
  36123. thirdPersonCamera.position.set(50, 40, 40);
  36124. thirdPersonCamera.lookAt(0, 0, 0);
  36125. thirdPersonRenderer = new _three.WebGLRenderer({
  36126. antialias: true
  36127. });
  36128. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  36129. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  36130. thirdPersonRenderer.setClearColor(0x0f1416);
  36131. document.body.appendChild(thirdPersonRenderer.domElement);
  36132. thirdPersonRenderer.domElement.style.position = 'fixed';
  36133. thirdPersonRenderer.domElement.style.left = '5px';
  36134. thirdPersonRenderer.domElement.style.bottom = '5px';
  36135. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  36136. thirdPersonControls.screenSpacePanning = false;
  36137. thirdPersonControls.minDistance = 1;
  36138. thirdPersonControls.maxDistance = 2000; // primary camera view
  36139. scene = new _three.Scene();
  36140. renderer = new _three.WebGLRenderer({
  36141. antialias: true
  36142. });
  36143. renderer.setPixelRatio(window.devicePixelRatio);
  36144. renderer.setSize(window.innerWidth, window.innerHeight);
  36145. renderer.setClearColor(0x151c1f);
  36146. renderer.gammaInput = true;
  36147. renderer.gameOutput = true;
  36148. document.body.appendChild(renderer.domElement);
  36149. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
  36150. camera.position.set(400, 400, 400);
  36151. cameraHelper = new _three.CameraHelper(camera);
  36152. scene.add(cameraHelper);
  36153. orthoCamera = new _three.OrthographicCamera();
  36154. orthoCameraHelper = new _three.CameraHelper(orthoCamera);
  36155. scene.add(orthoCameraHelper); // controls
  36156. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  36157. controls.screenSpacePanning = false;
  36158. controls.minDistance = 1;
  36159. controls.maxDistance = 2000; // lights
  36160. var dirLight = new _three.DirectionalLight(0xffffff);
  36161. dirLight.position.set(1, 2, 3);
  36162. scene.add(dirLight);
  36163. var ambLight = new _three.AmbientLight(0xffffff, 0.2);
  36164. scene.add(ambLight);
  36165. box = new _three.Box3();
  36166. offsetParent = new _three.Group();
  36167. scene.add(offsetParent); // Raycasting init
  36168. raycaster = new _three.Raycaster();
  36169. mouse = new _three.Vector2();
  36170. rayIntersect = new _three.Group();
  36171. const rayIntersectMat = new _three.MeshBasicMaterial({
  36172. color: 0xe91e63
  36173. });
  36174. const rayMesh = new _three.Mesh(new _three.CylinderBufferGeometry(0.25, 0.25, 10), rayIntersectMat);
  36175. rayMesh.rotation.x = Math.PI / 2;
  36176. rayMesh.position.z += 5;
  36177. rayIntersect.add(rayMesh);
  36178. const rayRing = new _three.Mesh(new _three.TorusBufferGeometry(1.5, 0.2, 16, 100), rayIntersectMat);
  36179. rayIntersect.add(rayRing);
  36180. scene.add(rayIntersect);
  36181. rayIntersect.visible = false;
  36182. reinstantiateTiles();
  36183. onWindowResize();
  36184. window.addEventListener('resize', onWindowResize, false);
  36185. window.addEventListener('mousemove', onMouseMove, false); // GUI
  36186. const gui = new dat.GUI();
  36187. const tiles = gui.addFolder('Tiles Options');
  36188. tiles.add(params, 'orthographic');
  36189. tiles.add(params, 'loadSiblings');
  36190. tiles.add(params, 'errorTarget').min(0).max(50);
  36191. tiles.add(params, 'errorThreshold').min(0).max(1000);
  36192. tiles.add(params, 'maxDepth').min(1).max(100);
  36193. tiles.add(params, 'up', ['+Y', '-Z']);
  36194. tiles.open();
  36195. gui.add(params, 'displayBounds');
  36196. gui.add(params, 'showThirdPerson');
  36197. gui.add(params, 'reload');
  36198. gui.open();
  36199. statsContainer = document.createElement('div');
  36200. statsContainer.style.position = 'absolute';
  36201. statsContainer.style.top = 0;
  36202. statsContainer.style.left = 0;
  36203. statsContainer.style.color = 'white';
  36204. statsContainer.style.width = '100%';
  36205. statsContainer.style.textAlign = 'center';
  36206. statsContainer.style.padding = '10px';
  36207. document.body.appendChild(statsContainer); // Stats
  36208. stats = new _statsModule.default();
  36209. stats.showPanel(0);
  36210. document.body.appendChild(stats.dom);
  36211. }
  36212. function onWindowResize() {
  36213. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  36214. thirdPersonCamera.updateProjectionMatrix();
  36215. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  36216. camera.aspect = window.innerWidth / window.innerHeight;
  36217. camera.updateProjectionMatrix();
  36218. renderer.setSize(window.innerWidth, window.innerHeight);
  36219. updateOrthoCamera();
  36220. }
  36221. function onMouseMove(e) {
  36222. mouse.x = e.clientX / window.innerWidth * 2 - 1;
  36223. mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
  36224. }
  36225. function updateOrthoCamera() {
  36226. orthoCamera.position.copy(camera.position);
  36227. orthoCamera.rotation.copy(camera.rotation);
  36228. const scale = camera.position.distanceTo(controls.target) / 2.0;
  36229. const aspect = window.innerWidth / window.innerHeight;
  36230. orthoCamera.left = -aspect * scale;
  36231. orthoCamera.right = aspect * scale;
  36232. orthoCamera.bottom = -scale;
  36233. orthoCamera.top = scale;
  36234. orthoCamera.near = camera.near;
  36235. orthoCamera.far = camera.far;
  36236. orthoCamera.updateProjectionMatrix();
  36237. }
  36238. function animate() {
  36239. // update options
  36240. tiles.errorTarget = params.errorTarget;
  36241. tiles.errorThreshold = params.errorThreshold;
  36242. tiles.loadSiblings = params.loadSiblings;
  36243. tiles.maxDepth = params.maxDepth;
  36244. tiles.displayBounds = params.displayBounds;
  36245. tiles.cameras[0] = params.orthographic ? orthoCamera : camera; // update tiles
  36246. tiles.update();
  36247. window.tiles = tiles;
  36248. offsetParent.rotation.set(0, 0, 0);
  36249. if (params.up === '-Z') {
  36250. offsetParent.rotation.x = Math.PI / 2;
  36251. } // update tiles center
  36252. if (tiles.getBounds(box)) {
  36253. box.getCenter(tiles.group.position);
  36254. tiles.group.position.multiplyScalar(-1);
  36255. }
  36256. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  36257. raycaster.firstHitOnly = true;
  36258. const results = raycaster.intersectObject(tiles.group, true);
  36259. if (results.length) {
  36260. const closestHit = results[0];
  36261. const point = closestHit.point;
  36262. rayIntersect.position.copy(point); // If the display bounds are visible they get intersected
  36263. if (closestHit.face) {
  36264. const normal = closestHit.face.normal;
  36265. rayIntersect.lookAt(point.x + normal.x, point.y + normal.y, point.z + normal.z);
  36266. }
  36267. rayIntersect.visible = true;
  36268. } else {
  36269. rayIntersect.visible = false;
  36270. }
  36271. stats.begin();
  36272. render();
  36273. stats.end();
  36274. requestAnimationFrame(animate);
  36275. }
  36276. function render() {
  36277. updateOrthoCamera(); // render primary view
  36278. cameraHelper.visible = false;
  36279. orthoCameraHelper.visible = false;
  36280. renderer.render(scene, params.orthographic ? orthoCamera : camera); // render third person view
  36281. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  36282. if (params.showThirdPerson) {
  36283. cameraHelper.update();
  36284. cameraHelper.visible = !params.orthographic;
  36285. orthoCameraHelper.update();
  36286. orthoCameraHelper.visible = params.orthographic;
  36287. thirdPersonRenderer.render(scene, thirdPersonCamera);
  36288. }
  36289. statsContainer.innerText = `Downloading: ${tiles.stats.downloading} Parsing: ${tiles.stats.parsing} Visible: ${tiles.group.children.length}`;
  36290. }
  36291. },{"../src/index.js":"../src/index.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/controls/OrbitControls.js":"../node_modules/three/examples/jsm/controls/OrbitControls.js","three/examples/jsm/libs/dat.gui.module.js":"../node_modules/three/examples/jsm/libs/dat.gui.module.js","three/examples/jsm/libs/stats.module.js":"../node_modules/three/examples/jsm/libs/stats.module.js"}],"../node_modules/parcel-bundler/src/builtins/hmr-runtime.js":[function(require,module,exports) {
  36292. var global = arguments[3];
  36293. var OVERLAY_ID = '__parcel__error__overlay__';
  36294. var OldModule = module.bundle.Module;
  36295. function Module(moduleName) {
  36296. OldModule.call(this, moduleName);
  36297. this.hot = {
  36298. data: module.bundle.hotData,
  36299. _acceptCallbacks: [],
  36300. _disposeCallbacks: [],
  36301. accept: function (fn) {
  36302. this._acceptCallbacks.push(fn || function () {});
  36303. },
  36304. dispose: function (fn) {
  36305. this._disposeCallbacks.push(fn);
  36306. }
  36307. };
  36308. module.bundle.hotData = null;
  36309. }
  36310. module.bundle.Module = Module;
  36311. var checkedAssets, assetsToAccept;
  36312. var parent = module.bundle.parent;
  36313. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  36314. var hostname = "" || location.hostname;
  36315. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  36316. var ws = new WebSocket(protocol + '://' + hostname + ':' + "57728" + '/');
  36317. ws.onmessage = function (event) {
  36318. checkedAssets = {};
  36319. assetsToAccept = [];
  36320. var data = JSON.parse(event.data);
  36321. if (data.type === 'update') {
  36322. var handled = false;
  36323. data.assets.forEach(function (asset) {
  36324. if (!asset.isNew) {
  36325. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  36326. if (didAccept) {
  36327. handled = true;
  36328. }
  36329. }
  36330. }); // Enable HMR for CSS by default.
  36331. handled = handled || data.assets.every(function (asset) {
  36332. return asset.type === 'css' && asset.generated.js;
  36333. });
  36334. if (handled) {
  36335. console.clear();
  36336. data.assets.forEach(function (asset) {
  36337. hmrApply(global.parcelRequire, asset);
  36338. });
  36339. assetsToAccept.forEach(function (v) {
  36340. hmrAcceptRun(v[0], v[1]);
  36341. });
  36342. } else if (location.reload) {
  36343. // `location` global exists in a web worker context but lacks `.reload()` function.
  36344. location.reload();
  36345. }
  36346. }
  36347. if (data.type === 'reload') {
  36348. ws.close();
  36349. ws.onclose = function () {
  36350. location.reload();
  36351. };
  36352. }
  36353. if (data.type === 'error-resolved') {
  36354. console.log('[parcel] ✨ Error resolved');
  36355. removeErrorOverlay();
  36356. }
  36357. if (data.type === 'error') {
  36358. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  36359. removeErrorOverlay();
  36360. var overlay = createErrorOverlay(data);
  36361. document.body.appendChild(overlay);
  36362. }
  36363. };
  36364. }
  36365. function removeErrorOverlay() {
  36366. var overlay = document.getElementById(OVERLAY_ID);
  36367. if (overlay) {
  36368. overlay.remove();
  36369. }
  36370. }
  36371. function createErrorOverlay(data) {
  36372. var overlay = document.createElement('div');
  36373. overlay.id = OVERLAY_ID; // html encode message and stack trace
  36374. var message = document.createElement('div');
  36375. var stackTrace = document.createElement('pre');
  36376. message.innerText = data.error.message;
  36377. stackTrace.innerText = data.error.stack;
  36378. 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>';
  36379. return overlay;
  36380. }
  36381. function getParents(bundle, id) {
  36382. var modules = bundle.modules;
  36383. if (!modules) {
  36384. return [];
  36385. }
  36386. var parents = [];
  36387. var k, d, dep;
  36388. for (k in modules) {
  36389. for (d in modules[k][1]) {
  36390. dep = modules[k][1][d];
  36391. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  36392. parents.push(k);
  36393. }
  36394. }
  36395. }
  36396. if (bundle.parent) {
  36397. parents = parents.concat(getParents(bundle.parent, id));
  36398. }
  36399. return parents;
  36400. }
  36401. function hmrApply(bundle, asset) {
  36402. var modules = bundle.modules;
  36403. if (!modules) {
  36404. return;
  36405. }
  36406. if (modules[asset.id] || !bundle.parent) {
  36407. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  36408. asset.isNew = !modules[asset.id];
  36409. modules[asset.id] = [fn, asset.deps];
  36410. } else if (bundle.parent) {
  36411. hmrApply(bundle.parent, asset);
  36412. }
  36413. }
  36414. function hmrAcceptCheck(bundle, id) {
  36415. var modules = bundle.modules;
  36416. if (!modules) {
  36417. return;
  36418. }
  36419. if (!modules[id] && bundle.parent) {
  36420. return hmrAcceptCheck(bundle.parent, id);
  36421. }
  36422. if (checkedAssets[id]) {
  36423. return;
  36424. }
  36425. checkedAssets[id] = true;
  36426. var cached = bundle.cache[id];
  36427. assetsToAccept.push([bundle, id]);
  36428. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36429. return true;
  36430. }
  36431. return getParents(global.parcelRequire, id).some(function (id) {
  36432. return hmrAcceptCheck(global.parcelRequire, id);
  36433. });
  36434. }
  36435. function hmrAcceptRun(bundle, id) {
  36436. var cached = bundle.cache[id];
  36437. bundle.hotData = {};
  36438. if (cached) {
  36439. cached.hot.data = bundle.hotData;
  36440. }
  36441. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  36442. cached.hot._disposeCallbacks.forEach(function (cb) {
  36443. cb(bundle.hotData);
  36444. });
  36445. }
  36446. delete bundle.cache[id];
  36447. bundle(id);
  36448. cached = bundle.cache[id];
  36449. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36450. cached.hot._acceptCallbacks.forEach(function (cb) {
  36451. cb();
  36452. });
  36453. return true;
  36454. }
  36455. }
  36456. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  36457. //# sourceMappingURL=example.e31bb0bc.js.map