example.e31bb0bc.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706
  1. // modules are defined as an array
  2. // [ module function, map of requires ]
  3. //
  4. // map of requires is short require name -> numeric require
  5. //
  6. // anything defined in a previous bundle is accessed via the
  7. // orig method which is the require for previous bundles
  8. parcelRequire = (function (modules, cache, entry, globalName) {
  9. // Save the require from previous bundle to this closure if any
  10. var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
  11. var nodeRequire = typeof require === 'function' && require;
  12. function newRequire(name, jumped) {
  13. if (!cache[name]) {
  14. if (!modules[name]) {
  15. // if we cannot find the module within our internal map or
  16. // cache jump to the current global require ie. the last bundle
  17. // that was added to the page.
  18. var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
  19. if (!jumped && currentRequire) {
  20. return currentRequire(name, true);
  21. }
  22. // If there are other bundles on this page the require from the
  23. // previous one is saved to 'previousRequire'. Repeat this as
  24. // many times as there are bundles until the module is found or
  25. // we exhaust the require chain.
  26. if (previousRequire) {
  27. return previousRequire(name, true);
  28. }
  29. // Try the node require function if it exists.
  30. if (nodeRequire && typeof name === 'string') {
  31. return nodeRequire(name);
  32. }
  33. var err = new Error('Cannot find module \'' + name + '\'');
  34. err.code = 'MODULE_NOT_FOUND';
  35. throw err;
  36. }
  37. localRequire.resolve = resolve;
  38. localRequire.cache = {};
  39. var module = cache[name] = new newRequire.Module(name);
  40. modules[name][0].call(module.exports, localRequire, module, module.exports, this);
  41. }
  42. return cache[name].exports;
  43. function localRequire(x){
  44. return newRequire(localRequire.resolve(x));
  45. }
  46. function resolve(x){
  47. return modules[name][1][x] || x;
  48. }
  49. }
  50. function Module(moduleName) {
  51. this.id = moduleName;
  52. this.bundle = newRequire;
  53. this.exports = {};
  54. }
  55. newRequire.isParcelRequire = true;
  56. newRequire.Module = Module;
  57. newRequire.modules = modules;
  58. newRequire.cache = cache;
  59. newRequire.parent = previousRequire;
  60. newRequire.register = function (id, exports) {
  61. modules[id] = [function (require, module) {
  62. module.exports = exports;
  63. }, {}];
  64. };
  65. var error;
  66. for (var i = 0; i < entry.length; i++) {
  67. try {
  68. newRequire(entry[i]);
  69. } catch (e) {
  70. // Save first error but execute all entries
  71. if (!error) {
  72. error = e;
  73. }
  74. }
  75. }
  76. if (entry.length) {
  77. // Expose entry point to Node, AMD or browser globals
  78. // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
  79. var mainExports = newRequire(entry[entry.length - 1]);
  80. // CommonJS
  81. if (typeof exports === "object" && typeof module !== "undefined") {
  82. module.exports = mainExports;
  83. // RequireJS
  84. } else if (typeof define === "function" && define.amd) {
  85. define(function () {
  86. return mainExports;
  87. });
  88. // <script>
  89. } else if (globalName) {
  90. this[globalName] = mainExports;
  91. }
  92. }
  93. // Override the current require with this new one
  94. parcelRequire = newRequire;
  95. if (error) {
  96. // throw error from earlier, _after updating parcelRequire_
  97. throw error;
  98. }
  99. return newRequire;
  100. })({"../node_modules/process/browser.js":[function(require,module,exports) {
  101. // shim for using process in browser
  102. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  103. // don't break things. But we need to wrap it in a try catch in case it is
  104. // wrapped in strict mode code which doesn't define any globals. It's inside a
  105. // function because try/catches deoptimize in certain engines.
  106. var cachedSetTimeout;
  107. var cachedClearTimeout;
  108. function defaultSetTimout() {
  109. throw new Error('setTimeout has not been defined');
  110. }
  111. function defaultClearTimeout() {
  112. throw new Error('clearTimeout has not been defined');
  113. }
  114. (function () {
  115. try {
  116. if (typeof setTimeout === 'function') {
  117. cachedSetTimeout = setTimeout;
  118. } else {
  119. cachedSetTimeout = defaultSetTimout;
  120. }
  121. } catch (e) {
  122. cachedSetTimeout = defaultSetTimout;
  123. }
  124. try {
  125. if (typeof clearTimeout === 'function') {
  126. cachedClearTimeout = clearTimeout;
  127. } else {
  128. cachedClearTimeout = defaultClearTimeout;
  129. }
  130. } catch (e) {
  131. cachedClearTimeout = defaultClearTimeout;
  132. }
  133. })();
  134. function runTimeout(fun) {
  135. if (cachedSetTimeout === setTimeout) {
  136. //normal enviroments in sane situations
  137. return setTimeout(fun, 0);
  138. } // if setTimeout wasn't available but was latter defined
  139. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  140. cachedSetTimeout = setTimeout;
  141. return setTimeout(fun, 0);
  142. }
  143. try {
  144. // when when somebody has screwed with setTimeout but no I.E. maddness
  145. return cachedSetTimeout(fun, 0);
  146. } catch (e) {
  147. try {
  148. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  149. return cachedSetTimeout.call(null, fun, 0);
  150. } catch (e) {
  151. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  152. return cachedSetTimeout.call(this, fun, 0);
  153. }
  154. }
  155. }
  156. function runClearTimeout(marker) {
  157. if (cachedClearTimeout === clearTimeout) {
  158. //normal enviroments in sane situations
  159. return clearTimeout(marker);
  160. } // if clearTimeout wasn't available but was latter defined
  161. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  162. cachedClearTimeout = clearTimeout;
  163. return clearTimeout(marker);
  164. }
  165. try {
  166. // when when somebody has screwed with setTimeout but no I.E. maddness
  167. return cachedClearTimeout(marker);
  168. } catch (e) {
  169. try {
  170. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  171. return cachedClearTimeout.call(null, marker);
  172. } catch (e) {
  173. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  174. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  175. return cachedClearTimeout.call(this, marker);
  176. }
  177. }
  178. }
  179. var queue = [];
  180. var draining = false;
  181. var currentQueue;
  182. var queueIndex = -1;
  183. function cleanUpNextTick() {
  184. if (!draining || !currentQueue) {
  185. return;
  186. }
  187. draining = false;
  188. if (currentQueue.length) {
  189. queue = currentQueue.concat(queue);
  190. } else {
  191. queueIndex = -1;
  192. }
  193. if (queue.length) {
  194. drainQueue();
  195. }
  196. }
  197. function drainQueue() {
  198. if (draining) {
  199. return;
  200. }
  201. var timeout = runTimeout(cleanUpNextTick);
  202. draining = true;
  203. var len = queue.length;
  204. while (len) {
  205. currentQueue = queue;
  206. queue = [];
  207. while (++queueIndex < len) {
  208. if (currentQueue) {
  209. currentQueue[queueIndex].run();
  210. }
  211. }
  212. queueIndex = -1;
  213. len = queue.length;
  214. }
  215. currentQueue = null;
  216. draining = false;
  217. runClearTimeout(timeout);
  218. }
  219. process.nextTick = function (fun) {
  220. var args = new Array(arguments.length - 1);
  221. if (arguments.length > 1) {
  222. for (var i = 1; i < arguments.length; i++) {
  223. args[i - 1] = arguments[i];
  224. }
  225. }
  226. queue.push(new Item(fun, args));
  227. if (queue.length === 1 && !draining) {
  228. runTimeout(drainQueue);
  229. }
  230. }; // v8 likes predictible objects
  231. function Item(fun, array) {
  232. this.fun = fun;
  233. this.array = array;
  234. }
  235. Item.prototype.run = function () {
  236. this.fun.apply(null, this.array);
  237. };
  238. process.title = 'browser';
  239. process.env = {};
  240. process.argv = [];
  241. process.version = ''; // empty string to avoid regexp issues
  242. process.versions = {};
  243. function noop() {}
  244. process.on = noop;
  245. process.addListener = noop;
  246. process.once = noop;
  247. process.off = noop;
  248. process.removeListener = noop;
  249. process.removeAllListeners = noop;
  250. process.emit = noop;
  251. process.prependListener = noop;
  252. process.prependOnceListener = noop;
  253. process.listeners = function (name) {
  254. return [];
  255. };
  256. process.binding = function (name) {
  257. throw new Error('process.binding is not supported');
  258. };
  259. process.cwd = function () {
  260. return '/';
  261. };
  262. process.chdir = function (dir) {
  263. throw new Error('process.chdir is not supported');
  264. };
  265. process.umask = function () {
  266. return 0;
  267. };
  268. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  269. var process = require("process");
  270. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  271. // backported and transplited with Babel, with backwards-compat fixes
  272. // Copyright Joyent, Inc. and other Node contributors.
  273. //
  274. // Permission is hereby granted, free of charge, to any person obtaining a
  275. // copy of this software and associated documentation files (the
  276. // "Software"), to deal in the Software without restriction, including
  277. // without limitation the rights to use, copy, modify, merge, publish,
  278. // distribute, sublicense, and/or sell copies of the Software, and to permit
  279. // persons to whom the Software is furnished to do so, subject to the
  280. // following conditions:
  281. //
  282. // The above copyright notice and this permission notice shall be included
  283. // in all copies or substantial portions of the Software.
  284. //
  285. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  286. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  287. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  288. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  289. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  290. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  291. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  292. // resolves . and .. elements in a path array with directory names there
  293. // must be no slashes, empty elements, or device names (c:\) in the array
  294. // (so also no leading and trailing slashes - it does not distinguish
  295. // relative and absolute paths)
  296. function normalizeArray(parts, allowAboveRoot) {
  297. // if the path tries to go above the root, `up` ends up > 0
  298. var up = 0;
  299. for (var i = parts.length - 1; i >= 0; i--) {
  300. var last = parts[i];
  301. if (last === '.') {
  302. parts.splice(i, 1);
  303. } else if (last === '..') {
  304. parts.splice(i, 1);
  305. up++;
  306. } else if (up) {
  307. parts.splice(i, 1);
  308. up--;
  309. }
  310. }
  311. // if the path is allowed to go above the root, restore leading ..s
  312. if (allowAboveRoot) {
  313. for (; up--; up) {
  314. parts.unshift('..');
  315. }
  316. }
  317. return parts;
  318. }
  319. // path.resolve([from ...], to)
  320. // posix version
  321. exports.resolve = function() {
  322. var resolvedPath = '',
  323. resolvedAbsolute = false;
  324. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  325. var path = (i >= 0) ? arguments[i] : process.cwd();
  326. // Skip empty and invalid entries
  327. if (typeof path !== 'string') {
  328. throw new TypeError('Arguments to path.resolve must be strings');
  329. } else if (!path) {
  330. continue;
  331. }
  332. resolvedPath = path + '/' + resolvedPath;
  333. resolvedAbsolute = path.charAt(0) === '/';
  334. }
  335. // At this point the path should be resolved to a full absolute path, but
  336. // handle relative paths to be safe (might happen when process.cwd() fails)
  337. // Normalize the path
  338. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  339. return !!p;
  340. }), !resolvedAbsolute).join('/');
  341. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  342. };
  343. // path.normalize(path)
  344. // posix version
  345. exports.normalize = function(path) {
  346. var isAbsolute = exports.isAbsolute(path),
  347. trailingSlash = substr(path, -1) === '/';
  348. // Normalize the path
  349. path = normalizeArray(filter(path.split('/'), function(p) {
  350. return !!p;
  351. }), !isAbsolute).join('/');
  352. if (!path && !isAbsolute) {
  353. path = '.';
  354. }
  355. if (path && trailingSlash) {
  356. path += '/';
  357. }
  358. return (isAbsolute ? '/' : '') + path;
  359. };
  360. // posix version
  361. exports.isAbsolute = function(path) {
  362. return path.charAt(0) === '/';
  363. };
  364. // posix version
  365. exports.join = function() {
  366. var paths = Array.prototype.slice.call(arguments, 0);
  367. return exports.normalize(filter(paths, function(p, index) {
  368. if (typeof p !== 'string') {
  369. throw new TypeError('Arguments to path.join must be strings');
  370. }
  371. return p;
  372. }).join('/'));
  373. };
  374. // path.relative(from, to)
  375. // posix version
  376. exports.relative = function(from, to) {
  377. from = exports.resolve(from).substr(1);
  378. to = exports.resolve(to).substr(1);
  379. function trim(arr) {
  380. var start = 0;
  381. for (; start < arr.length; start++) {
  382. if (arr[start] !== '') break;
  383. }
  384. var end = arr.length - 1;
  385. for (; end >= 0; end--) {
  386. if (arr[end] !== '') break;
  387. }
  388. if (start > end) return [];
  389. return arr.slice(start, end - start + 1);
  390. }
  391. var fromParts = trim(from.split('/'));
  392. var toParts = trim(to.split('/'));
  393. var length = Math.min(fromParts.length, toParts.length);
  394. var samePartsLength = length;
  395. for (var i = 0; i < length; i++) {
  396. if (fromParts[i] !== toParts[i]) {
  397. samePartsLength = i;
  398. break;
  399. }
  400. }
  401. var outputParts = [];
  402. for (var i = samePartsLength; i < fromParts.length; i++) {
  403. outputParts.push('..');
  404. }
  405. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  406. return outputParts.join('/');
  407. };
  408. exports.sep = '/';
  409. exports.delimiter = ':';
  410. exports.dirname = function (path) {
  411. if (typeof path !== 'string') path = path + '';
  412. if (path.length === 0) return '.';
  413. var code = path.charCodeAt(0);
  414. var hasRoot = code === 47 /*/*/;
  415. var end = -1;
  416. var matchedSlash = true;
  417. for (var i = path.length - 1; i >= 1; --i) {
  418. code = path.charCodeAt(i);
  419. if (code === 47 /*/*/) {
  420. if (!matchedSlash) {
  421. end = i;
  422. break;
  423. }
  424. } else {
  425. // We saw the first non-path separator
  426. matchedSlash = false;
  427. }
  428. }
  429. if (end === -1) return hasRoot ? '/' : '.';
  430. if (hasRoot && end === 1) {
  431. // return '//';
  432. // Backwards-compat fix:
  433. return '/';
  434. }
  435. return path.slice(0, end);
  436. };
  437. function basename(path) {
  438. if (typeof path !== 'string') path = path + '';
  439. var start = 0;
  440. var end = -1;
  441. var matchedSlash = true;
  442. var i;
  443. for (i = path.length - 1; i >= 0; --i) {
  444. if (path.charCodeAt(i) === 47 /*/*/) {
  445. // If we reached a path separator that was not part of a set of path
  446. // separators at the end of the string, stop now
  447. if (!matchedSlash) {
  448. start = i + 1;
  449. break;
  450. }
  451. } else if (end === -1) {
  452. // We saw the first non-path separator, mark this as the end of our
  453. // path component
  454. matchedSlash = false;
  455. end = i + 1;
  456. }
  457. }
  458. if (end === -1) return '';
  459. return path.slice(start, end);
  460. }
  461. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  462. // in new Node.js versions, so only basename() above is backported here
  463. exports.basename = function (path, ext) {
  464. var f = basename(path);
  465. if (ext && f.substr(-1 * ext.length) === ext) {
  466. f = f.substr(0, f.length - ext.length);
  467. }
  468. return f;
  469. };
  470. exports.extname = function (path) {
  471. if (typeof path !== 'string') path = path + '';
  472. var startDot = -1;
  473. var startPart = 0;
  474. var end = -1;
  475. var matchedSlash = true;
  476. // Track the state of characters (if any) we see before our first dot and
  477. // after any path separator we find
  478. var preDotState = 0;
  479. for (var i = path.length - 1; i >= 0; --i) {
  480. var code = path.charCodeAt(i);
  481. if (code === 47 /*/*/) {
  482. // If we reached a path separator that was not part of a set of path
  483. // separators at the end of the string, stop now
  484. if (!matchedSlash) {
  485. startPart = i + 1;
  486. break;
  487. }
  488. continue;
  489. }
  490. if (end === -1) {
  491. // We saw the first non-path separator, mark this as the end of our
  492. // extension
  493. matchedSlash = false;
  494. end = i + 1;
  495. }
  496. if (code === 46 /*.*/) {
  497. // If this is our first dot, mark it as the start of our extension
  498. if (startDot === -1)
  499. startDot = i;
  500. else if (preDotState !== 1)
  501. preDotState = 1;
  502. } else if (startDot !== -1) {
  503. // We saw a non-dot and non-path separator before our dot, so we should
  504. // have a good chance at having a non-empty extension
  505. preDotState = -1;
  506. }
  507. }
  508. if (startDot === -1 || end === -1 ||
  509. // We saw a non-dot character immediately before the dot
  510. preDotState === 0 ||
  511. // The (right-most) trimmed path component is exactly '..'
  512. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  513. return '';
  514. }
  515. return path.slice(startDot, end);
  516. };
  517. function filter (xs, f) {
  518. if (xs.filter) return xs.filter(f);
  519. var res = [];
  520. for (var i = 0; i < xs.length; i++) {
  521. if (f(xs[i], i, xs)) res.push(xs[i]);
  522. }
  523. return res;
  524. }
  525. // String.prototype.substr - negative index don't work in IE8
  526. var substr = 'ab'.substr(-1) === 'b'
  527. ? function (str, start, len) { return str.substr(start, len) }
  528. : function (str, start, len) {
  529. if (start < 0) start = str.length + start;
  530. return str.substr(start, len);
  531. }
  532. ;
  533. },{"process":"../node_modules/process/browser.js"}],"../src/LRUCache.js":[function(require,module,exports) {
  534. "use strict";
  535. Object.defineProperty(exports, "__esModule", {
  536. value: true
  537. });
  538. exports.LRUCache = void 0;
  539. class LRUCache {
  540. constructor() {
  541. // options
  542. this.maxSize = 800;
  543. this.minSize = 600;
  544. this.unloadPercent = 0.2;
  545. this.usedSet = new Set();
  546. this.itemSet = new Set();
  547. this.itemList = [];
  548. this.callbacks = new Map();
  549. } // Returns whether or not the cache has reached the maximum size
  550. isFull() {
  551. return this.itemSet.size >= this.maxSize;
  552. }
  553. add(item, removeCb) {
  554. const itemSet = this.itemSet;
  555. if (itemSet.has(item)) {
  556. return false;
  557. }
  558. if (this.isFull()) {
  559. return false;
  560. }
  561. const usedSet = this.usedSet;
  562. const itemList = this.itemList;
  563. const callbacks = this.callbacks;
  564. itemList.push(item);
  565. usedSet.add(item);
  566. itemSet.add(item);
  567. callbacks.set(item, removeCb);
  568. return true;
  569. }
  570. remove(item) {
  571. const usedSet = this.usedSet;
  572. const itemSet = this.itemSet;
  573. const itemList = this.itemList;
  574. const callbacks = this.callbacks;
  575. if (itemSet.has(item)) {
  576. callbacks.get(item)(item);
  577. const index = itemList.indexOf(item);
  578. itemList.splice(index, 1);
  579. usedSet.delete(item);
  580. itemSet.delete(item);
  581. callbacks.delete(item);
  582. return true;
  583. }
  584. return false;
  585. }
  586. markUsed(item) {
  587. const itemSet = this.itemSet;
  588. const usedSet = this.usedSet;
  589. if (itemSet.has(item) && !usedSet.has(item)) {
  590. const itemList = this.itemList;
  591. const index = itemList.indexOf(item);
  592. itemList.splice(index, 1);
  593. itemList.push(item);
  594. usedSet.add(item);
  595. }
  596. }
  597. markAllUnused() {
  598. this.usedSet.clear();
  599. }
  600. unloadUnusedContent(prioritySortCb) {
  601. const unloadPercent = this.unloadPercent;
  602. const targetSize = this.minSize;
  603. const itemList = this.itemList;
  604. const itemSet = this.itemSet;
  605. const usedSet = this.usedSet;
  606. const callbacks = this.callbacks;
  607. const unused = itemList.length - usedSet.size;
  608. if (itemList.length > targetSize && unused > 0) {
  609. // TODO: sort by priority
  610. let nodesToUnload = Math.max(itemList.length - targetSize, targetSize) * unloadPercent;
  611. nodesToUnload = Math.ceil(nodesToUnload);
  612. nodesToUnload = Math.min(unused, nodesToUnload);
  613. const removedItems = itemList.splice(0, nodesToUnload);
  614. for (let i = 0, l = removedItems.length; i < l; i++) {
  615. const item = removedItems[i];
  616. callbacks.get(item)(item);
  617. itemSet.delete(item);
  618. callbacks.delete(item);
  619. }
  620. }
  621. }
  622. scheduleUnload(prioritySortCb, markAllUnused = true) {
  623. if (!this.scheduled) {
  624. this.scheduled = true;
  625. Promise.resolve().then(() => {
  626. this.scheduled = false;
  627. this.unloadUnusedContent(prioritySortCb);
  628. if (markAllUnused) {
  629. this.markAllUnused();
  630. }
  631. });
  632. }
  633. }
  634. }
  635. exports.LRUCache = LRUCache;
  636. },{}],"../src/PriorityQueue.js":[function(require,module,exports) {
  637. "use strict";
  638. Object.defineProperty(exports, "__esModule", {
  639. value: true
  640. });
  641. exports.PriorityQueue = void 0;
  642. class PriorityQueue {
  643. constructor(maxJobs = 6) {
  644. // options
  645. this.maxJobs = maxJobs;
  646. this.items = [];
  647. this.currJobs = 0;
  648. this.scheduled = false;
  649. }
  650. add(item, priority, callback) {
  651. return new Promise((resolve, reject) => {
  652. const prCallback = (...args) => callback(...args).then(resolve).catch(reject);
  653. const items = this.items;
  654. for (let i = 0, l = items.length; i < l; i++) {
  655. const thisItem = items[i];
  656. if (thisItem.priority > priority) {
  657. items.splice(i, 0, {
  658. priority,
  659. item,
  660. callback: prCallback
  661. });
  662. this.scheduleJobRun();
  663. return;
  664. }
  665. }
  666. items.push({
  667. priority,
  668. item,
  669. callback: prCallback
  670. });
  671. this.scheduleJobRun();
  672. });
  673. }
  674. remove(item) {
  675. const items = this.items;
  676. for (let i = 0, l = items.length; i < l; i++) {
  677. const thisItem = items[i];
  678. if (thisItem.item === item) {
  679. items.splice(i, 1);
  680. break;
  681. }
  682. }
  683. }
  684. tryRunJobs() {
  685. const items = this.items;
  686. const maxJobs = this.maxJobs;
  687. while (maxJobs > this.currJobs && items.length > 0) {
  688. this.currJobs++;
  689. const {
  690. item,
  691. priority,
  692. callback
  693. } = items.pop();
  694. callback(item, priority).then(() => {
  695. this.currJobs--;
  696. this.scheduleJobRun();
  697. }).catch(() => {
  698. this.currJobs--;
  699. this.scheduleJobRun();
  700. });
  701. }
  702. }
  703. scheduleJobRun() {
  704. if (!this.scheduled) {
  705. Promise.resolve().then(() => {
  706. this.tryRunJobs();
  707. this.scheduled = false;
  708. });
  709. this.scheduled = true;
  710. }
  711. }
  712. }
  713. exports.PriorityQueue = PriorityQueue;
  714. },{}],"../src/TilesRenderer.js":[function(require,module,exports) {
  715. "use strict";
  716. Object.defineProperty(exports, "__esModule", {
  717. value: true
  718. });
  719. exports.TilesRenderer = void 0;
  720. var _path = _interopRequireDefault(require("path"));
  721. var _LRUCache = require("./LRUCache.js");
  722. var _PriorityQueue = require("./PriorityQueue.js");
  723. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  724. // TODO: find out why tiles are left dangling in the hierarchy
  725. // TODO: Address the issue of too many promises, garbage collection
  726. // TODO: remove more redundant computation
  727. // TODO: See if using classes improves performance
  728. // TODO: See if declaring function inline improves performance
  729. // TODO: Make sure active state works as expected
  730. const UNLOADED = 0;
  731. const LOADING = 1;
  732. const PARSING = 2;
  733. const LOADED = 3;
  734. const FAILED = 4;
  735. function traverseSet(tile, beforeCb = null, afterCb = null, parent = null, depth = 0) {
  736. if (beforeCb && beforeCb(tile, parent, depth)) {
  737. if (afterCb) {
  738. afterCb(tile, parent, depth);
  739. }
  740. return;
  741. }
  742. const children = tile.children;
  743. for (let i = 0, l = children.length; i < l; i++) {
  744. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  745. }
  746. if (afterCb) {
  747. afterCb(tile, parent, depth);
  748. }
  749. }
  750. function isUsedThisFrame(tile, frameCount) {
  751. return tile.__lastFrameVisited === frameCount && tile.__used;
  752. }
  753. function resetFrameState(tile, frameCount) {
  754. if (tile.__lastFrameVisited !== frameCount) {
  755. tile.__lastFrameVisited = frameCount;
  756. tile.__used = false;
  757. tile.__inFrustum = false;
  758. tile.__isLeaf = false;
  759. tile.__visible = false;
  760. tile.__active = false;
  761. tile.__error = 0;
  762. }
  763. }
  764. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  765. resetFrameState(tile, frameCount);
  766. tile.__used = true;
  767. lruCache.markUsed(tile);
  768. if (tile.__contentEmpty) {
  769. const children = tile.children;
  770. for (let i = 0, l = children.length; i < l; i++) {
  771. recursivelyMarkUsed(children[i], frameCount, lruCache);
  772. }
  773. }
  774. } // TODO: include frustum mask here?
  775. function determineFrustumSet(tile, renderer) {
  776. const stats = renderer.stats;
  777. const frameCount = renderer.frameCount;
  778. const errorTarget = renderer.errorTarget;
  779. const maxDepth = renderer.maxDepth;
  780. const loadSiblings = renderer.loadSiblings;
  781. const lruCache = renderer.lruCache;
  782. resetFrameState(tile, frameCount);
  783. const inFrustum = renderer.tileInView(tile);
  784. if (inFrustum === false) {
  785. return false;
  786. }
  787. tile.__used = true;
  788. lruCache.markUsed(tile);
  789. tile.__inFrustum = true;
  790. stats.inFrustum++;
  791. if (!tile.__contentEmpty) {
  792. const error = renderer.calculateError(tile);
  793. tile.__error = error;
  794. if (error <= errorTarget) {
  795. return true;
  796. }
  797. }
  798. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  799. return true;
  800. }
  801. let anyChildrenUsed = false;
  802. const children = tile.children;
  803. for (let i = 0, l = children.length; i < l; i++) {
  804. const c = children[i];
  805. const r = determineFrustumSet(c, renderer);
  806. anyChildrenUsed = anyChildrenUsed || r;
  807. }
  808. if (anyChildrenUsed && loadSiblings) {
  809. for (let i = 0, l = children.length; i < l; i++) {
  810. recursivelyMarkUsed(tile, frameCount, lruCache);
  811. }
  812. }
  813. return true;
  814. }
  815. function markUsedSetLeaves(tile, renderer) {
  816. const stats = renderer.stats;
  817. const frameCount = renderer.frameCount;
  818. if (!isUsedThisFrame(tile, frameCount)) {
  819. return;
  820. }
  821. stats.used++;
  822. const children = tile.children;
  823. let anyChildrenUsed = false;
  824. for (let i = 0, l = children.length; i < l; i++) {
  825. const c = children[i];
  826. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  827. }
  828. if (!anyChildrenUsed) {
  829. tile.__isLeaf = true; // TODO: stats
  830. } else {
  831. for (let i = 0, l = children.length; i < l; i++) {
  832. const c = children[i];
  833. markUsedSetLeaves(c, renderer);
  834. }
  835. }
  836. }
  837. function skipTraversal(tile, renderer) {
  838. const stats = renderer.stats;
  839. const frameCount = renderer.frameCount;
  840. if (!isUsedThisFrame(tile, frameCount)) {
  841. return;
  842. }
  843. const lruCache = renderer.lruCache;
  844. if (tile.__isLeaf) {
  845. if (tile.__loadingState === LOADED) {
  846. if (tile.__inFrustum) {
  847. tile.__visible = true;
  848. stats.visible++;
  849. }
  850. tile.__active = true;
  851. stats.active++;
  852. } else if (!lruCache.isFull()) {
  853. renderer.requestTileContents(tile);
  854. }
  855. return;
  856. }
  857. const errorRequirement = renderer.errorTarget * renderer.errorThreshold;
  858. const meetsSSE = tile.__error < errorRequirement;
  859. const hasContent = tile.__loadingState === LOADED && !tile.__contentEmpty;
  860. const children = tile.children;
  861. let allChildrenHaveContent = true;
  862. for (let i = 0, l = children.length; i < l; i++) {
  863. const c = children[i];
  864. if (isUsedThisFrame(c, frameCount)) {
  865. const childContent = c.__loadingState === LOADED || tile.__contentEmpty;
  866. allChildrenHaveContent = allChildrenHaveContent && childContent;
  867. }
  868. }
  869. if (meetsSSE && !hasContent && !lruCache.isFull()) {
  870. renderer.requestTileContents(tile);
  871. }
  872. if (meetsSSE && hasContent && !allChildrenHaveContent) {
  873. if (tile.__inFrustum) {
  874. tile.__visible = true;
  875. stats.visible++;
  876. }
  877. tile.__active = true;
  878. stats.active++;
  879. for (let i = 0, l = children.length; i < l; i++) {
  880. const c = children[i];
  881. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  882. renderer.requestTileContents(c);
  883. }
  884. }
  885. return;
  886. }
  887. for (let i = 0, l = children.length; i < l; i++) {
  888. const c = children[i];
  889. if (isUsedThisFrame(c, frameCount)) {
  890. skipTraversal(c, renderer);
  891. }
  892. }
  893. }
  894. function toggleTiles(tile, renderer) {
  895. const frameCount = renderer.frameCount;
  896. const isUsed = isUsedThisFrame(tile, frameCount);
  897. if (isUsed || tile.__usedLastFrame) {
  898. if (!isUsed) {
  899. if (!tile.__contentEmpty && tile.__loadingState === LOADED) {
  900. renderer.setTileVisible(tile, false);
  901. renderer.setTileActive(tile, false);
  902. }
  903. tile.__usedLastFrame = false;
  904. } else {
  905. if (!tile.__contentEmpty && tile.__loadingState === LOADED) {
  906. // enable visibility if active due to shadows
  907. renderer.setTileActive(tile, tile.__active);
  908. renderer.setTileVisible(tile, tile.__active || tile.__visible);
  909. }
  910. tile.__usedLastFrame = true;
  911. }
  912. const children = tile.children;
  913. for (let i = 0, l = children.length; i < l; i++) {
  914. const c = children[i];
  915. toggleTiles(c, renderer);
  916. }
  917. }
  918. }
  919. class TilesRenderer {
  920. get root() {
  921. return this.tileSets[this.rootSet].root;
  922. }
  923. constructor(url, cache = new _LRUCache.LRUCache(), downloadQueue = new _PriorityQueue.PriorityQueue(6), parseQueue = new _PriorityQueue.PriorityQueue(2)) {
  924. // state
  925. this.tileSets = {};
  926. this.rootSet = url;
  927. this.lruCache = cache;
  928. this.downloadQueue = downloadQueue;
  929. this.parseQueue = parseQueue;
  930. this.stats = {
  931. parsing: 0,
  932. downloading: 0,
  933. inFrustum: 0,
  934. used: 0,
  935. active: 0,
  936. visible: 0
  937. };
  938. this.frameCount = 0; // options
  939. this.errorTarget = 6.0;
  940. this.errorThreshold = 6.0;
  941. this.loadSiblings = true;
  942. this.maxDepth = Infinity;
  943. this.loadSiblings = true;
  944. this.loadTileSet(url);
  945. }
  946. traverse(cb) {
  947. const tileSets = this.tileSets;
  948. const rootTileSet = tileSets[this.rootSet];
  949. if (!rootTileSet.root) return;
  950. traverseSet(rootTileSet.root, cb);
  951. } // Public API
  952. update() {
  953. // TODO: Mark all tiles as unused
  954. // TODO: Check if any tiles have finished
  955. const stats = this.stats;
  956. const lruCache = this.lruCache;
  957. const tileSets = this.tileSets;
  958. const rootTileSet = tileSets[this.rootSet];
  959. if (!rootTileSet.root) return;
  960. const root = rootTileSet.root; // TODO: determine if the root tile should be visible / rendered?
  961. // TODO: Preprocess and modify the node uris instead of
  962. // generating the path on the fly
  963. // const errorTarget = this.errorTarget;
  964. // const errorThreshold = this.errorThreshold;
  965. // const maxDepth = this.maxDepth;
  966. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  967. determineFrustumSet(root, this);
  968. markUsedSetLeaves(root, this);
  969. skipTraversal(root, this);
  970. toggleTiles(root, this); // TODO: We may want to add this function in the requestTileContents function
  971. lruCache.scheduleUnload(null);
  972. } // Overrideable
  973. parseTile(buffer, tile) {
  974. return null;
  975. }
  976. disposeTile(tile) {}
  977. preprocessNode(tile, parentTile, tileSetDir) {
  978. if (tile.content) {
  979. if (!('uri' in tile.content) && 'url' in tile.content) {
  980. tile.content.uri = tile.content.url;
  981. delete tile.content.url;
  982. }
  983. if (tile.content.uri) {
  984. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  985. } // TODO: fix for some cases where tilesets provide the bounding volume
  986. // but volumes are not present. See
  987. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  988. delete tile.content.boundingVolume;
  989. }
  990. }
  991. tile.parent = parentTile;
  992. tile.__contentEmpty = !tile.content || !tile.content.uri;
  993. tile.__error = 0.0;
  994. tile.__inFrustum = false;
  995. tile.__isLeaf = false;
  996. tile.__wasUsed = false;
  997. tile.__used = false;
  998. tile.__wasVisible = false;
  999. tile.__visible = false;
  1000. tile.__wasActive = false;
  1001. tile.__active = false;
  1002. tile.__childrenActive = false;
  1003. tile.__loadingState = UNLOADED;
  1004. tile.__loadIndex = 0;
  1005. tile.__loadAbort = null;
  1006. if (parentTile === null) {
  1007. tile.__depth = 0;
  1008. } else {
  1009. tile.__depth = parentTile.__depth + 1;
  1010. }
  1011. }
  1012. setTileActive(tile, state) {}
  1013. setTileVisible(tile, state) {}
  1014. calculateError(tile) {
  1015. return 0;
  1016. }
  1017. tileInView(tile) {
  1018. return true;
  1019. } // Private Functions
  1020. loadTileSet(url) {
  1021. const tileSets = this.tileSets;
  1022. if (!(url in tileSets)) {
  1023. const pr = fetch(url, {
  1024. credentials: 'same-origin'
  1025. }).then(res => {
  1026. return res.json();
  1027. }).then(json => {
  1028. // TODO: Add version query?
  1029. const version = json.asset.version;
  1030. console.assert(version === '1.0' || version === '0.0');
  1031. const basePath = _path.default.dirname(url);
  1032. traverseSet(json.root, (node, parent) => this.preprocessNode(node, parent, basePath));
  1033. tileSets[url] = json;
  1034. return json;
  1035. });
  1036. pr.catch(e => {
  1037. console.error(`TilesLoader: Failed to load tile set json "${url}"`);
  1038. console.error(e);
  1039. delete tileSets[url];
  1040. });
  1041. tileSets[url] = pr;
  1042. }
  1043. return Promise.resolve(tileSets[url]);
  1044. }
  1045. requestTileContents(tile) {
  1046. // If the tile is already being loaded then don't
  1047. // start it again.
  1048. if (tile.__loadingState !== UNLOADED) {
  1049. return;
  1050. } // TODO: reuse the functions created here?
  1051. const lruCache = this.lruCache;
  1052. const downloadQueue = this.downloadQueue;
  1053. const parseQueue = this.parseQueue;
  1054. lruCache.add(tile, t => {
  1055. if (t.__loadingState === LOADING) {
  1056. t.__loadAbort.abort();
  1057. t.__loadAbort = null;
  1058. } else {
  1059. this.disposeTile(t);
  1060. }
  1061. if (t.__loadingState === LOADING) {
  1062. stats.downloading--;
  1063. } else if (t.__loadingState === PARSING) {
  1064. stats.parsing--;
  1065. }
  1066. t.__loadingState = UNLOADED;
  1067. t.__loadIndex++; // TODO: Removing from the queues here is slow
  1068. // parseQueue.remove( t );
  1069. // downloadQueue.remove( t );
  1070. });
  1071. tile.__loadIndex++;
  1072. const loadIndex = tile.__loadIndex;
  1073. const priority = 1 / (tile.__depth + 1);
  1074. const stats = this.stats;
  1075. const controller = new AbortController();
  1076. const signal = controller.signal;
  1077. stats.downloading++;
  1078. tile.__loadAbort = controller;
  1079. tile.__loadingState = LOADING;
  1080. downloadQueue.add(tile, priority, tile => {
  1081. if (tile.__loadIndex !== loadIndex) {
  1082. return Promise.resolve();
  1083. }
  1084. return fetch(tile.content.uri, {
  1085. credentials: 'same-origin',
  1086. signal
  1087. });
  1088. }).then(res => {
  1089. if (tile.__loadIndex !== loadIndex) {
  1090. return;
  1091. }
  1092. if (res.ok) {
  1093. return res.arrayBuffer();
  1094. } else {
  1095. throw new Error(`Failed to load model with error code ${res.status}`);
  1096. }
  1097. }).then(buffer => {
  1098. if (tile.__loadIndex !== loadIndex) {
  1099. return;
  1100. }
  1101. stats.downloading--;
  1102. stats.parsing++;
  1103. tile.__loadAbort = null;
  1104. tile.__loadingState = PARSING;
  1105. return parseQueue.add(buffer, priority, buffer => {
  1106. if (tile.__loadIndex !== loadIndex) {
  1107. return Promise.resolve();
  1108. }
  1109. return this.parseTile(buffer, tile);
  1110. });
  1111. }).then(() => {
  1112. if (tile.__loadIndex !== loadIndex) {
  1113. return;
  1114. }
  1115. stats.parsing--;
  1116. tile.__loadingState = LOADED;
  1117. this.setTileActive(tile, tile.__active);
  1118. this.setTileVisible(tile, tile.__visible);
  1119. }).catch(e => {
  1120. // if it has been unloaded then the tile has been disposed
  1121. if (tile.__loadIndex !== loadIndex) {
  1122. return;
  1123. }
  1124. if (e.name !== 'AbortError') {
  1125. console.error('TilesRenderer : Failed to load tile.');
  1126. console.error(e);
  1127. tile.__loadingState = FAILED;
  1128. } else {
  1129. lruCache.remove(tile);
  1130. }
  1131. });
  1132. }
  1133. }
  1134. exports.TilesRenderer = TilesRenderer;
  1135. },{"path":"../node_modules/path-browserify/index.js","./LRUCache.js":"../src/LRUCache.js","./PriorityQueue.js":"../src/PriorityQueue.js"}],"../src/B3DMLoader.js":[function(require,module,exports) {
  1136. "use strict";
  1137. Object.defineProperty(exports, "__esModule", {
  1138. value: true
  1139. });
  1140. exports.B3DMLoader = void 0;
  1141. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  1142. // convert an array of numbers to a string
  1143. function arrayToString(array) {
  1144. let str = '';
  1145. for (let i = 0, l = array.length; i < l; i++) {
  1146. str += String.fromCharCode(array[i]);
  1147. }
  1148. return str;
  1149. }
  1150. class B3DMLoader {
  1151. load(url) {
  1152. return fetch(url, {
  1153. credentials: 'same-origin'
  1154. }).then(res => res.arrayBuffer()).then(buffer => this.parse(buffer));
  1155. }
  1156. parse(buffer) {
  1157. const dataView = new DataView(buffer); // 28-byte header
  1158. // 4 bytes
  1159. const magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  1160. console.assert(magic === 'b3dm'); // 4 bytes
  1161. const version = dataView.getUint32(4, true);
  1162. console.assert(version === 1); // 4 bytes
  1163. const byteLength = dataView.getUint32(8, true);
  1164. console.assert(byteLength === buffer.byteLength); // 4 bytes
  1165. const featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  1166. const featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  1167. const batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  1168. const batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  1169. const featureTableStart = 28;
  1170. const jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  1171. const jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData));
  1172. const binFeatureTableData = new Uint8Array(buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength); // TODO: dereference the json feature table data in to the binary array.
  1173. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1174. // Batch Table
  1175. const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  1176. const jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  1177. const jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData));
  1178. const binBatchTableData = new Uint8Array(buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength); // TODO: dereference the json batch table data in to the binary array.
  1179. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  1180. const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  1181. const glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  1182. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  1183. return {
  1184. version,
  1185. featureTable: jsonFeatureTable,
  1186. batchTable: jsonBatchTable,
  1187. glbBytes
  1188. };
  1189. }
  1190. }
  1191. exports.B3DMLoader = B3DMLoader;
  1192. },{}],"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  1193. "use strict";
  1194. Object.defineProperty(exports, "__esModule", {
  1195. value: true
  1196. });
  1197. exports.AmbientLight = AmbientLight;
  1198. exports.AmbientLightProbe = AmbientLightProbe;
  1199. exports.AnimationClip = AnimationClip;
  1200. exports.AnimationLoader = AnimationLoader;
  1201. exports.AnimationMixer = AnimationMixer;
  1202. exports.AnimationObjectGroup = AnimationObjectGroup;
  1203. exports.ArcCurve = ArcCurve;
  1204. exports.ArrayCamera = ArrayCamera;
  1205. exports.ArrowHelper = ArrowHelper;
  1206. exports.Audio = Audio;
  1207. exports.AudioAnalyser = AudioAnalyser;
  1208. exports.AudioListener = AudioListener;
  1209. exports.AudioLoader = AudioLoader;
  1210. exports.AxesHelper = AxesHelper;
  1211. exports.AxisHelper = AxisHelper;
  1212. exports.BinaryTextureLoader = BinaryTextureLoader;
  1213. exports.Bone = Bone;
  1214. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  1215. exports.BoundingBoxHelper = BoundingBoxHelper;
  1216. exports.Box2 = Box2;
  1217. exports.Box3 = Box3;
  1218. exports.Box3Helper = Box3Helper;
  1219. exports.BoxHelper = BoxHelper;
  1220. exports.BufferAttribute = BufferAttribute;
  1221. exports.BufferGeometry = BufferGeometry;
  1222. exports.BufferGeometryLoader = BufferGeometryLoader;
  1223. exports.Camera = Camera;
  1224. exports.CameraHelper = CameraHelper;
  1225. exports.CanvasRenderer = CanvasRenderer;
  1226. exports.CanvasTexture = CanvasTexture;
  1227. exports.CatmullRomCurve3 = CatmullRomCurve3;
  1228. exports.CircleBufferGeometry = CircleBufferGeometry;
  1229. exports.CircleGeometry = CircleGeometry;
  1230. exports.Clock = Clock;
  1231. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  1232. exports.Color = Color;
  1233. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  1234. exports.CompressedTexture = CompressedTexture;
  1235. exports.CompressedTextureLoader = CompressedTextureLoader;
  1236. exports.ConeBufferGeometry = ConeBufferGeometry;
  1237. exports.ConeGeometry = ConeGeometry;
  1238. exports.CubeCamera = CubeCamera;
  1239. exports.CubeTexture = CubeTexture;
  1240. exports.CubeTextureLoader = CubeTextureLoader;
  1241. exports.CubicBezierCurve = CubicBezierCurve;
  1242. exports.CubicBezierCurve3 = CubicBezierCurve3;
  1243. exports.CubicInterpolant = CubicInterpolant;
  1244. exports.Curve = Curve;
  1245. exports.CurvePath = CurvePath;
  1246. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  1247. exports.CylinderGeometry = CylinderGeometry;
  1248. exports.Cylindrical = Cylindrical;
  1249. exports.DataTexture = DataTexture;
  1250. exports.DataTexture2DArray = DataTexture2DArray;
  1251. exports.DataTexture3D = DataTexture3D;
  1252. exports.DataTextureLoader = DataTextureLoader;
  1253. exports.DepthTexture = DepthTexture;
  1254. exports.DirectionalLight = DirectionalLight;
  1255. exports.DirectionalLightHelper = DirectionalLightHelper;
  1256. exports.DirectionalLightShadow = DirectionalLightShadow;
  1257. exports.DiscreteInterpolant = DiscreteInterpolant;
  1258. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  1259. exports.DodecahedronGeometry = DodecahedronGeometry;
  1260. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  1261. exports.EdgesGeometry = EdgesGeometry;
  1262. exports.EdgesHelper = EdgesHelper;
  1263. exports.EllipseCurve = EllipseCurve;
  1264. exports.Euler = Euler;
  1265. exports.EventDispatcher = EventDispatcher;
  1266. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  1267. exports.ExtrudeGeometry = ExtrudeGeometry;
  1268. exports.Face3 = Face3;
  1269. exports.Face4 = Face4;
  1270. exports.FaceNormalsHelper = FaceNormalsHelper;
  1271. exports.FileLoader = FileLoader;
  1272. exports.Float32Attribute = Float32Attribute;
  1273. exports.Float32BufferAttribute = Float32BufferAttribute;
  1274. exports.Float64Attribute = Float64Attribute;
  1275. exports.Float64BufferAttribute = Float64BufferAttribute;
  1276. exports.Fog = Fog;
  1277. exports.FogExp2 = FogExp2;
  1278. exports.Font = Font;
  1279. exports.FontLoader = FontLoader;
  1280. exports.Frustum = Frustum;
  1281. exports.Geometry = Geometry;
  1282. exports.GridHelper = GridHelper;
  1283. exports.Group = Group;
  1284. exports.HemisphereLight = HemisphereLight;
  1285. exports.HemisphereLightHelper = HemisphereLightHelper;
  1286. exports.HemisphereLightProbe = HemisphereLightProbe;
  1287. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  1288. exports.IcosahedronGeometry = IcosahedronGeometry;
  1289. exports.ImageBitmapLoader = ImageBitmapLoader;
  1290. exports.ImageLoader = ImageLoader;
  1291. exports.ImmediateRenderObject = ImmediateRenderObject;
  1292. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  1293. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  1294. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  1295. exports.InstancedMesh = InstancedMesh;
  1296. exports.Int16Attribute = Int16Attribute;
  1297. exports.Int16BufferAttribute = Int16BufferAttribute;
  1298. exports.Int32Attribute = Int32Attribute;
  1299. exports.Int32BufferAttribute = Int32BufferAttribute;
  1300. exports.Int8Attribute = Int8Attribute;
  1301. exports.Int8BufferAttribute = Int8BufferAttribute;
  1302. exports.InterleavedBuffer = InterleavedBuffer;
  1303. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  1304. exports.Interpolant = Interpolant;
  1305. exports.JSONLoader = JSONLoader;
  1306. exports.KeyframeTrack = KeyframeTrack;
  1307. exports.LOD = LOD;
  1308. exports.LatheBufferGeometry = LatheBufferGeometry;
  1309. exports.LatheGeometry = LatheGeometry;
  1310. exports.Layers = Layers;
  1311. exports.LensFlare = LensFlare;
  1312. exports.Light = Light;
  1313. exports.LightProbe = LightProbe;
  1314. exports.LightProbeHelper = LightProbeHelper;
  1315. exports.LightShadow = LightShadow;
  1316. exports.Line = Line;
  1317. exports.Line3 = Line3;
  1318. exports.LineBasicMaterial = LineBasicMaterial;
  1319. exports.LineCurve = LineCurve;
  1320. exports.LineCurve3 = LineCurve3;
  1321. exports.LineDashedMaterial = LineDashedMaterial;
  1322. exports.LineLoop = LineLoop;
  1323. exports.LineSegments = LineSegments;
  1324. exports.LinearInterpolant = LinearInterpolant;
  1325. exports.Loader = Loader;
  1326. exports.LoadingManager = LoadingManager;
  1327. exports.Material = Material;
  1328. exports.MaterialLoader = MaterialLoader;
  1329. exports.Matrix3 = Matrix3;
  1330. exports.Matrix4 = Matrix4;
  1331. exports.Mesh = Mesh;
  1332. exports.MeshBasicMaterial = MeshBasicMaterial;
  1333. exports.MeshDepthMaterial = MeshDepthMaterial;
  1334. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  1335. exports.MeshFaceMaterial = MeshFaceMaterial;
  1336. exports.MeshLambertMaterial = MeshLambertMaterial;
  1337. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  1338. exports.MeshNormalMaterial = MeshNormalMaterial;
  1339. exports.MeshPhongMaterial = MeshPhongMaterial;
  1340. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  1341. exports.MeshStandardMaterial = MeshStandardMaterial;
  1342. exports.MeshToonMaterial = MeshToonMaterial;
  1343. exports.MultiMaterial = MultiMaterial;
  1344. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  1345. exports.Object3D = Object3D;
  1346. exports.ObjectLoader = ObjectLoader;
  1347. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  1348. exports.OctahedronGeometry = OctahedronGeometry;
  1349. exports.OrthographicCamera = OrthographicCamera;
  1350. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  1351. exports.ParametricGeometry = ParametricGeometry;
  1352. exports.Particle = Particle;
  1353. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  1354. exports.ParticleSystem = ParticleSystem;
  1355. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  1356. exports.Path = Path;
  1357. exports.PerspectiveCamera = PerspectiveCamera;
  1358. exports.Plane = Plane;
  1359. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  1360. exports.PlaneGeometry = PlaneGeometry;
  1361. exports.PlaneHelper = PlaneHelper;
  1362. exports.PointCloud = PointCloud;
  1363. exports.PointCloudMaterial = PointCloudMaterial;
  1364. exports.PointLight = PointLight;
  1365. exports.PointLightHelper = PointLightHelper;
  1366. exports.Points = Points;
  1367. exports.PointsMaterial = PointsMaterial;
  1368. exports.PolarGridHelper = PolarGridHelper;
  1369. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  1370. exports.PolyhedronGeometry = PolyhedronGeometry;
  1371. exports.PositionalAudio = PositionalAudio;
  1372. exports.PositionalAudioHelper = PositionalAudioHelper;
  1373. exports.PropertyBinding = PropertyBinding;
  1374. exports.PropertyMixer = PropertyMixer;
  1375. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  1376. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  1377. exports.Quaternion = Quaternion;
  1378. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  1379. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  1380. exports.RawShaderMaterial = RawShaderMaterial;
  1381. exports.Ray = Ray;
  1382. exports.Raycaster = Raycaster;
  1383. exports.RectAreaLight = RectAreaLight;
  1384. exports.RectAreaLightHelper = RectAreaLightHelper;
  1385. exports.RingBufferGeometry = RingBufferGeometry;
  1386. exports.RingGeometry = RingGeometry;
  1387. exports.Scene = Scene;
  1388. exports.ShaderMaterial = ShaderMaterial;
  1389. exports.ShadowMaterial = ShadowMaterial;
  1390. exports.Shape = Shape;
  1391. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  1392. exports.ShapeGeometry = ShapeGeometry;
  1393. exports.ShapePath = ShapePath;
  1394. exports.Skeleton = Skeleton;
  1395. exports.SkeletonHelper = SkeletonHelper;
  1396. exports.SkinnedMesh = SkinnedMesh;
  1397. exports.Sphere = Sphere;
  1398. exports.SphereBufferGeometry = SphereBufferGeometry;
  1399. exports.SphereGeometry = SphereGeometry;
  1400. exports.Spherical = Spherical;
  1401. exports.SphericalHarmonics3 = SphericalHarmonics3;
  1402. exports.Spline = Spline;
  1403. exports.SplineCurve = SplineCurve;
  1404. exports.SplineCurve3 = SplineCurve3;
  1405. exports.SpotLight = SpotLight;
  1406. exports.SpotLightHelper = SpotLightHelper;
  1407. exports.SpotLightShadow = SpotLightShadow;
  1408. exports.Sprite = Sprite;
  1409. exports.SpriteMaterial = SpriteMaterial;
  1410. exports.StereoCamera = StereoCamera;
  1411. exports.StringKeyframeTrack = StringKeyframeTrack;
  1412. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  1413. exports.TetrahedronGeometry = TetrahedronGeometry;
  1414. exports.TextBufferGeometry = TextBufferGeometry;
  1415. exports.TextGeometry = TextGeometry;
  1416. exports.Texture = Texture;
  1417. exports.TextureLoader = TextureLoader;
  1418. exports.TorusBufferGeometry = TorusBufferGeometry;
  1419. exports.TorusGeometry = TorusGeometry;
  1420. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  1421. exports.TorusKnotGeometry = TorusKnotGeometry;
  1422. exports.Triangle = Triangle;
  1423. exports.TubeBufferGeometry = TubeBufferGeometry;
  1424. exports.TubeGeometry = TubeGeometry;
  1425. exports.Uint16Attribute = Uint16Attribute;
  1426. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  1427. exports.Uint32Attribute = Uint32Attribute;
  1428. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  1429. exports.Uint8Attribute = Uint8Attribute;
  1430. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  1431. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  1432. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  1433. exports.Uniform = Uniform;
  1434. exports.Vector2 = Vector2;
  1435. exports.Vector3 = Vector3;
  1436. exports.Vector4 = Vector4;
  1437. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  1438. exports.Vertex = Vertex;
  1439. exports.VertexNormalsHelper = VertexNormalsHelper;
  1440. exports.VideoTexture = VideoTexture;
  1441. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  1442. exports.WebGLRenderTarget = WebGLRenderTarget;
  1443. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  1444. exports.WebGLRenderer = WebGLRenderer;
  1445. exports.WebGLUtils = WebGLUtils;
  1446. exports.WireframeGeometry = WireframeGeometry;
  1447. exports.WireframeHelper = WireframeHelper;
  1448. exports.XHRLoader = XHRLoader;
  1449. 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;
  1450. 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;
  1451. // Polyfills
  1452. if (Number.EPSILON === undefined) {
  1453. Number.EPSILON = Math.pow(2, -52);
  1454. }
  1455. if (Number.isInteger === undefined) {
  1456. // Missing in IE
  1457. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  1458. Number.isInteger = function (value) {
  1459. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  1460. };
  1461. } //
  1462. if (Math.sign === undefined) {
  1463. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  1464. Math.sign = function (x) {
  1465. return x < 0 ? -1 : x > 0 ? 1 : +x;
  1466. };
  1467. }
  1468. if ('name' in Function.prototype === false) {
  1469. // Missing in IE
  1470. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  1471. Object.defineProperty(Function.prototype, 'name', {
  1472. get: function () {
  1473. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  1474. }
  1475. });
  1476. }
  1477. if (Object.assign === undefined) {
  1478. // Missing in IE
  1479. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  1480. Object.assign = function (target) {
  1481. if (target === undefined || target === null) {
  1482. throw new TypeError('Cannot convert undefined or null to object');
  1483. }
  1484. var output = Object(target);
  1485. for (var index = 1; index < arguments.length; index++) {
  1486. var source = arguments[index];
  1487. if (source !== undefined && source !== null) {
  1488. for (var nextKey in source) {
  1489. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  1490. output[nextKey] = source[nextKey];
  1491. }
  1492. }
  1493. }
  1494. }
  1495. return output;
  1496. };
  1497. }
  1498. var REVISION = '109';
  1499. exports.REVISION = REVISION;
  1500. var MOUSE = {
  1501. LEFT: 0,
  1502. MIDDLE: 1,
  1503. RIGHT: 2,
  1504. ROTATE: 0,
  1505. DOLLY: 1,
  1506. PAN: 2
  1507. };
  1508. exports.MOUSE = MOUSE;
  1509. var TOUCH = {
  1510. ROTATE: 0,
  1511. PAN: 1,
  1512. DOLLY_PAN: 2,
  1513. DOLLY_ROTATE: 3
  1514. };
  1515. exports.TOUCH = TOUCH;
  1516. var CullFaceNone = 0;
  1517. exports.CullFaceNone = CullFaceNone;
  1518. var CullFaceBack = 1;
  1519. exports.CullFaceBack = CullFaceBack;
  1520. var CullFaceFront = 2;
  1521. exports.CullFaceFront = CullFaceFront;
  1522. var CullFaceFrontBack = 3;
  1523. exports.CullFaceFrontBack = CullFaceFrontBack;
  1524. var FrontFaceDirectionCW = 0;
  1525. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  1526. var FrontFaceDirectionCCW = 1;
  1527. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  1528. var BasicShadowMap = 0;
  1529. exports.BasicShadowMap = BasicShadowMap;
  1530. var PCFShadowMap = 1;
  1531. exports.PCFShadowMap = PCFShadowMap;
  1532. var PCFSoftShadowMap = 2;
  1533. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  1534. var VSMShadowMap = 3;
  1535. exports.VSMShadowMap = VSMShadowMap;
  1536. var FrontSide = 0;
  1537. exports.FrontSide = FrontSide;
  1538. var BackSide = 1;
  1539. exports.BackSide = BackSide;
  1540. var DoubleSide = 2;
  1541. exports.DoubleSide = DoubleSide;
  1542. var FlatShading = 1;
  1543. exports.FlatShading = FlatShading;
  1544. var SmoothShading = 2;
  1545. exports.SmoothShading = SmoothShading;
  1546. var NoColors = 0;
  1547. exports.NoColors = NoColors;
  1548. var FaceColors = 1;
  1549. exports.FaceColors = FaceColors;
  1550. var VertexColors = 2;
  1551. exports.VertexColors = VertexColors;
  1552. var NoBlending = 0;
  1553. exports.NoBlending = NoBlending;
  1554. var NormalBlending = 1;
  1555. exports.NormalBlending = NormalBlending;
  1556. var AdditiveBlending = 2;
  1557. exports.AdditiveBlending = AdditiveBlending;
  1558. var SubtractiveBlending = 3;
  1559. exports.SubtractiveBlending = SubtractiveBlending;
  1560. var MultiplyBlending = 4;
  1561. exports.MultiplyBlending = MultiplyBlending;
  1562. var CustomBlending = 5;
  1563. exports.CustomBlending = CustomBlending;
  1564. var AddEquation = 100;
  1565. exports.AddEquation = AddEquation;
  1566. var SubtractEquation = 101;
  1567. exports.SubtractEquation = SubtractEquation;
  1568. var ReverseSubtractEquation = 102;
  1569. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  1570. var MinEquation = 103;
  1571. exports.MinEquation = MinEquation;
  1572. var MaxEquation = 104;
  1573. exports.MaxEquation = MaxEquation;
  1574. var ZeroFactor = 200;
  1575. exports.ZeroFactor = ZeroFactor;
  1576. var OneFactor = 201;
  1577. exports.OneFactor = OneFactor;
  1578. var SrcColorFactor = 202;
  1579. exports.SrcColorFactor = SrcColorFactor;
  1580. var OneMinusSrcColorFactor = 203;
  1581. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  1582. var SrcAlphaFactor = 204;
  1583. exports.SrcAlphaFactor = SrcAlphaFactor;
  1584. var OneMinusSrcAlphaFactor = 205;
  1585. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  1586. var DstAlphaFactor = 206;
  1587. exports.DstAlphaFactor = DstAlphaFactor;
  1588. var OneMinusDstAlphaFactor = 207;
  1589. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  1590. var DstColorFactor = 208;
  1591. exports.DstColorFactor = DstColorFactor;
  1592. var OneMinusDstColorFactor = 209;
  1593. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  1594. var SrcAlphaSaturateFactor = 210;
  1595. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  1596. var NeverDepth = 0;
  1597. exports.NeverDepth = NeverDepth;
  1598. var AlwaysDepth = 1;
  1599. exports.AlwaysDepth = AlwaysDepth;
  1600. var LessDepth = 2;
  1601. exports.LessDepth = LessDepth;
  1602. var LessEqualDepth = 3;
  1603. exports.LessEqualDepth = LessEqualDepth;
  1604. var EqualDepth = 4;
  1605. exports.EqualDepth = EqualDepth;
  1606. var GreaterEqualDepth = 5;
  1607. exports.GreaterEqualDepth = GreaterEqualDepth;
  1608. var GreaterDepth = 6;
  1609. exports.GreaterDepth = GreaterDepth;
  1610. var NotEqualDepth = 7;
  1611. exports.NotEqualDepth = NotEqualDepth;
  1612. var MultiplyOperation = 0;
  1613. exports.MultiplyOperation = MultiplyOperation;
  1614. var MixOperation = 1;
  1615. exports.MixOperation = MixOperation;
  1616. var AddOperation = 2;
  1617. exports.AddOperation = AddOperation;
  1618. var NoToneMapping = 0;
  1619. exports.NoToneMapping = NoToneMapping;
  1620. var LinearToneMapping = 1;
  1621. exports.LinearToneMapping = LinearToneMapping;
  1622. var ReinhardToneMapping = 2;
  1623. exports.ReinhardToneMapping = ReinhardToneMapping;
  1624. var Uncharted2ToneMapping = 3;
  1625. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  1626. var CineonToneMapping = 4;
  1627. exports.CineonToneMapping = CineonToneMapping;
  1628. var ACESFilmicToneMapping = 5;
  1629. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  1630. var UVMapping = 300;
  1631. exports.UVMapping = UVMapping;
  1632. var CubeReflectionMapping = 301;
  1633. exports.CubeReflectionMapping = CubeReflectionMapping;
  1634. var CubeRefractionMapping = 302;
  1635. exports.CubeRefractionMapping = CubeRefractionMapping;
  1636. var EquirectangularReflectionMapping = 303;
  1637. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  1638. var EquirectangularRefractionMapping = 304;
  1639. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  1640. var SphericalReflectionMapping = 305;
  1641. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  1642. var CubeUVReflectionMapping = 306;
  1643. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  1644. var CubeUVRefractionMapping = 307;
  1645. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  1646. var RepeatWrapping = 1000;
  1647. exports.RepeatWrapping = RepeatWrapping;
  1648. var ClampToEdgeWrapping = 1001;
  1649. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  1650. var MirroredRepeatWrapping = 1002;
  1651. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  1652. var NearestFilter = 1003;
  1653. exports.NearestFilter = NearestFilter;
  1654. var NearestMipmapNearestFilter = 1004;
  1655. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  1656. var NearestMipMapNearestFilter = 1004;
  1657. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  1658. var NearestMipmapLinearFilter = 1005;
  1659. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  1660. var NearestMipMapLinearFilter = 1005;
  1661. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  1662. var LinearFilter = 1006;
  1663. exports.LinearFilter = LinearFilter;
  1664. var LinearMipmapNearestFilter = 1007;
  1665. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  1666. var LinearMipMapNearestFilter = 1007;
  1667. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  1668. var LinearMipmapLinearFilter = 1008;
  1669. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  1670. var LinearMipMapLinearFilter = 1008;
  1671. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  1672. var UnsignedByteType = 1009;
  1673. exports.UnsignedByteType = UnsignedByteType;
  1674. var ByteType = 1010;
  1675. exports.ByteType = ByteType;
  1676. var ShortType = 1011;
  1677. exports.ShortType = ShortType;
  1678. var UnsignedShortType = 1012;
  1679. exports.UnsignedShortType = UnsignedShortType;
  1680. var IntType = 1013;
  1681. exports.IntType = IntType;
  1682. var UnsignedIntType = 1014;
  1683. exports.UnsignedIntType = UnsignedIntType;
  1684. var FloatType = 1015;
  1685. exports.FloatType = FloatType;
  1686. var HalfFloatType = 1016;
  1687. exports.HalfFloatType = HalfFloatType;
  1688. var UnsignedShort4444Type = 1017;
  1689. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  1690. var UnsignedShort5551Type = 1018;
  1691. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  1692. var UnsignedShort565Type = 1019;
  1693. exports.UnsignedShort565Type = UnsignedShort565Type;
  1694. var UnsignedInt248Type = 1020;
  1695. exports.UnsignedInt248Type = UnsignedInt248Type;
  1696. var AlphaFormat = 1021;
  1697. exports.AlphaFormat = AlphaFormat;
  1698. var RGBFormat = 1022;
  1699. exports.RGBFormat = RGBFormat;
  1700. var RGBAFormat = 1023;
  1701. exports.RGBAFormat = RGBAFormat;
  1702. var LuminanceFormat = 1024;
  1703. exports.LuminanceFormat = LuminanceFormat;
  1704. var LuminanceAlphaFormat = 1025;
  1705. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  1706. var RGBEFormat = RGBAFormat;
  1707. exports.RGBEFormat = RGBEFormat;
  1708. var DepthFormat = 1026;
  1709. exports.DepthFormat = DepthFormat;
  1710. var DepthStencilFormat = 1027;
  1711. exports.DepthStencilFormat = DepthStencilFormat;
  1712. var RedFormat = 1028;
  1713. exports.RedFormat = RedFormat;
  1714. var RGB_S3TC_DXT1_Format = 33776;
  1715. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  1716. var RGBA_S3TC_DXT1_Format = 33777;
  1717. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  1718. var RGBA_S3TC_DXT3_Format = 33778;
  1719. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  1720. var RGBA_S3TC_DXT5_Format = 33779;
  1721. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  1722. var RGB_PVRTC_4BPPV1_Format = 35840;
  1723. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  1724. var RGB_PVRTC_2BPPV1_Format = 35841;
  1725. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  1726. var RGBA_PVRTC_4BPPV1_Format = 35842;
  1727. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  1728. var RGBA_PVRTC_2BPPV1_Format = 35843;
  1729. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  1730. var RGB_ETC1_Format = 36196;
  1731. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  1732. var RGBA_ASTC_4x4_Format = 37808;
  1733. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  1734. var RGBA_ASTC_5x4_Format = 37809;
  1735. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  1736. var RGBA_ASTC_5x5_Format = 37810;
  1737. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  1738. var RGBA_ASTC_6x5_Format = 37811;
  1739. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  1740. var RGBA_ASTC_6x6_Format = 37812;
  1741. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  1742. var RGBA_ASTC_8x5_Format = 37813;
  1743. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  1744. var RGBA_ASTC_8x6_Format = 37814;
  1745. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  1746. var RGBA_ASTC_8x8_Format = 37815;
  1747. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  1748. var RGBA_ASTC_10x5_Format = 37816;
  1749. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  1750. var RGBA_ASTC_10x6_Format = 37817;
  1751. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  1752. var RGBA_ASTC_10x8_Format = 37818;
  1753. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  1754. var RGBA_ASTC_10x10_Format = 37819;
  1755. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  1756. var RGBA_ASTC_12x10_Format = 37820;
  1757. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  1758. var RGBA_ASTC_12x12_Format = 37821;
  1759. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  1760. var LoopOnce = 2200;
  1761. exports.LoopOnce = LoopOnce;
  1762. var LoopRepeat = 2201;
  1763. exports.LoopRepeat = LoopRepeat;
  1764. var LoopPingPong = 2202;
  1765. exports.LoopPingPong = LoopPingPong;
  1766. var InterpolateDiscrete = 2300;
  1767. exports.InterpolateDiscrete = InterpolateDiscrete;
  1768. var InterpolateLinear = 2301;
  1769. exports.InterpolateLinear = InterpolateLinear;
  1770. var InterpolateSmooth = 2302;
  1771. exports.InterpolateSmooth = InterpolateSmooth;
  1772. var ZeroCurvatureEnding = 2400;
  1773. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  1774. var ZeroSlopeEnding = 2401;
  1775. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  1776. var WrapAroundEnding = 2402;
  1777. exports.WrapAroundEnding = WrapAroundEnding;
  1778. var TrianglesDrawMode = 0;
  1779. exports.TrianglesDrawMode = TrianglesDrawMode;
  1780. var TriangleStripDrawMode = 1;
  1781. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  1782. var TriangleFanDrawMode = 2;
  1783. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  1784. var LinearEncoding = 3000;
  1785. exports.LinearEncoding = LinearEncoding;
  1786. var sRGBEncoding = 3001;
  1787. exports.sRGBEncoding = sRGBEncoding;
  1788. var GammaEncoding = 3007;
  1789. exports.GammaEncoding = GammaEncoding;
  1790. var RGBEEncoding = 3002;
  1791. exports.RGBEEncoding = RGBEEncoding;
  1792. var LogLuvEncoding = 3003;
  1793. exports.LogLuvEncoding = LogLuvEncoding;
  1794. var RGBM7Encoding = 3004;
  1795. exports.RGBM7Encoding = RGBM7Encoding;
  1796. var RGBM16Encoding = 3005;
  1797. exports.RGBM16Encoding = RGBM16Encoding;
  1798. var RGBDEncoding = 3006;
  1799. exports.RGBDEncoding = RGBDEncoding;
  1800. var BasicDepthPacking = 3200;
  1801. exports.BasicDepthPacking = BasicDepthPacking;
  1802. var RGBADepthPacking = 3201;
  1803. exports.RGBADepthPacking = RGBADepthPacking;
  1804. var TangentSpaceNormalMap = 0;
  1805. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  1806. var ObjectSpaceNormalMap = 1;
  1807. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  1808. var ZeroStencilOp = 0;
  1809. exports.ZeroStencilOp = ZeroStencilOp;
  1810. var KeepStencilOp = 7680;
  1811. exports.KeepStencilOp = KeepStencilOp;
  1812. var ReplaceStencilOp = 7681;
  1813. exports.ReplaceStencilOp = ReplaceStencilOp;
  1814. var IncrementStencilOp = 7682;
  1815. exports.IncrementStencilOp = IncrementStencilOp;
  1816. var DecrementStencilOp = 7683;
  1817. exports.DecrementStencilOp = DecrementStencilOp;
  1818. var IncrementWrapStencilOp = 34055;
  1819. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  1820. var DecrementWrapStencilOp = 34056;
  1821. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  1822. var InvertStencilOp = 5386;
  1823. exports.InvertStencilOp = InvertStencilOp;
  1824. var NeverStencilFunc = 512;
  1825. exports.NeverStencilFunc = NeverStencilFunc;
  1826. var LessStencilFunc = 513;
  1827. exports.LessStencilFunc = LessStencilFunc;
  1828. var EqualStencilFunc = 514;
  1829. exports.EqualStencilFunc = EqualStencilFunc;
  1830. var LessEqualStencilFunc = 515;
  1831. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  1832. var GreaterStencilFunc = 516;
  1833. exports.GreaterStencilFunc = GreaterStencilFunc;
  1834. var NotEqualStencilFunc = 517;
  1835. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  1836. var GreaterEqualStencilFunc = 518;
  1837. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  1838. var AlwaysStencilFunc = 519;
  1839. /**
  1840. * https://github.com/mrdoob/eventdispatcher.js/
  1841. */
  1842. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  1843. function EventDispatcher() {}
  1844. Object.assign(EventDispatcher.prototype, {
  1845. addEventListener: function (type, listener) {
  1846. if (this._listeners === undefined) this._listeners = {};
  1847. var listeners = this._listeners;
  1848. if (listeners[type] === undefined) {
  1849. listeners[type] = [];
  1850. }
  1851. if (listeners[type].indexOf(listener) === -1) {
  1852. listeners[type].push(listener);
  1853. }
  1854. },
  1855. hasEventListener: function (type, listener) {
  1856. if (this._listeners === undefined) return false;
  1857. var listeners = this._listeners;
  1858. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  1859. },
  1860. removeEventListener: function (type, listener) {
  1861. if (this._listeners === undefined) return;
  1862. var listeners = this._listeners;
  1863. var listenerArray = listeners[type];
  1864. if (listenerArray !== undefined) {
  1865. var index = listenerArray.indexOf(listener);
  1866. if (index !== -1) {
  1867. listenerArray.splice(index, 1);
  1868. }
  1869. }
  1870. },
  1871. dispatchEvent: function (event) {
  1872. if (this._listeners === undefined) return;
  1873. var listeners = this._listeners;
  1874. var listenerArray = listeners[event.type];
  1875. if (listenerArray !== undefined) {
  1876. event.target = this;
  1877. var array = listenerArray.slice(0);
  1878. for (var i = 0, l = array.length; i < l; i++) {
  1879. array[i].call(this, event);
  1880. }
  1881. }
  1882. }
  1883. });
  1884. /**
  1885. * @author alteredq / http://alteredqualia.com/
  1886. * @author mrdoob / http://mrdoob.com/
  1887. */
  1888. var _lut = [];
  1889. for (var i = 0; i < 256; i++) {
  1890. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  1891. }
  1892. var _Math = {
  1893. DEG2RAD: Math.PI / 180,
  1894. RAD2DEG: 180 / Math.PI,
  1895. generateUUID: function () {
  1896. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1897. var d0 = Math.random() * 0xffffffff | 0;
  1898. var d1 = Math.random() * 0xffffffff | 0;
  1899. var d2 = Math.random() * 0xffffffff | 0;
  1900. var d3 = Math.random() * 0xffffffff | 0;
  1901. 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.
  1902. return uuid.toUpperCase();
  1903. },
  1904. clamp: function (value, min, max) {
  1905. return Math.max(min, Math.min(max, value));
  1906. },
  1907. // compute euclidian modulo of m % n
  1908. // https://en.wikipedia.org/wiki/Modulo_operation
  1909. euclideanModulo: function (n, m) {
  1910. return (n % m + m) % m;
  1911. },
  1912. // Linear mapping from range <a1, a2> to range <b1, b2>
  1913. mapLinear: function (x, a1, a2, b1, b2) {
  1914. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  1915. },
  1916. // https://en.wikipedia.org/wiki/Linear_interpolation
  1917. lerp: function (x, y, t) {
  1918. return (1 - t) * x + t * y;
  1919. },
  1920. // http://en.wikipedia.org/wiki/Smoothstep
  1921. smoothstep: function (x, min, max) {
  1922. if (x <= min) return 0;
  1923. if (x >= max) return 1;
  1924. x = (x - min) / (max - min);
  1925. return x * x * (3 - 2 * x);
  1926. },
  1927. smootherstep: function (x, min, max) {
  1928. if (x <= min) return 0;
  1929. if (x >= max) return 1;
  1930. x = (x - min) / (max - min);
  1931. return x * x * x * (x * (x * 6 - 15) + 10);
  1932. },
  1933. // Random integer from <low, high> interval
  1934. randInt: function (low, high) {
  1935. return low + Math.floor(Math.random() * (high - low + 1));
  1936. },
  1937. // Random float from <low, high> interval
  1938. randFloat: function (low, high) {
  1939. return low + Math.random() * (high - low);
  1940. },
  1941. // Random float from <-range/2, range/2> interval
  1942. randFloatSpread: function (range) {
  1943. return range * (0.5 - Math.random());
  1944. },
  1945. degToRad: function (degrees) {
  1946. return degrees * _Math.DEG2RAD;
  1947. },
  1948. radToDeg: function (radians) {
  1949. return radians * _Math.RAD2DEG;
  1950. },
  1951. isPowerOfTwo: function (value) {
  1952. return (value & value - 1) === 0 && value !== 0;
  1953. },
  1954. ceilPowerOfTwo: function (value) {
  1955. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  1956. },
  1957. floorPowerOfTwo: function (value) {
  1958. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  1959. }
  1960. };
  1961. /**
  1962. * @author mrdoob / http://mrdoob.com/
  1963. * @author philogb / http://blog.thejit.org/
  1964. * @author egraether / http://egraether.com/
  1965. * @author zz85 / http://www.lab4games.net/zz85/blog
  1966. */
  1967. exports.Math = _Math;
  1968. function Vector2(x, y) {
  1969. this.x = x || 0;
  1970. this.y = y || 0;
  1971. }
  1972. Object.defineProperties(Vector2.prototype, {
  1973. "width": {
  1974. get: function () {
  1975. return this.x;
  1976. },
  1977. set: function (value) {
  1978. this.x = value;
  1979. }
  1980. },
  1981. "height": {
  1982. get: function () {
  1983. return this.y;
  1984. },
  1985. set: function (value) {
  1986. this.y = value;
  1987. }
  1988. }
  1989. });
  1990. Object.assign(Vector2.prototype, {
  1991. isVector2: true,
  1992. set: function (x, y) {
  1993. this.x = x;
  1994. this.y = y;
  1995. return this;
  1996. },
  1997. setScalar: function (scalar) {
  1998. this.x = scalar;
  1999. this.y = scalar;
  2000. return this;
  2001. },
  2002. setX: function (x) {
  2003. this.x = x;
  2004. return this;
  2005. },
  2006. setY: function (y) {
  2007. this.y = y;
  2008. return this;
  2009. },
  2010. setComponent: function (index, value) {
  2011. switch (index) {
  2012. case 0:
  2013. this.x = value;
  2014. break;
  2015. case 1:
  2016. this.y = value;
  2017. break;
  2018. default:
  2019. throw new Error('index is out of range: ' + index);
  2020. }
  2021. return this;
  2022. },
  2023. getComponent: function (index) {
  2024. switch (index) {
  2025. case 0:
  2026. return this.x;
  2027. case 1:
  2028. return this.y;
  2029. default:
  2030. throw new Error('index is out of range: ' + index);
  2031. }
  2032. },
  2033. clone: function () {
  2034. return new this.constructor(this.x, this.y);
  2035. },
  2036. copy: function (v) {
  2037. this.x = v.x;
  2038. this.y = v.y;
  2039. return this;
  2040. },
  2041. add: function (v, w) {
  2042. if (w !== undefined) {
  2043. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2044. return this.addVectors(v, w);
  2045. }
  2046. this.x += v.x;
  2047. this.y += v.y;
  2048. return this;
  2049. },
  2050. addScalar: function (s) {
  2051. this.x += s;
  2052. this.y += s;
  2053. return this;
  2054. },
  2055. addVectors: function (a, b) {
  2056. this.x = a.x + b.x;
  2057. this.y = a.y + b.y;
  2058. return this;
  2059. },
  2060. addScaledVector: function (v, s) {
  2061. this.x += v.x * s;
  2062. this.y += v.y * s;
  2063. return this;
  2064. },
  2065. sub: function (v, w) {
  2066. if (w !== undefined) {
  2067. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2068. return this.subVectors(v, w);
  2069. }
  2070. this.x -= v.x;
  2071. this.y -= v.y;
  2072. return this;
  2073. },
  2074. subScalar: function (s) {
  2075. this.x -= s;
  2076. this.y -= s;
  2077. return this;
  2078. },
  2079. subVectors: function (a, b) {
  2080. this.x = a.x - b.x;
  2081. this.y = a.y - b.y;
  2082. return this;
  2083. },
  2084. multiply: function (v) {
  2085. this.x *= v.x;
  2086. this.y *= v.y;
  2087. return this;
  2088. },
  2089. multiplyScalar: function (scalar) {
  2090. this.x *= scalar;
  2091. this.y *= scalar;
  2092. return this;
  2093. },
  2094. divide: function (v) {
  2095. this.x /= v.x;
  2096. this.y /= v.y;
  2097. return this;
  2098. },
  2099. divideScalar: function (scalar) {
  2100. return this.multiplyScalar(1 / scalar);
  2101. },
  2102. applyMatrix3: function (m) {
  2103. var x = this.x,
  2104. y = this.y;
  2105. var e = m.elements;
  2106. this.x = e[0] * x + e[3] * y + e[6];
  2107. this.y = e[1] * x + e[4] * y + e[7];
  2108. return this;
  2109. },
  2110. min: function (v) {
  2111. this.x = Math.min(this.x, v.x);
  2112. this.y = Math.min(this.y, v.y);
  2113. return this;
  2114. },
  2115. max: function (v) {
  2116. this.x = Math.max(this.x, v.x);
  2117. this.y = Math.max(this.y, v.y);
  2118. return this;
  2119. },
  2120. clamp: function (min, max) {
  2121. // assumes min < max, componentwise
  2122. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2123. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2124. return this;
  2125. },
  2126. clampScalar: function (minVal, maxVal) {
  2127. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2128. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2129. return this;
  2130. },
  2131. clampLength: function (min, max) {
  2132. var length = this.length();
  2133. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2134. },
  2135. floor: function () {
  2136. this.x = Math.floor(this.x);
  2137. this.y = Math.floor(this.y);
  2138. return this;
  2139. },
  2140. ceil: function () {
  2141. this.x = Math.ceil(this.x);
  2142. this.y = Math.ceil(this.y);
  2143. return this;
  2144. },
  2145. round: function () {
  2146. this.x = Math.round(this.x);
  2147. this.y = Math.round(this.y);
  2148. return this;
  2149. },
  2150. roundToZero: function () {
  2151. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2152. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2153. return this;
  2154. },
  2155. negate: function () {
  2156. this.x = -this.x;
  2157. this.y = -this.y;
  2158. return this;
  2159. },
  2160. dot: function (v) {
  2161. return this.x * v.x + this.y * v.y;
  2162. },
  2163. cross: function (v) {
  2164. return this.x * v.y - this.y * v.x;
  2165. },
  2166. lengthSq: function () {
  2167. return this.x * this.x + this.y * this.y;
  2168. },
  2169. length: function () {
  2170. return Math.sqrt(this.x * this.x + this.y * this.y);
  2171. },
  2172. manhattanLength: function () {
  2173. return Math.abs(this.x) + Math.abs(this.y);
  2174. },
  2175. normalize: function () {
  2176. return this.divideScalar(this.length() || 1);
  2177. },
  2178. angle: function () {
  2179. // computes the angle in radians with respect to the positive x-axis
  2180. var angle = Math.atan2(this.y, this.x);
  2181. if (angle < 0) angle += 2 * Math.PI;
  2182. return angle;
  2183. },
  2184. distanceTo: function (v) {
  2185. return Math.sqrt(this.distanceToSquared(v));
  2186. },
  2187. distanceToSquared: function (v) {
  2188. var dx = this.x - v.x,
  2189. dy = this.y - v.y;
  2190. return dx * dx + dy * dy;
  2191. },
  2192. manhattanDistanceTo: function (v) {
  2193. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  2194. },
  2195. setLength: function (length) {
  2196. return this.normalize().multiplyScalar(length);
  2197. },
  2198. lerp: function (v, alpha) {
  2199. this.x += (v.x - this.x) * alpha;
  2200. this.y += (v.y - this.y) * alpha;
  2201. return this;
  2202. },
  2203. lerpVectors: function (v1, v2, alpha) {
  2204. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2205. },
  2206. equals: function (v) {
  2207. return v.x === this.x && v.y === this.y;
  2208. },
  2209. fromArray: function (array, offset) {
  2210. if (offset === undefined) offset = 0;
  2211. this.x = array[offset];
  2212. this.y = array[offset + 1];
  2213. return this;
  2214. },
  2215. toArray: function (array, offset) {
  2216. if (array === undefined) array = [];
  2217. if (offset === undefined) offset = 0;
  2218. array[offset] = this.x;
  2219. array[offset + 1] = this.y;
  2220. return array;
  2221. },
  2222. fromBufferAttribute: function (attribute, index, offset) {
  2223. if (offset !== undefined) {
  2224. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  2225. }
  2226. this.x = attribute.getX(index);
  2227. this.y = attribute.getY(index);
  2228. return this;
  2229. },
  2230. rotateAround: function (center, angle) {
  2231. var c = Math.cos(angle),
  2232. s = Math.sin(angle);
  2233. var x = this.x - center.x;
  2234. var y = this.y - center.y;
  2235. this.x = x * c - y * s + center.x;
  2236. this.y = x * s + y * c + center.y;
  2237. return this;
  2238. }
  2239. });
  2240. /**
  2241. * @author mikael emtinger / http://gomo.se/
  2242. * @author alteredq / http://alteredqualia.com/
  2243. * @author WestLangley / http://github.com/WestLangley
  2244. * @author bhouston / http://clara.io
  2245. */
  2246. function Quaternion(x, y, z, w) {
  2247. this._x = x || 0;
  2248. this._y = y || 0;
  2249. this._z = z || 0;
  2250. this._w = w !== undefined ? w : 1;
  2251. }
  2252. Object.assign(Quaternion, {
  2253. slerp: function (qa, qb, qm, t) {
  2254. return qm.copy(qa).slerp(qb, t);
  2255. },
  2256. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2257. // fuzz-free, array-based Quaternion SLERP operation
  2258. var x0 = src0[srcOffset0 + 0],
  2259. y0 = src0[srcOffset0 + 1],
  2260. z0 = src0[srcOffset0 + 2],
  2261. w0 = src0[srcOffset0 + 3],
  2262. x1 = src1[srcOffset1 + 0],
  2263. y1 = src1[srcOffset1 + 1],
  2264. z1 = src1[srcOffset1 + 2],
  2265. w1 = src1[srcOffset1 + 3];
  2266. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2267. var s = 1 - t,
  2268. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2269. dir = cos >= 0 ? 1 : -1,
  2270. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2271. if (sqrSin > Number.EPSILON) {
  2272. var sin = Math.sqrt(sqrSin),
  2273. len = Math.atan2(sin, cos * dir);
  2274. s = Math.sin(s * len) / sin;
  2275. t = Math.sin(t * len) / sin;
  2276. }
  2277. var tDir = t * dir;
  2278. x0 = x0 * s + x1 * tDir;
  2279. y0 = y0 * s + y1 * tDir;
  2280. z0 = z0 * s + z1 * tDir;
  2281. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2282. if (s === 1 - t) {
  2283. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2284. x0 *= f;
  2285. y0 *= f;
  2286. z0 *= f;
  2287. w0 *= f;
  2288. }
  2289. }
  2290. dst[dstOffset] = x0;
  2291. dst[dstOffset + 1] = y0;
  2292. dst[dstOffset + 2] = z0;
  2293. dst[dstOffset + 3] = w0;
  2294. }
  2295. });
  2296. Object.defineProperties(Quaternion.prototype, {
  2297. x: {
  2298. get: function () {
  2299. return this._x;
  2300. },
  2301. set: function (value) {
  2302. this._x = value;
  2303. this._onChangeCallback();
  2304. }
  2305. },
  2306. y: {
  2307. get: function () {
  2308. return this._y;
  2309. },
  2310. set: function (value) {
  2311. this._y = value;
  2312. this._onChangeCallback();
  2313. }
  2314. },
  2315. z: {
  2316. get: function () {
  2317. return this._z;
  2318. },
  2319. set: function (value) {
  2320. this._z = value;
  2321. this._onChangeCallback();
  2322. }
  2323. },
  2324. w: {
  2325. get: function () {
  2326. return this._w;
  2327. },
  2328. set: function (value) {
  2329. this._w = value;
  2330. this._onChangeCallback();
  2331. }
  2332. }
  2333. });
  2334. Object.assign(Quaternion.prototype, {
  2335. isQuaternion: true,
  2336. set: function (x, y, z, w) {
  2337. this._x = x;
  2338. this._y = y;
  2339. this._z = z;
  2340. this._w = w;
  2341. this._onChangeCallback();
  2342. return this;
  2343. },
  2344. clone: function () {
  2345. return new this.constructor(this._x, this._y, this._z, this._w);
  2346. },
  2347. copy: function (quaternion) {
  2348. this._x = quaternion.x;
  2349. this._y = quaternion.y;
  2350. this._z = quaternion.z;
  2351. this._w = quaternion.w;
  2352. this._onChangeCallback();
  2353. return this;
  2354. },
  2355. setFromEuler: function (euler, update) {
  2356. if (!(euler && euler.isEuler)) {
  2357. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2358. }
  2359. var x = euler._x,
  2360. y = euler._y,
  2361. z = euler._z,
  2362. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2363. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2364. // content/SpinCalc.m
  2365. var cos = Math.cos;
  2366. var sin = Math.sin;
  2367. var c1 = cos(x / 2);
  2368. var c2 = cos(y / 2);
  2369. var c3 = cos(z / 2);
  2370. var s1 = sin(x / 2);
  2371. var s2 = sin(y / 2);
  2372. var s3 = sin(z / 2);
  2373. if (order === 'XYZ') {
  2374. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2375. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2376. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2377. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2378. } else if (order === 'YXZ') {
  2379. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2380. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2381. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2382. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2383. } else if (order === 'ZXY') {
  2384. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2385. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2386. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2387. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2388. } else if (order === 'ZYX') {
  2389. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2390. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2391. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2392. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2393. } else if (order === 'YZX') {
  2394. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2395. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2396. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2397. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2398. } else if (order === 'XZY') {
  2399. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2400. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2401. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2402. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2403. }
  2404. if (update !== false) this._onChangeCallback();
  2405. return this;
  2406. },
  2407. setFromAxisAngle: function (axis, angle) {
  2408. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2409. // assumes axis is normalized
  2410. var halfAngle = angle / 2,
  2411. s = Math.sin(halfAngle);
  2412. this._x = axis.x * s;
  2413. this._y = axis.y * s;
  2414. this._z = axis.z * s;
  2415. this._w = Math.cos(halfAngle);
  2416. this._onChangeCallback();
  2417. return this;
  2418. },
  2419. setFromRotationMatrix: function (m) {
  2420. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2421. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2422. var te = m.elements,
  2423. m11 = te[0],
  2424. m12 = te[4],
  2425. m13 = te[8],
  2426. m21 = te[1],
  2427. m22 = te[5],
  2428. m23 = te[9],
  2429. m31 = te[2],
  2430. m32 = te[6],
  2431. m33 = te[10],
  2432. trace = m11 + m22 + m33,
  2433. s;
  2434. if (trace > 0) {
  2435. s = 0.5 / Math.sqrt(trace + 1.0);
  2436. this._w = 0.25 / s;
  2437. this._x = (m32 - m23) * s;
  2438. this._y = (m13 - m31) * s;
  2439. this._z = (m21 - m12) * s;
  2440. } else if (m11 > m22 && m11 > m33) {
  2441. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2442. this._w = (m32 - m23) / s;
  2443. this._x = 0.25 * s;
  2444. this._y = (m12 + m21) / s;
  2445. this._z = (m13 + m31) / s;
  2446. } else if (m22 > m33) {
  2447. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2448. this._w = (m13 - m31) / s;
  2449. this._x = (m12 + m21) / s;
  2450. this._y = 0.25 * s;
  2451. this._z = (m23 + m32) / s;
  2452. } else {
  2453. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2454. this._w = (m21 - m12) / s;
  2455. this._x = (m13 + m31) / s;
  2456. this._y = (m23 + m32) / s;
  2457. this._z = 0.25 * s;
  2458. }
  2459. this._onChangeCallback();
  2460. return this;
  2461. },
  2462. setFromUnitVectors: function (vFrom, vTo) {
  2463. // assumes direction vectors vFrom and vTo are normalized
  2464. var EPS = 0.000001;
  2465. var r = vFrom.dot(vTo) + 1;
  2466. if (r < EPS) {
  2467. r = 0;
  2468. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2469. this._x = -vFrom.y;
  2470. this._y = vFrom.x;
  2471. this._z = 0;
  2472. this._w = r;
  2473. } else {
  2474. this._x = 0;
  2475. this._y = -vFrom.z;
  2476. this._z = vFrom.y;
  2477. this._w = r;
  2478. }
  2479. } else {
  2480. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2481. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2482. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2483. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2484. this._w = r;
  2485. }
  2486. return this.normalize();
  2487. },
  2488. angleTo: function (q) {
  2489. return 2 * Math.acos(Math.abs(_Math.clamp(this.dot(q), -1, 1)));
  2490. },
  2491. rotateTowards: function (q, step) {
  2492. var angle = this.angleTo(q);
  2493. if (angle === 0) return this;
  2494. var t = Math.min(1, step / angle);
  2495. this.slerp(q, t);
  2496. return this;
  2497. },
  2498. inverse: function () {
  2499. // quaternion is assumed to have unit length
  2500. return this.conjugate();
  2501. },
  2502. conjugate: function () {
  2503. this._x *= -1;
  2504. this._y *= -1;
  2505. this._z *= -1;
  2506. this._onChangeCallback();
  2507. return this;
  2508. },
  2509. dot: function (v) {
  2510. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2511. },
  2512. lengthSq: function () {
  2513. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2514. },
  2515. length: function () {
  2516. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2517. },
  2518. normalize: function () {
  2519. var l = this.length();
  2520. if (l === 0) {
  2521. this._x = 0;
  2522. this._y = 0;
  2523. this._z = 0;
  2524. this._w = 1;
  2525. } else {
  2526. l = 1 / l;
  2527. this._x = this._x * l;
  2528. this._y = this._y * l;
  2529. this._z = this._z * l;
  2530. this._w = this._w * l;
  2531. }
  2532. this._onChangeCallback();
  2533. return this;
  2534. },
  2535. multiply: function (q, p) {
  2536. if (p !== undefined) {
  2537. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2538. return this.multiplyQuaternions(q, p);
  2539. }
  2540. return this.multiplyQuaternions(this, q);
  2541. },
  2542. premultiply: function (q) {
  2543. return this.multiplyQuaternions(q, this);
  2544. },
  2545. multiplyQuaternions: function (a, b) {
  2546. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2547. var qax = a._x,
  2548. qay = a._y,
  2549. qaz = a._z,
  2550. qaw = a._w;
  2551. var qbx = b._x,
  2552. qby = b._y,
  2553. qbz = b._z,
  2554. qbw = b._w;
  2555. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2556. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2557. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2558. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2559. this._onChangeCallback();
  2560. return this;
  2561. },
  2562. slerp: function (qb, t) {
  2563. if (t === 0) return this;
  2564. if (t === 1) return this.copy(qb);
  2565. var x = this._x,
  2566. y = this._y,
  2567. z = this._z,
  2568. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2569. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2570. if (cosHalfTheta < 0) {
  2571. this._w = -qb._w;
  2572. this._x = -qb._x;
  2573. this._y = -qb._y;
  2574. this._z = -qb._z;
  2575. cosHalfTheta = -cosHalfTheta;
  2576. } else {
  2577. this.copy(qb);
  2578. }
  2579. if (cosHalfTheta >= 1.0) {
  2580. this._w = w;
  2581. this._x = x;
  2582. this._y = y;
  2583. this._z = z;
  2584. return this;
  2585. }
  2586. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2587. if (sqrSinHalfTheta <= Number.EPSILON) {
  2588. var s = 1 - t;
  2589. this._w = s * w + t * this._w;
  2590. this._x = s * x + t * this._x;
  2591. this._y = s * y + t * this._y;
  2592. this._z = s * z + t * this._z;
  2593. this.normalize();
  2594. this._onChangeCallback();
  2595. return this;
  2596. }
  2597. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2598. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2599. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2600. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2601. this._w = w * ratioA + this._w * ratioB;
  2602. this._x = x * ratioA + this._x * ratioB;
  2603. this._y = y * ratioA + this._y * ratioB;
  2604. this._z = z * ratioA + this._z * ratioB;
  2605. this._onChangeCallback();
  2606. return this;
  2607. },
  2608. equals: function (quaternion) {
  2609. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2610. },
  2611. fromArray: function (array, offset) {
  2612. if (offset === undefined) offset = 0;
  2613. this._x = array[offset];
  2614. this._y = array[offset + 1];
  2615. this._z = array[offset + 2];
  2616. this._w = array[offset + 3];
  2617. this._onChangeCallback();
  2618. return this;
  2619. },
  2620. toArray: function (array, offset) {
  2621. if (array === undefined) array = [];
  2622. if (offset === undefined) offset = 0;
  2623. array[offset] = this._x;
  2624. array[offset + 1] = this._y;
  2625. array[offset + 2] = this._z;
  2626. array[offset + 3] = this._w;
  2627. return array;
  2628. },
  2629. _onChange: function (callback) {
  2630. this._onChangeCallback = callback;
  2631. return this;
  2632. },
  2633. _onChangeCallback: function () {}
  2634. });
  2635. /**
  2636. * @author mrdoob / http://mrdoob.com/
  2637. * @author kile / http://kile.stravaganza.org/
  2638. * @author philogb / http://blog.thejit.org/
  2639. * @author mikael emtinger / http://gomo.se/
  2640. * @author egraether / http://egraether.com/
  2641. * @author WestLangley / http://github.com/WestLangley
  2642. */
  2643. var _vector = new Vector3();
  2644. var _quaternion = new Quaternion();
  2645. function Vector3(x, y, z) {
  2646. this.x = x || 0;
  2647. this.y = y || 0;
  2648. this.z = z || 0;
  2649. }
  2650. Object.assign(Vector3.prototype, {
  2651. isVector3: true,
  2652. set: function (x, y, z) {
  2653. this.x = x;
  2654. this.y = y;
  2655. this.z = z;
  2656. return this;
  2657. },
  2658. setScalar: function (scalar) {
  2659. this.x = scalar;
  2660. this.y = scalar;
  2661. this.z = scalar;
  2662. return this;
  2663. },
  2664. setX: function (x) {
  2665. this.x = x;
  2666. return this;
  2667. },
  2668. setY: function (y) {
  2669. this.y = y;
  2670. return this;
  2671. },
  2672. setZ: function (z) {
  2673. this.z = z;
  2674. return this;
  2675. },
  2676. setComponent: function (index, value) {
  2677. switch (index) {
  2678. case 0:
  2679. this.x = value;
  2680. break;
  2681. case 1:
  2682. this.y = value;
  2683. break;
  2684. case 2:
  2685. this.z = value;
  2686. break;
  2687. default:
  2688. throw new Error('index is out of range: ' + index);
  2689. }
  2690. return this;
  2691. },
  2692. getComponent: function (index) {
  2693. switch (index) {
  2694. case 0:
  2695. return this.x;
  2696. case 1:
  2697. return this.y;
  2698. case 2:
  2699. return this.z;
  2700. default:
  2701. throw new Error('index is out of range: ' + index);
  2702. }
  2703. },
  2704. clone: function () {
  2705. return new this.constructor(this.x, this.y, this.z);
  2706. },
  2707. copy: function (v) {
  2708. this.x = v.x;
  2709. this.y = v.y;
  2710. this.z = v.z;
  2711. return this;
  2712. },
  2713. add: function (v, w) {
  2714. if (w !== undefined) {
  2715. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2716. return this.addVectors(v, w);
  2717. }
  2718. this.x += v.x;
  2719. this.y += v.y;
  2720. this.z += v.z;
  2721. return this;
  2722. },
  2723. addScalar: function (s) {
  2724. this.x += s;
  2725. this.y += s;
  2726. this.z += s;
  2727. return this;
  2728. },
  2729. addVectors: function (a, b) {
  2730. this.x = a.x + b.x;
  2731. this.y = a.y + b.y;
  2732. this.z = a.z + b.z;
  2733. return this;
  2734. },
  2735. addScaledVector: function (v, s) {
  2736. this.x += v.x * s;
  2737. this.y += v.y * s;
  2738. this.z += v.z * s;
  2739. return this;
  2740. },
  2741. sub: function (v, w) {
  2742. if (w !== undefined) {
  2743. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2744. return this.subVectors(v, w);
  2745. }
  2746. this.x -= v.x;
  2747. this.y -= v.y;
  2748. this.z -= v.z;
  2749. return this;
  2750. },
  2751. subScalar: function (s) {
  2752. this.x -= s;
  2753. this.y -= s;
  2754. this.z -= s;
  2755. return this;
  2756. },
  2757. subVectors: function (a, b) {
  2758. this.x = a.x - b.x;
  2759. this.y = a.y - b.y;
  2760. this.z = a.z - b.z;
  2761. return this;
  2762. },
  2763. multiply: function (v, w) {
  2764. if (w !== undefined) {
  2765. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2766. return this.multiplyVectors(v, w);
  2767. }
  2768. this.x *= v.x;
  2769. this.y *= v.y;
  2770. this.z *= v.z;
  2771. return this;
  2772. },
  2773. multiplyScalar: function (scalar) {
  2774. this.x *= scalar;
  2775. this.y *= scalar;
  2776. this.z *= scalar;
  2777. return this;
  2778. },
  2779. multiplyVectors: function (a, b) {
  2780. this.x = a.x * b.x;
  2781. this.y = a.y * b.y;
  2782. this.z = a.z * b.z;
  2783. return this;
  2784. },
  2785. applyEuler: function (euler) {
  2786. if (!(euler && euler.isEuler)) {
  2787. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2788. }
  2789. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2790. },
  2791. applyAxisAngle: function (axis, angle) {
  2792. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2793. },
  2794. applyMatrix3: function (m) {
  2795. var x = this.x,
  2796. y = this.y,
  2797. z = this.z;
  2798. var e = m.elements;
  2799. this.x = e[0] * x + e[3] * y + e[6] * z;
  2800. this.y = e[1] * x + e[4] * y + e[7] * z;
  2801. this.z = e[2] * x + e[5] * y + e[8] * z;
  2802. return this;
  2803. },
  2804. applyMatrix4: function (m) {
  2805. var x = this.x,
  2806. y = this.y,
  2807. z = this.z;
  2808. var e = m.elements;
  2809. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2810. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2811. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2812. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2813. return this;
  2814. },
  2815. applyQuaternion: function (q) {
  2816. var x = this.x,
  2817. y = this.y,
  2818. z = this.z;
  2819. var qx = q.x,
  2820. qy = q.y,
  2821. qz = q.z,
  2822. qw = q.w; // calculate quat * vector
  2823. var ix = qw * x + qy * z - qz * y;
  2824. var iy = qw * y + qz * x - qx * z;
  2825. var iz = qw * z + qx * y - qy * x;
  2826. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2827. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2828. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2829. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2830. return this;
  2831. },
  2832. project: function (camera) {
  2833. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2834. },
  2835. unproject: function (camera) {
  2836. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2837. },
  2838. transformDirection: function (m) {
  2839. // input: THREE.Matrix4 affine matrix
  2840. // vector interpreted as a direction
  2841. var x = this.x,
  2842. y = this.y,
  2843. z = this.z;
  2844. var e = m.elements;
  2845. this.x = e[0] * x + e[4] * y + e[8] * z;
  2846. this.y = e[1] * x + e[5] * y + e[9] * z;
  2847. this.z = e[2] * x + e[6] * y + e[10] * z;
  2848. return this.normalize();
  2849. },
  2850. divide: function (v) {
  2851. this.x /= v.x;
  2852. this.y /= v.y;
  2853. this.z /= v.z;
  2854. return this;
  2855. },
  2856. divideScalar: function (scalar) {
  2857. return this.multiplyScalar(1 / scalar);
  2858. },
  2859. min: function (v) {
  2860. this.x = Math.min(this.x, v.x);
  2861. this.y = Math.min(this.y, v.y);
  2862. this.z = Math.min(this.z, v.z);
  2863. return this;
  2864. },
  2865. max: function (v) {
  2866. this.x = Math.max(this.x, v.x);
  2867. this.y = Math.max(this.y, v.y);
  2868. this.z = Math.max(this.z, v.z);
  2869. return this;
  2870. },
  2871. clamp: function (min, max) {
  2872. // assumes min < max, componentwise
  2873. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2874. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2875. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2876. return this;
  2877. },
  2878. clampScalar: function (minVal, maxVal) {
  2879. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2880. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2881. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2882. return this;
  2883. },
  2884. clampLength: function (min, max) {
  2885. var length = this.length();
  2886. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2887. },
  2888. floor: function () {
  2889. this.x = Math.floor(this.x);
  2890. this.y = Math.floor(this.y);
  2891. this.z = Math.floor(this.z);
  2892. return this;
  2893. },
  2894. ceil: function () {
  2895. this.x = Math.ceil(this.x);
  2896. this.y = Math.ceil(this.y);
  2897. this.z = Math.ceil(this.z);
  2898. return this;
  2899. },
  2900. round: function () {
  2901. this.x = Math.round(this.x);
  2902. this.y = Math.round(this.y);
  2903. this.z = Math.round(this.z);
  2904. return this;
  2905. },
  2906. roundToZero: function () {
  2907. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2908. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2909. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2910. return this;
  2911. },
  2912. negate: function () {
  2913. this.x = -this.x;
  2914. this.y = -this.y;
  2915. this.z = -this.z;
  2916. return this;
  2917. },
  2918. dot: function (v) {
  2919. return this.x * v.x + this.y * v.y + this.z * v.z;
  2920. },
  2921. // TODO lengthSquared?
  2922. lengthSq: function () {
  2923. return this.x * this.x + this.y * this.y + this.z * this.z;
  2924. },
  2925. length: function () {
  2926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2927. },
  2928. manhattanLength: function () {
  2929. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2930. },
  2931. normalize: function () {
  2932. return this.divideScalar(this.length() || 1);
  2933. },
  2934. setLength: function (length) {
  2935. return this.normalize().multiplyScalar(length);
  2936. },
  2937. lerp: function (v, alpha) {
  2938. this.x += (v.x - this.x) * alpha;
  2939. this.y += (v.y - this.y) * alpha;
  2940. this.z += (v.z - this.z) * alpha;
  2941. return this;
  2942. },
  2943. lerpVectors: function (v1, v2, alpha) {
  2944. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2945. },
  2946. cross: function (v, w) {
  2947. if (w !== undefined) {
  2948. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2949. return this.crossVectors(v, w);
  2950. }
  2951. return this.crossVectors(this, v);
  2952. },
  2953. crossVectors: function (a, b) {
  2954. var ax = a.x,
  2955. ay = a.y,
  2956. az = a.z;
  2957. var bx = b.x,
  2958. by = b.y,
  2959. bz = b.z;
  2960. this.x = ay * bz - az * by;
  2961. this.y = az * bx - ax * bz;
  2962. this.z = ax * by - ay * bx;
  2963. return this;
  2964. },
  2965. projectOnVector: function (v) {
  2966. // v cannot be the zero v
  2967. var scalar = v.dot(this) / v.lengthSq();
  2968. return this.copy(v).multiplyScalar(scalar);
  2969. },
  2970. projectOnPlane: function (planeNormal) {
  2971. _vector.copy(this).projectOnVector(planeNormal);
  2972. return this.sub(_vector);
  2973. },
  2974. reflect: function (normal) {
  2975. // reflect incident vector off plane orthogonal to normal
  2976. // normal is assumed to have unit length
  2977. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2978. },
  2979. angleTo: function (v) {
  2980. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2981. if (denominator === 0) console.error('THREE.Vector3: angleTo() can\'t handle zero length vectors.');
  2982. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2983. return Math.acos(_Math.clamp(theta, -1, 1));
  2984. },
  2985. distanceTo: function (v) {
  2986. return Math.sqrt(this.distanceToSquared(v));
  2987. },
  2988. distanceToSquared: function (v) {
  2989. var dx = this.x - v.x,
  2990. dy = this.y - v.y,
  2991. dz = this.z - v.z;
  2992. return dx * dx + dy * dy + dz * dz;
  2993. },
  2994. manhattanDistanceTo: function (v) {
  2995. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2996. },
  2997. setFromSpherical: function (s) {
  2998. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2999. },
  3000. setFromSphericalCoords: function (radius, phi, theta) {
  3001. var sinPhiRadius = Math.sin(phi) * radius;
  3002. this.x = sinPhiRadius * Math.sin(theta);
  3003. this.y = Math.cos(phi) * radius;
  3004. this.z = sinPhiRadius * Math.cos(theta);
  3005. return this;
  3006. },
  3007. setFromCylindrical: function (c) {
  3008. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3009. },
  3010. setFromCylindricalCoords: function (radius, theta, y) {
  3011. this.x = radius * Math.sin(theta);
  3012. this.y = y;
  3013. this.z = radius * Math.cos(theta);
  3014. return this;
  3015. },
  3016. setFromMatrixPosition: function (m) {
  3017. var e = m.elements;
  3018. this.x = e[12];
  3019. this.y = e[13];
  3020. this.z = e[14];
  3021. return this;
  3022. },
  3023. setFromMatrixScale: function (m) {
  3024. var sx = this.setFromMatrixColumn(m, 0).length();
  3025. var sy = this.setFromMatrixColumn(m, 1).length();
  3026. var sz = this.setFromMatrixColumn(m, 2).length();
  3027. this.x = sx;
  3028. this.y = sy;
  3029. this.z = sz;
  3030. return this;
  3031. },
  3032. setFromMatrixColumn: function (m, index) {
  3033. return this.fromArray(m.elements, index * 4);
  3034. },
  3035. equals: function (v) {
  3036. return v.x === this.x && v.y === this.y && v.z === this.z;
  3037. },
  3038. fromArray: function (array, offset) {
  3039. if (offset === undefined) offset = 0;
  3040. this.x = array[offset];
  3041. this.y = array[offset + 1];
  3042. this.z = array[offset + 2];
  3043. return this;
  3044. },
  3045. toArray: function (array, offset) {
  3046. if (array === undefined) array = [];
  3047. if (offset === undefined) offset = 0;
  3048. array[offset] = this.x;
  3049. array[offset + 1] = this.y;
  3050. array[offset + 2] = this.z;
  3051. return array;
  3052. },
  3053. fromBufferAttribute: function (attribute, index, offset) {
  3054. if (offset !== undefined) {
  3055. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  3056. }
  3057. this.x = attribute.getX(index);
  3058. this.y = attribute.getY(index);
  3059. this.z = attribute.getZ(index);
  3060. return this;
  3061. }
  3062. });
  3063. /**
  3064. * @author alteredq / http://alteredqualia.com/
  3065. * @author WestLangley / http://github.com/WestLangley
  3066. * @author bhouston / http://clara.io
  3067. * @author tschw
  3068. */
  3069. var _vector$1 = new Vector3();
  3070. function Matrix3() {
  3071. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3072. if (arguments.length > 0) {
  3073. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  3074. }
  3075. }
  3076. Object.assign(Matrix3.prototype, {
  3077. isMatrix3: true,
  3078. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  3079. var te = this.elements;
  3080. te[0] = n11;
  3081. te[1] = n21;
  3082. te[2] = n31;
  3083. te[3] = n12;
  3084. te[4] = n22;
  3085. te[5] = n32;
  3086. te[6] = n13;
  3087. te[7] = n23;
  3088. te[8] = n33;
  3089. return this;
  3090. },
  3091. identity: function () {
  3092. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  3093. return this;
  3094. },
  3095. clone: function () {
  3096. return new this.constructor().fromArray(this.elements);
  3097. },
  3098. copy: function (m) {
  3099. var te = this.elements;
  3100. var me = m.elements;
  3101. te[0] = me[0];
  3102. te[1] = me[1];
  3103. te[2] = me[2];
  3104. te[3] = me[3];
  3105. te[4] = me[4];
  3106. te[5] = me[5];
  3107. te[6] = me[6];
  3108. te[7] = me[7];
  3109. te[8] = me[8];
  3110. return this;
  3111. },
  3112. setFromMatrix4: function (m) {
  3113. var me = m.elements;
  3114. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  3115. return this;
  3116. },
  3117. applyToBufferAttribute: function (attribute) {
  3118. for (var i = 0, l = attribute.count; i < l; i++) {
  3119. _vector$1.x = attribute.getX(i);
  3120. _vector$1.y = attribute.getY(i);
  3121. _vector$1.z = attribute.getZ(i);
  3122. _vector$1.applyMatrix3(this);
  3123. attribute.setXYZ(i, _vector$1.x, _vector$1.y, _vector$1.z);
  3124. }
  3125. return attribute;
  3126. },
  3127. multiply: function (m) {
  3128. return this.multiplyMatrices(this, m);
  3129. },
  3130. premultiply: function (m) {
  3131. return this.multiplyMatrices(m, this);
  3132. },
  3133. multiplyMatrices: function (a, b) {
  3134. var ae = a.elements;
  3135. var be = b.elements;
  3136. var te = this.elements;
  3137. var a11 = ae[0],
  3138. a12 = ae[3],
  3139. a13 = ae[6];
  3140. var a21 = ae[1],
  3141. a22 = ae[4],
  3142. a23 = ae[7];
  3143. var a31 = ae[2],
  3144. a32 = ae[5],
  3145. a33 = ae[8];
  3146. var b11 = be[0],
  3147. b12 = be[3],
  3148. b13 = be[6];
  3149. var b21 = be[1],
  3150. b22 = be[4],
  3151. b23 = be[7];
  3152. var b31 = be[2],
  3153. b32 = be[5],
  3154. b33 = be[8];
  3155. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  3156. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  3157. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  3158. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  3159. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  3160. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  3161. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  3162. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  3163. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  3164. return this;
  3165. },
  3166. multiplyScalar: function (s) {
  3167. var te = this.elements;
  3168. te[0] *= s;
  3169. te[3] *= s;
  3170. te[6] *= s;
  3171. te[1] *= s;
  3172. te[4] *= s;
  3173. te[7] *= s;
  3174. te[2] *= s;
  3175. te[5] *= s;
  3176. te[8] *= s;
  3177. return this;
  3178. },
  3179. determinant: function () {
  3180. var te = this.elements;
  3181. var a = te[0],
  3182. b = te[1],
  3183. c = te[2],
  3184. d = te[3],
  3185. e = te[4],
  3186. f = te[5],
  3187. g = te[6],
  3188. h = te[7],
  3189. i = te[8];
  3190. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  3191. },
  3192. getInverse: function (matrix, throwOnDegenerate) {
  3193. if (matrix && matrix.isMatrix4) {
  3194. console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");
  3195. }
  3196. var me = matrix.elements,
  3197. te = this.elements,
  3198. n11 = me[0],
  3199. n21 = me[1],
  3200. n31 = me[2],
  3201. n12 = me[3],
  3202. n22 = me[4],
  3203. n32 = me[5],
  3204. n13 = me[6],
  3205. n23 = me[7],
  3206. n33 = me[8],
  3207. t11 = n33 * n22 - n32 * n23,
  3208. t12 = n32 * n13 - n33 * n12,
  3209. t13 = n23 * n12 - n22 * n13,
  3210. det = n11 * t11 + n21 * t12 + n31 * t13;
  3211. if (det === 0) {
  3212. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  3213. if (throwOnDegenerate === true) {
  3214. throw new Error(msg);
  3215. } else {
  3216. console.warn(msg);
  3217. }
  3218. return this.identity();
  3219. }
  3220. var detInv = 1 / det;
  3221. te[0] = t11 * detInv;
  3222. te[1] = (n31 * n23 - n33 * n21) * detInv;
  3223. te[2] = (n32 * n21 - n31 * n22) * detInv;
  3224. te[3] = t12 * detInv;
  3225. te[4] = (n33 * n11 - n31 * n13) * detInv;
  3226. te[5] = (n31 * n12 - n32 * n11) * detInv;
  3227. te[6] = t13 * detInv;
  3228. te[7] = (n21 * n13 - n23 * n11) * detInv;
  3229. te[8] = (n22 * n11 - n21 * n12) * detInv;
  3230. return this;
  3231. },
  3232. transpose: function () {
  3233. var tmp,
  3234. m = this.elements;
  3235. tmp = m[1];
  3236. m[1] = m[3];
  3237. m[3] = tmp;
  3238. tmp = m[2];
  3239. m[2] = m[6];
  3240. m[6] = tmp;
  3241. tmp = m[5];
  3242. m[5] = m[7];
  3243. m[7] = tmp;
  3244. return this;
  3245. },
  3246. getNormalMatrix: function (matrix4) {
  3247. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  3248. },
  3249. transposeIntoArray: function (r) {
  3250. var m = this.elements;
  3251. r[0] = m[0];
  3252. r[1] = m[3];
  3253. r[2] = m[6];
  3254. r[3] = m[1];
  3255. r[4] = m[4];
  3256. r[5] = m[7];
  3257. r[6] = m[2];
  3258. r[7] = m[5];
  3259. r[8] = m[8];
  3260. return this;
  3261. },
  3262. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  3263. var c = Math.cos(rotation);
  3264. var s = Math.sin(rotation);
  3265. 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);
  3266. },
  3267. scale: function (sx, sy) {
  3268. var te = this.elements;
  3269. te[0] *= sx;
  3270. te[3] *= sx;
  3271. te[6] *= sx;
  3272. te[1] *= sy;
  3273. te[4] *= sy;
  3274. te[7] *= sy;
  3275. return this;
  3276. },
  3277. rotate: function (theta) {
  3278. var c = Math.cos(theta);
  3279. var s = Math.sin(theta);
  3280. var te = this.elements;
  3281. var a11 = te[0],
  3282. a12 = te[3],
  3283. a13 = te[6];
  3284. var a21 = te[1],
  3285. a22 = te[4],
  3286. a23 = te[7];
  3287. te[0] = c * a11 + s * a21;
  3288. te[3] = c * a12 + s * a22;
  3289. te[6] = c * a13 + s * a23;
  3290. te[1] = -s * a11 + c * a21;
  3291. te[4] = -s * a12 + c * a22;
  3292. te[7] = -s * a13 + c * a23;
  3293. return this;
  3294. },
  3295. translate: function (tx, ty) {
  3296. var te = this.elements;
  3297. te[0] += tx * te[2];
  3298. te[3] += tx * te[5];
  3299. te[6] += tx * te[8];
  3300. te[1] += ty * te[2];
  3301. te[4] += ty * te[5];
  3302. te[7] += ty * te[8];
  3303. return this;
  3304. },
  3305. equals: function (matrix) {
  3306. var te = this.elements;
  3307. var me = matrix.elements;
  3308. for (var i = 0; i < 9; i++) {
  3309. if (te[i] !== me[i]) return false;
  3310. }
  3311. return true;
  3312. },
  3313. fromArray: function (array, offset) {
  3314. if (offset === undefined) offset = 0;
  3315. for (var i = 0; i < 9; i++) {
  3316. this.elements[i] = array[i + offset];
  3317. }
  3318. return this;
  3319. },
  3320. toArray: function (array, offset) {
  3321. if (array === undefined) array = [];
  3322. if (offset === undefined) offset = 0;
  3323. var te = this.elements;
  3324. array[offset] = te[0];
  3325. array[offset + 1] = te[1];
  3326. array[offset + 2] = te[2];
  3327. array[offset + 3] = te[3];
  3328. array[offset + 4] = te[4];
  3329. array[offset + 5] = te[5];
  3330. array[offset + 6] = te[6];
  3331. array[offset + 7] = te[7];
  3332. array[offset + 8] = te[8];
  3333. return array;
  3334. }
  3335. });
  3336. /**
  3337. * @author mrdoob / http://mrdoob.com/
  3338. * @author alteredq / http://alteredqualia.com/
  3339. * @author szimek / https://github.com/szimek/
  3340. */
  3341. var _canvas;
  3342. var ImageUtils = {
  3343. getDataURL: function (image) {
  3344. var canvas;
  3345. if (typeof HTMLCanvasElement == 'undefined') {
  3346. return image.src;
  3347. } else if (image instanceof HTMLCanvasElement) {
  3348. canvas = image;
  3349. } else {
  3350. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  3351. _canvas.width = image.width;
  3352. _canvas.height = image.height;
  3353. var context = _canvas.getContext('2d');
  3354. if (image instanceof ImageData) {
  3355. context.putImageData(image, 0, 0);
  3356. } else {
  3357. context.drawImage(image, 0, 0, image.width, image.height);
  3358. }
  3359. canvas = _canvas;
  3360. }
  3361. if (canvas.width > 2048 || canvas.height > 2048) {
  3362. return canvas.toDataURL('image/jpeg', 0.6);
  3363. } else {
  3364. return canvas.toDataURL('image/png');
  3365. }
  3366. }
  3367. };
  3368. /**
  3369. * @author mrdoob / http://mrdoob.com/
  3370. * @author alteredq / http://alteredqualia.com/
  3371. * @author szimek / https://github.com/szimek/
  3372. */
  3373. exports.ImageUtils = ImageUtils;
  3374. var textureId = 0;
  3375. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  3376. Object.defineProperty(this, 'id', {
  3377. value: textureId++
  3378. });
  3379. this.uuid = _Math.generateUUID();
  3380. this.name = '';
  3381. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  3382. this.mipmaps = [];
  3383. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  3384. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  3385. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  3386. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  3387. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  3388. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  3389. this.format = format !== undefined ? format : RGBAFormat;
  3390. this.type = type !== undefined ? type : UnsignedByteType;
  3391. this.offset = new Vector2(0, 0);
  3392. this.repeat = new Vector2(1, 1);
  3393. this.center = new Vector2(0, 0);
  3394. this.rotation = 0;
  3395. this.matrixAutoUpdate = true;
  3396. this.matrix = new Matrix3();
  3397. this.generateMipmaps = true;
  3398. this.premultiplyAlpha = false;
  3399. this.flipY = true;
  3400. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  3401. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  3402. //
  3403. // Also changing the encoding after already used by a Material will not automatically make the Material
  3404. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  3405. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  3406. this.version = 0;
  3407. this.onUpdate = null;
  3408. }
  3409. Texture.DEFAULT_IMAGE = undefined;
  3410. Texture.DEFAULT_MAPPING = UVMapping;
  3411. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3412. constructor: Texture,
  3413. isTexture: true,
  3414. updateMatrix: function () {
  3415. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  3416. },
  3417. clone: function () {
  3418. return new this.constructor().copy(this);
  3419. },
  3420. copy: function (source) {
  3421. this.name = source.name;
  3422. this.image = source.image;
  3423. this.mipmaps = source.mipmaps.slice(0);
  3424. this.mapping = source.mapping;
  3425. this.wrapS = source.wrapS;
  3426. this.wrapT = source.wrapT;
  3427. this.magFilter = source.magFilter;
  3428. this.minFilter = source.minFilter;
  3429. this.anisotropy = source.anisotropy;
  3430. this.format = source.format;
  3431. this.type = source.type;
  3432. this.offset.copy(source.offset);
  3433. this.repeat.copy(source.repeat);
  3434. this.center.copy(source.center);
  3435. this.rotation = source.rotation;
  3436. this.matrixAutoUpdate = source.matrixAutoUpdate;
  3437. this.matrix.copy(source.matrix);
  3438. this.generateMipmaps = source.generateMipmaps;
  3439. this.premultiplyAlpha = source.premultiplyAlpha;
  3440. this.flipY = source.flipY;
  3441. this.unpackAlignment = source.unpackAlignment;
  3442. this.encoding = source.encoding;
  3443. return this;
  3444. },
  3445. toJSON: function (meta) {
  3446. var isRootObject = meta === undefined || typeof meta === 'string';
  3447. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  3448. return meta.textures[this.uuid];
  3449. }
  3450. var output = {
  3451. metadata: {
  3452. version: 4.5,
  3453. type: 'Texture',
  3454. generator: 'Texture.toJSON'
  3455. },
  3456. uuid: this.uuid,
  3457. name: this.name,
  3458. mapping: this.mapping,
  3459. repeat: [this.repeat.x, this.repeat.y],
  3460. offset: [this.offset.x, this.offset.y],
  3461. center: [this.center.x, this.center.y],
  3462. rotation: this.rotation,
  3463. wrap: [this.wrapS, this.wrapT],
  3464. format: this.format,
  3465. type: this.type,
  3466. encoding: this.encoding,
  3467. minFilter: this.minFilter,
  3468. magFilter: this.magFilter,
  3469. anisotropy: this.anisotropy,
  3470. flipY: this.flipY,
  3471. premultiplyAlpha: this.premultiplyAlpha,
  3472. unpackAlignment: this.unpackAlignment
  3473. };
  3474. if (this.image !== undefined) {
  3475. // TODO: Move to THREE.Image
  3476. var image = this.image;
  3477. if (image.uuid === undefined) {
  3478. image.uuid = _Math.generateUUID(); // UGH
  3479. }
  3480. if (!isRootObject && meta.images[image.uuid] === undefined) {
  3481. var url;
  3482. if (Array.isArray(image)) {
  3483. // process array of images e.g. CubeTexture
  3484. url = [];
  3485. for (var i = 0, l = image.length; i < l; i++) {
  3486. url.push(ImageUtils.getDataURL(image[i]));
  3487. }
  3488. } else {
  3489. // process single image
  3490. url = ImageUtils.getDataURL(image);
  3491. }
  3492. meta.images[image.uuid] = {
  3493. uuid: image.uuid,
  3494. url: url
  3495. };
  3496. }
  3497. output.image = image.uuid;
  3498. }
  3499. if (!isRootObject) {
  3500. meta.textures[this.uuid] = output;
  3501. }
  3502. return output;
  3503. },
  3504. dispose: function () {
  3505. this.dispatchEvent({
  3506. type: 'dispose'
  3507. });
  3508. },
  3509. transformUv: function (uv) {
  3510. if (this.mapping !== UVMapping) return uv;
  3511. uv.applyMatrix3(this.matrix);
  3512. if (uv.x < 0 || uv.x > 1) {
  3513. switch (this.wrapS) {
  3514. case RepeatWrapping:
  3515. uv.x = uv.x - Math.floor(uv.x);
  3516. break;
  3517. case ClampToEdgeWrapping:
  3518. uv.x = uv.x < 0 ? 0 : 1;
  3519. break;
  3520. case MirroredRepeatWrapping:
  3521. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  3522. uv.x = Math.ceil(uv.x) - uv.x;
  3523. } else {
  3524. uv.x = uv.x - Math.floor(uv.x);
  3525. }
  3526. break;
  3527. }
  3528. }
  3529. if (uv.y < 0 || uv.y > 1) {
  3530. switch (this.wrapT) {
  3531. case RepeatWrapping:
  3532. uv.y = uv.y - Math.floor(uv.y);
  3533. break;
  3534. case ClampToEdgeWrapping:
  3535. uv.y = uv.y < 0 ? 0 : 1;
  3536. break;
  3537. case MirroredRepeatWrapping:
  3538. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  3539. uv.y = Math.ceil(uv.y) - uv.y;
  3540. } else {
  3541. uv.y = uv.y - Math.floor(uv.y);
  3542. }
  3543. break;
  3544. }
  3545. }
  3546. if (this.flipY) {
  3547. uv.y = 1 - uv.y;
  3548. }
  3549. return uv;
  3550. }
  3551. });
  3552. Object.defineProperty(Texture.prototype, "needsUpdate", {
  3553. set: function (value) {
  3554. if (value === true) this.version++;
  3555. }
  3556. });
  3557. /**
  3558. * @author supereggbert / http://www.paulbrunt.co.uk/
  3559. * @author philogb / http://blog.thejit.org/
  3560. * @author mikael emtinger / http://gomo.se/
  3561. * @author egraether / http://egraether.com/
  3562. * @author WestLangley / http://github.com/WestLangley
  3563. */
  3564. function Vector4(x, y, z, w) {
  3565. this.x = x || 0;
  3566. this.y = y || 0;
  3567. this.z = z || 0;
  3568. this.w = w !== undefined ? w : 1;
  3569. }
  3570. Object.defineProperties(Vector4.prototype, {
  3571. "width": {
  3572. get: function () {
  3573. return this.z;
  3574. },
  3575. set: function (value) {
  3576. this.z = value;
  3577. }
  3578. },
  3579. "height": {
  3580. get: function () {
  3581. return this.w;
  3582. },
  3583. set: function (value) {
  3584. this.w = value;
  3585. }
  3586. }
  3587. });
  3588. Object.assign(Vector4.prototype, {
  3589. isVector4: true,
  3590. set: function (x, y, z, w) {
  3591. this.x = x;
  3592. this.y = y;
  3593. this.z = z;
  3594. this.w = w;
  3595. return this;
  3596. },
  3597. setScalar: function (scalar) {
  3598. this.x = scalar;
  3599. this.y = scalar;
  3600. this.z = scalar;
  3601. this.w = scalar;
  3602. return this;
  3603. },
  3604. setX: function (x) {
  3605. this.x = x;
  3606. return this;
  3607. },
  3608. setY: function (y) {
  3609. this.y = y;
  3610. return this;
  3611. },
  3612. setZ: function (z) {
  3613. this.z = z;
  3614. return this;
  3615. },
  3616. setW: function (w) {
  3617. this.w = w;
  3618. return this;
  3619. },
  3620. setComponent: function (index, value) {
  3621. switch (index) {
  3622. case 0:
  3623. this.x = value;
  3624. break;
  3625. case 1:
  3626. this.y = value;
  3627. break;
  3628. case 2:
  3629. this.z = value;
  3630. break;
  3631. case 3:
  3632. this.w = value;
  3633. break;
  3634. default:
  3635. throw new Error('index is out of range: ' + index);
  3636. }
  3637. return this;
  3638. },
  3639. getComponent: function (index) {
  3640. switch (index) {
  3641. case 0:
  3642. return this.x;
  3643. case 1:
  3644. return this.y;
  3645. case 2:
  3646. return this.z;
  3647. case 3:
  3648. return this.w;
  3649. default:
  3650. throw new Error('index is out of range: ' + index);
  3651. }
  3652. },
  3653. clone: function () {
  3654. return new this.constructor(this.x, this.y, this.z, this.w);
  3655. },
  3656. copy: function (v) {
  3657. this.x = v.x;
  3658. this.y = v.y;
  3659. this.z = v.z;
  3660. this.w = v.w !== undefined ? v.w : 1;
  3661. return this;
  3662. },
  3663. add: function (v, w) {
  3664. if (w !== undefined) {
  3665. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  3666. return this.addVectors(v, w);
  3667. }
  3668. this.x += v.x;
  3669. this.y += v.y;
  3670. this.z += v.z;
  3671. this.w += v.w;
  3672. return this;
  3673. },
  3674. addScalar: function (s) {
  3675. this.x += s;
  3676. this.y += s;
  3677. this.z += s;
  3678. this.w += s;
  3679. return this;
  3680. },
  3681. addVectors: function (a, b) {
  3682. this.x = a.x + b.x;
  3683. this.y = a.y + b.y;
  3684. this.z = a.z + b.z;
  3685. this.w = a.w + b.w;
  3686. return this;
  3687. },
  3688. addScaledVector: function (v, s) {
  3689. this.x += v.x * s;
  3690. this.y += v.y * s;
  3691. this.z += v.z * s;
  3692. this.w += v.w * s;
  3693. return this;
  3694. },
  3695. sub: function (v, w) {
  3696. if (w !== undefined) {
  3697. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  3698. return this.subVectors(v, w);
  3699. }
  3700. this.x -= v.x;
  3701. this.y -= v.y;
  3702. this.z -= v.z;
  3703. this.w -= v.w;
  3704. return this;
  3705. },
  3706. subScalar: function (s) {
  3707. this.x -= s;
  3708. this.y -= s;
  3709. this.z -= s;
  3710. this.w -= s;
  3711. return this;
  3712. },
  3713. subVectors: function (a, b) {
  3714. this.x = a.x - b.x;
  3715. this.y = a.y - b.y;
  3716. this.z = a.z - b.z;
  3717. this.w = a.w - b.w;
  3718. return this;
  3719. },
  3720. multiplyScalar: function (scalar) {
  3721. this.x *= scalar;
  3722. this.y *= scalar;
  3723. this.z *= scalar;
  3724. this.w *= scalar;
  3725. return this;
  3726. },
  3727. applyMatrix4: function (m) {
  3728. var x = this.x,
  3729. y = this.y,
  3730. z = this.z,
  3731. w = this.w;
  3732. var e = m.elements;
  3733. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  3734. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  3735. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  3736. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  3737. return this;
  3738. },
  3739. divideScalar: function (scalar) {
  3740. return this.multiplyScalar(1 / scalar);
  3741. },
  3742. setAxisAngleFromQuaternion: function (q) {
  3743. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3744. // q is assumed to be normalized
  3745. this.w = 2 * Math.acos(q.w);
  3746. var s = Math.sqrt(1 - q.w * q.w);
  3747. if (s < 0.0001) {
  3748. this.x = 1;
  3749. this.y = 0;
  3750. this.z = 0;
  3751. } else {
  3752. this.x = q.x / s;
  3753. this.y = q.y / s;
  3754. this.z = q.z / s;
  3755. }
  3756. return this;
  3757. },
  3758. setAxisAngleFromRotationMatrix: function (m) {
  3759. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3760. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3761. var angle,
  3762. x,
  3763. y,
  3764. z,
  3765. // variables for result
  3766. epsilon = 0.01,
  3767. // margin to allow for rounding errors
  3768. epsilon2 = 0.1,
  3769. // margin to distinguish between 0 and 180 degrees
  3770. te = m.elements,
  3771. m11 = te[0],
  3772. m12 = te[4],
  3773. m13 = te[8],
  3774. m21 = te[1],
  3775. m22 = te[5],
  3776. m23 = te[9],
  3777. m31 = te[2],
  3778. m32 = te[6],
  3779. m33 = te[10];
  3780. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  3781. // singularity found
  3782. // first check for identity matrix which must have +1 for all terms
  3783. // in leading diagonal and zero in other terms
  3784. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  3785. // this singularity is identity matrix so angle = 0
  3786. this.set(1, 0, 0, 0);
  3787. return this; // zero angle, arbitrary axis
  3788. } // otherwise this singularity is angle = 180
  3789. angle = Math.PI;
  3790. var xx = (m11 + 1) / 2;
  3791. var yy = (m22 + 1) / 2;
  3792. var zz = (m33 + 1) / 2;
  3793. var xy = (m12 + m21) / 4;
  3794. var xz = (m13 + m31) / 4;
  3795. var yz = (m23 + m32) / 4;
  3796. if (xx > yy && xx > zz) {
  3797. // m11 is the largest diagonal term
  3798. if (xx < epsilon) {
  3799. x = 0;
  3800. y = 0.707106781;
  3801. z = 0.707106781;
  3802. } else {
  3803. x = Math.sqrt(xx);
  3804. y = xy / x;
  3805. z = xz / x;
  3806. }
  3807. } else if (yy > zz) {
  3808. // m22 is the largest diagonal term
  3809. if (yy < epsilon) {
  3810. x = 0.707106781;
  3811. y = 0;
  3812. z = 0.707106781;
  3813. } else {
  3814. y = Math.sqrt(yy);
  3815. x = xy / y;
  3816. z = yz / y;
  3817. }
  3818. } else {
  3819. // m33 is the largest diagonal term so base result on this
  3820. if (zz < epsilon) {
  3821. x = 0.707106781;
  3822. y = 0.707106781;
  3823. z = 0;
  3824. } else {
  3825. z = Math.sqrt(zz);
  3826. x = xz / z;
  3827. y = yz / z;
  3828. }
  3829. }
  3830. this.set(x, y, z, angle);
  3831. return this; // return 180 deg rotation
  3832. } // as we have reached here there are no singularities so we can handle normally
  3833. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  3834. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3835. // caught by singularity test above, but I've left it in just in case
  3836. this.x = (m32 - m23) / s;
  3837. this.y = (m13 - m31) / s;
  3838. this.z = (m21 - m12) / s;
  3839. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  3840. return this;
  3841. },
  3842. min: function (v) {
  3843. this.x = Math.min(this.x, v.x);
  3844. this.y = Math.min(this.y, v.y);
  3845. this.z = Math.min(this.z, v.z);
  3846. this.w = Math.min(this.w, v.w);
  3847. return this;
  3848. },
  3849. max: function (v) {
  3850. this.x = Math.max(this.x, v.x);
  3851. this.y = Math.max(this.y, v.y);
  3852. this.z = Math.max(this.z, v.z);
  3853. this.w = Math.max(this.w, v.w);
  3854. return this;
  3855. },
  3856. clamp: function (min, max) {
  3857. // assumes min < max, componentwise
  3858. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3859. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3860. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3861. this.w = Math.max(min.w, Math.min(max.w, this.w));
  3862. return this;
  3863. },
  3864. clampScalar: function (minVal, maxVal) {
  3865. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3866. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3867. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3868. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  3869. return this;
  3870. },
  3871. clampLength: function (min, max) {
  3872. var length = this.length();
  3873. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3874. },
  3875. floor: function () {
  3876. this.x = Math.floor(this.x);
  3877. this.y = Math.floor(this.y);
  3878. this.z = Math.floor(this.z);
  3879. this.w = Math.floor(this.w);
  3880. return this;
  3881. },
  3882. ceil: function () {
  3883. this.x = Math.ceil(this.x);
  3884. this.y = Math.ceil(this.y);
  3885. this.z = Math.ceil(this.z);
  3886. this.w = Math.ceil(this.w);
  3887. return this;
  3888. },
  3889. round: function () {
  3890. this.x = Math.round(this.x);
  3891. this.y = Math.round(this.y);
  3892. this.z = Math.round(this.z);
  3893. this.w = Math.round(this.w);
  3894. return this;
  3895. },
  3896. roundToZero: function () {
  3897. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3898. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3899. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3900. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  3901. return this;
  3902. },
  3903. negate: function () {
  3904. this.x = -this.x;
  3905. this.y = -this.y;
  3906. this.z = -this.z;
  3907. this.w = -this.w;
  3908. return this;
  3909. },
  3910. dot: function (v) {
  3911. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3912. },
  3913. lengthSq: function () {
  3914. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3915. },
  3916. length: function () {
  3917. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3918. },
  3919. manhattanLength: function () {
  3920. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  3921. },
  3922. normalize: function () {
  3923. return this.divideScalar(this.length() || 1);
  3924. },
  3925. setLength: function (length) {
  3926. return this.normalize().multiplyScalar(length);
  3927. },
  3928. lerp: function (v, alpha) {
  3929. this.x += (v.x - this.x) * alpha;
  3930. this.y += (v.y - this.y) * alpha;
  3931. this.z += (v.z - this.z) * alpha;
  3932. this.w += (v.w - this.w) * alpha;
  3933. return this;
  3934. },
  3935. lerpVectors: function (v1, v2, alpha) {
  3936. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  3937. },
  3938. equals: function (v) {
  3939. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  3940. },
  3941. fromArray: function (array, offset) {
  3942. if (offset === undefined) offset = 0;
  3943. this.x = array[offset];
  3944. this.y = array[offset + 1];
  3945. this.z = array[offset + 2];
  3946. this.w = array[offset + 3];
  3947. return this;
  3948. },
  3949. toArray: function (array, offset) {
  3950. if (array === undefined) array = [];
  3951. if (offset === undefined) offset = 0;
  3952. array[offset] = this.x;
  3953. array[offset + 1] = this.y;
  3954. array[offset + 2] = this.z;
  3955. array[offset + 3] = this.w;
  3956. return array;
  3957. },
  3958. fromBufferAttribute: function (attribute, index, offset) {
  3959. if (offset !== undefined) {
  3960. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  3961. }
  3962. this.x = attribute.getX(index);
  3963. this.y = attribute.getY(index);
  3964. this.z = attribute.getZ(index);
  3965. this.w = attribute.getW(index);
  3966. return this;
  3967. }
  3968. });
  3969. /**
  3970. * @author szimek / https://github.com/szimek/
  3971. * @author alteredq / http://alteredqualia.com/
  3972. * @author Marius Kintel / https://github.com/kintel
  3973. */
  3974. /*
  3975. In options, we can specify:
  3976. * Texture parameters for an auto-generated target texture
  3977. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  3978. */
  3979. function WebGLRenderTarget(width, height, options) {
  3980. this.width = width;
  3981. this.height = height;
  3982. this.scissor = new Vector4(0, 0, width, height);
  3983. this.scissorTest = false;
  3984. this.viewport = new Vector4(0, 0, width, height);
  3985. options = options || {};
  3986. this.texture = new Texture(undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  3987. this.texture.image = {};
  3988. this.texture.image.width = width;
  3989. this.texture.image.height = height;
  3990. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  3991. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  3992. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  3993. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  3994. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  3995. }
  3996. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  3997. constructor: WebGLRenderTarget,
  3998. isWebGLRenderTarget: true,
  3999. setSize: function (width, height) {
  4000. if (this.width !== width || this.height !== height) {
  4001. this.width = width;
  4002. this.height = height;
  4003. this.texture.image.width = width;
  4004. this.texture.image.height = height;
  4005. this.dispose();
  4006. }
  4007. this.viewport.set(0, 0, width, height);
  4008. this.scissor.set(0, 0, width, height);
  4009. },
  4010. clone: function () {
  4011. return new this.constructor().copy(this);
  4012. },
  4013. copy: function (source) {
  4014. this.width = source.width;
  4015. this.height = source.height;
  4016. this.viewport.copy(source.viewport);
  4017. this.texture = source.texture.clone();
  4018. this.depthBuffer = source.depthBuffer;
  4019. this.stencilBuffer = source.stencilBuffer;
  4020. this.depthTexture = source.depthTexture;
  4021. return this;
  4022. },
  4023. dispose: function () {
  4024. this.dispatchEvent({
  4025. type: 'dispose'
  4026. });
  4027. }
  4028. });
  4029. /**
  4030. * @author Mugen87 / https://github.com/Mugen87
  4031. * @author Matt DesLauriers / @mattdesl
  4032. */
  4033. function WebGLMultisampleRenderTarget(width, height, options) {
  4034. WebGLRenderTarget.call(this, width, height, options);
  4035. this.samples = 4;
  4036. }
  4037. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  4038. constructor: WebGLMultisampleRenderTarget,
  4039. isWebGLMultisampleRenderTarget: true,
  4040. copy: function (source) {
  4041. WebGLRenderTarget.prototype.copy.call(this, source);
  4042. this.samples = source.samples;
  4043. return this;
  4044. }
  4045. });
  4046. var _v1 = new Vector3();
  4047. var _m1 = new Matrix4();
  4048. var _zero = new Vector3(0, 0, 0);
  4049. var _one = new Vector3(1, 1, 1);
  4050. var _x = new Vector3();
  4051. var _y = new Vector3();
  4052. var _z = new Vector3();
  4053. /**
  4054. * @author mrdoob / http://mrdoob.com/
  4055. * @author supereggbert / http://www.paulbrunt.co.uk/
  4056. * @author philogb / http://blog.thejit.org/
  4057. * @author jordi_ros / http://plattsoft.com
  4058. * @author D1plo1d / http://github.com/D1plo1d
  4059. * @author alteredq / http://alteredqualia.com/
  4060. * @author mikael emtinger / http://gomo.se/
  4061. * @author timknip / http://www.floorplanner.com/
  4062. * @author bhouston / http://clara.io
  4063. * @author WestLangley / http://github.com/WestLangley
  4064. */
  4065. function Matrix4() {
  4066. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4067. if (arguments.length > 0) {
  4068. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  4069. }
  4070. }
  4071. Object.assign(Matrix4.prototype, {
  4072. isMatrix4: true,
  4073. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  4074. var te = this.elements;
  4075. te[0] = n11;
  4076. te[4] = n12;
  4077. te[8] = n13;
  4078. te[12] = n14;
  4079. te[1] = n21;
  4080. te[5] = n22;
  4081. te[9] = n23;
  4082. te[13] = n24;
  4083. te[2] = n31;
  4084. te[6] = n32;
  4085. te[10] = n33;
  4086. te[14] = n34;
  4087. te[3] = n41;
  4088. te[7] = n42;
  4089. te[11] = n43;
  4090. te[15] = n44;
  4091. return this;
  4092. },
  4093. identity: function () {
  4094. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4095. return this;
  4096. },
  4097. clone: function () {
  4098. return new Matrix4().fromArray(this.elements);
  4099. },
  4100. copy: function (m) {
  4101. var te = this.elements;
  4102. var me = m.elements;
  4103. te[0] = me[0];
  4104. te[1] = me[1];
  4105. te[2] = me[2];
  4106. te[3] = me[3];
  4107. te[4] = me[4];
  4108. te[5] = me[5];
  4109. te[6] = me[6];
  4110. te[7] = me[7];
  4111. te[8] = me[8];
  4112. te[9] = me[9];
  4113. te[10] = me[10];
  4114. te[11] = me[11];
  4115. te[12] = me[12];
  4116. te[13] = me[13];
  4117. te[14] = me[14];
  4118. te[15] = me[15];
  4119. return this;
  4120. },
  4121. copyPosition: function (m) {
  4122. var te = this.elements,
  4123. me = m.elements;
  4124. te[12] = me[12];
  4125. te[13] = me[13];
  4126. te[14] = me[14];
  4127. return this;
  4128. },
  4129. extractBasis: function (xAxis, yAxis, zAxis) {
  4130. xAxis.setFromMatrixColumn(this, 0);
  4131. yAxis.setFromMatrixColumn(this, 1);
  4132. zAxis.setFromMatrixColumn(this, 2);
  4133. return this;
  4134. },
  4135. makeBasis: function (xAxis, yAxis, zAxis) {
  4136. 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);
  4137. return this;
  4138. },
  4139. extractRotation: function (m) {
  4140. // this method does not support reflection matrices
  4141. var te = this.elements;
  4142. var me = m.elements;
  4143. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  4144. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  4145. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  4146. te[0] = me[0] * scaleX;
  4147. te[1] = me[1] * scaleX;
  4148. te[2] = me[2] * scaleX;
  4149. te[3] = 0;
  4150. te[4] = me[4] * scaleY;
  4151. te[5] = me[5] * scaleY;
  4152. te[6] = me[6] * scaleY;
  4153. te[7] = 0;
  4154. te[8] = me[8] * scaleZ;
  4155. te[9] = me[9] * scaleZ;
  4156. te[10] = me[10] * scaleZ;
  4157. te[11] = 0;
  4158. te[12] = 0;
  4159. te[13] = 0;
  4160. te[14] = 0;
  4161. te[15] = 1;
  4162. return this;
  4163. },
  4164. makeRotationFromEuler: function (euler) {
  4165. if (!(euler && euler.isEuler)) {
  4166. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  4167. }
  4168. var te = this.elements;
  4169. var x = euler.x,
  4170. y = euler.y,
  4171. z = euler.z;
  4172. var a = Math.cos(x),
  4173. b = Math.sin(x);
  4174. var c = Math.cos(y),
  4175. d = Math.sin(y);
  4176. var e = Math.cos(z),
  4177. f = Math.sin(z);
  4178. if (euler.order === 'XYZ') {
  4179. var ae = a * e,
  4180. af = a * f,
  4181. be = b * e,
  4182. bf = b * f;
  4183. te[0] = c * e;
  4184. te[4] = -c * f;
  4185. te[8] = d;
  4186. te[1] = af + be * d;
  4187. te[5] = ae - bf * d;
  4188. te[9] = -b * c;
  4189. te[2] = bf - ae * d;
  4190. te[6] = be + af * d;
  4191. te[10] = a * c;
  4192. } else if (euler.order === 'YXZ') {
  4193. var ce = c * e,
  4194. cf = c * f,
  4195. de = d * e,
  4196. df = d * f;
  4197. te[0] = ce + df * b;
  4198. te[4] = de * b - cf;
  4199. te[8] = a * d;
  4200. te[1] = a * f;
  4201. te[5] = a * e;
  4202. te[9] = -b;
  4203. te[2] = cf * b - de;
  4204. te[6] = df + ce * b;
  4205. te[10] = a * c;
  4206. } else if (euler.order === 'ZXY') {
  4207. var ce = c * e,
  4208. cf = c * f,
  4209. de = d * e,
  4210. df = d * f;
  4211. te[0] = ce - df * b;
  4212. te[4] = -a * f;
  4213. te[8] = de + cf * b;
  4214. te[1] = cf + de * b;
  4215. te[5] = a * e;
  4216. te[9] = df - ce * b;
  4217. te[2] = -a * d;
  4218. te[6] = b;
  4219. te[10] = a * c;
  4220. } else if (euler.order === 'ZYX') {
  4221. var ae = a * e,
  4222. af = a * f,
  4223. be = b * e,
  4224. bf = b * f;
  4225. te[0] = c * e;
  4226. te[4] = be * d - af;
  4227. te[8] = ae * d + bf;
  4228. te[1] = c * f;
  4229. te[5] = bf * d + ae;
  4230. te[9] = af * d - be;
  4231. te[2] = -d;
  4232. te[6] = b * c;
  4233. te[10] = a * c;
  4234. } else if (euler.order === 'YZX') {
  4235. var ac = a * c,
  4236. ad = a * d,
  4237. bc = b * c,
  4238. bd = b * d;
  4239. te[0] = c * e;
  4240. te[4] = bd - ac * f;
  4241. te[8] = bc * f + ad;
  4242. te[1] = f;
  4243. te[5] = a * e;
  4244. te[9] = -b * e;
  4245. te[2] = -d * e;
  4246. te[6] = ad * f + bc;
  4247. te[10] = ac - bd * f;
  4248. } else if (euler.order === 'XZY') {
  4249. var ac = a * c,
  4250. ad = a * d,
  4251. bc = b * c,
  4252. bd = b * d;
  4253. te[0] = c * e;
  4254. te[4] = -f;
  4255. te[8] = d * e;
  4256. te[1] = ac * f + bd;
  4257. te[5] = a * e;
  4258. te[9] = ad * f - bc;
  4259. te[2] = bc * f - ad;
  4260. te[6] = b * e;
  4261. te[10] = bd * f + ac;
  4262. } // bottom row
  4263. te[3] = 0;
  4264. te[7] = 0;
  4265. te[11] = 0; // last column
  4266. te[12] = 0;
  4267. te[13] = 0;
  4268. te[14] = 0;
  4269. te[15] = 1;
  4270. return this;
  4271. },
  4272. makeRotationFromQuaternion: function (q) {
  4273. return this.compose(_zero, q, _one);
  4274. },
  4275. lookAt: function (eye, target, up) {
  4276. var te = this.elements;
  4277. _z.subVectors(eye, target);
  4278. if (_z.lengthSq() === 0) {
  4279. // eye and target are in the same position
  4280. _z.z = 1;
  4281. }
  4282. _z.normalize();
  4283. _x.crossVectors(up, _z);
  4284. if (_x.lengthSq() === 0) {
  4285. // up and z are parallel
  4286. if (Math.abs(up.z) === 1) {
  4287. _z.x += 0.0001;
  4288. } else {
  4289. _z.z += 0.0001;
  4290. }
  4291. _z.normalize();
  4292. _x.crossVectors(up, _z);
  4293. }
  4294. _x.normalize();
  4295. _y.crossVectors(_z, _x);
  4296. te[0] = _x.x;
  4297. te[4] = _y.x;
  4298. te[8] = _z.x;
  4299. te[1] = _x.y;
  4300. te[5] = _y.y;
  4301. te[9] = _z.y;
  4302. te[2] = _x.z;
  4303. te[6] = _y.z;
  4304. te[10] = _z.z;
  4305. return this;
  4306. },
  4307. multiply: function (m, n) {
  4308. if (n !== undefined) {
  4309. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  4310. return this.multiplyMatrices(m, n);
  4311. }
  4312. return this.multiplyMatrices(this, m);
  4313. },
  4314. premultiply: function (m) {
  4315. return this.multiplyMatrices(m, this);
  4316. },
  4317. multiplyMatrices: function (a, b) {
  4318. var ae = a.elements;
  4319. var be = b.elements;
  4320. var te = this.elements;
  4321. var a11 = ae[0],
  4322. a12 = ae[4],
  4323. a13 = ae[8],
  4324. a14 = ae[12];
  4325. var a21 = ae[1],
  4326. a22 = ae[5],
  4327. a23 = ae[9],
  4328. a24 = ae[13];
  4329. var a31 = ae[2],
  4330. a32 = ae[6],
  4331. a33 = ae[10],
  4332. a34 = ae[14];
  4333. var a41 = ae[3],
  4334. a42 = ae[7],
  4335. a43 = ae[11],
  4336. a44 = ae[15];
  4337. var b11 = be[0],
  4338. b12 = be[4],
  4339. b13 = be[8],
  4340. b14 = be[12];
  4341. var b21 = be[1],
  4342. b22 = be[5],
  4343. b23 = be[9],
  4344. b24 = be[13];
  4345. var b31 = be[2],
  4346. b32 = be[6],
  4347. b33 = be[10],
  4348. b34 = be[14];
  4349. var b41 = be[3],
  4350. b42 = be[7],
  4351. b43 = be[11],
  4352. b44 = be[15];
  4353. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4354. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4355. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4356. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4357. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4358. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4359. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4360. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4361. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4362. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4363. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4364. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4365. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4366. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4367. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4368. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4369. return this;
  4370. },
  4371. multiplyScalar: function (s) {
  4372. var te = this.elements;
  4373. te[0] *= s;
  4374. te[4] *= s;
  4375. te[8] *= s;
  4376. te[12] *= s;
  4377. te[1] *= s;
  4378. te[5] *= s;
  4379. te[9] *= s;
  4380. te[13] *= s;
  4381. te[2] *= s;
  4382. te[6] *= s;
  4383. te[10] *= s;
  4384. te[14] *= s;
  4385. te[3] *= s;
  4386. te[7] *= s;
  4387. te[11] *= s;
  4388. te[15] *= s;
  4389. return this;
  4390. },
  4391. applyToBufferAttribute: function (attribute) {
  4392. for (var i = 0, l = attribute.count; i < l; i++) {
  4393. _v1.x = attribute.getX(i);
  4394. _v1.y = attribute.getY(i);
  4395. _v1.z = attribute.getZ(i);
  4396. _v1.applyMatrix4(this);
  4397. attribute.setXYZ(i, _v1.x, _v1.y, _v1.z);
  4398. }
  4399. return attribute;
  4400. },
  4401. determinant: function () {
  4402. var te = this.elements;
  4403. var n11 = te[0],
  4404. n12 = te[4],
  4405. n13 = te[8],
  4406. n14 = te[12];
  4407. var n21 = te[1],
  4408. n22 = te[5],
  4409. n23 = te[9],
  4410. n24 = te[13];
  4411. var n31 = te[2],
  4412. n32 = te[6],
  4413. n33 = te[10],
  4414. n34 = te[14];
  4415. var n41 = te[3],
  4416. n42 = te[7],
  4417. n43 = te[11],
  4418. n44 = te[15]; //TODO: make this more efficient
  4419. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4420. 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);
  4421. },
  4422. transpose: function () {
  4423. var te = this.elements;
  4424. var tmp;
  4425. tmp = te[1];
  4426. te[1] = te[4];
  4427. te[4] = tmp;
  4428. tmp = te[2];
  4429. te[2] = te[8];
  4430. te[8] = tmp;
  4431. tmp = te[6];
  4432. te[6] = te[9];
  4433. te[9] = tmp;
  4434. tmp = te[3];
  4435. te[3] = te[12];
  4436. te[12] = tmp;
  4437. tmp = te[7];
  4438. te[7] = te[13];
  4439. te[13] = tmp;
  4440. tmp = te[11];
  4441. te[11] = te[14];
  4442. te[14] = tmp;
  4443. return this;
  4444. },
  4445. setPosition: function (x, y, z) {
  4446. var te = this.elements;
  4447. if (x.isVector3) {
  4448. te[12] = x.x;
  4449. te[13] = x.y;
  4450. te[14] = x.z;
  4451. } else {
  4452. te[12] = x;
  4453. te[13] = y;
  4454. te[14] = z;
  4455. }
  4456. return this;
  4457. },
  4458. getInverse: function (m, throwOnDegenerate) {
  4459. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4460. var te = this.elements,
  4461. me = m.elements,
  4462. n11 = me[0],
  4463. n21 = me[1],
  4464. n31 = me[2],
  4465. n41 = me[3],
  4466. n12 = me[4],
  4467. n22 = me[5],
  4468. n32 = me[6],
  4469. n42 = me[7],
  4470. n13 = me[8],
  4471. n23 = me[9],
  4472. n33 = me[10],
  4473. n43 = me[11],
  4474. n14 = me[12],
  4475. n24 = me[13],
  4476. n34 = me[14],
  4477. n44 = me[15],
  4478. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4479. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4480. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4481. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4482. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4483. if (det === 0) {
  4484. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  4485. if (throwOnDegenerate === true) {
  4486. throw new Error(msg);
  4487. } else {
  4488. console.warn(msg);
  4489. }
  4490. return this.identity();
  4491. }
  4492. var detInv = 1 / det;
  4493. te[0] = t11 * detInv;
  4494. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4495. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4496. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4497. te[4] = t12 * detInv;
  4498. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4499. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4500. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4501. te[8] = t13 * detInv;
  4502. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4503. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4504. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4505. te[12] = t14 * detInv;
  4506. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4507. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4508. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4509. return this;
  4510. },
  4511. scale: function (v) {
  4512. var te = this.elements;
  4513. var x = v.x,
  4514. y = v.y,
  4515. z = v.z;
  4516. te[0] *= x;
  4517. te[4] *= y;
  4518. te[8] *= z;
  4519. te[1] *= x;
  4520. te[5] *= y;
  4521. te[9] *= z;
  4522. te[2] *= x;
  4523. te[6] *= y;
  4524. te[10] *= z;
  4525. te[3] *= x;
  4526. te[7] *= y;
  4527. te[11] *= z;
  4528. return this;
  4529. },
  4530. getMaxScaleOnAxis: function () {
  4531. var te = this.elements;
  4532. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4533. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4534. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4535. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4536. },
  4537. makeTranslation: function (x, y, z) {
  4538. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4539. return this;
  4540. },
  4541. makeRotationX: function (theta) {
  4542. var c = Math.cos(theta),
  4543. s = Math.sin(theta);
  4544. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4545. return this;
  4546. },
  4547. makeRotationY: function (theta) {
  4548. var c = Math.cos(theta),
  4549. s = Math.sin(theta);
  4550. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4551. return this;
  4552. },
  4553. makeRotationZ: function (theta) {
  4554. var c = Math.cos(theta),
  4555. s = Math.sin(theta);
  4556. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4557. return this;
  4558. },
  4559. makeRotationAxis: function (axis, angle) {
  4560. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4561. var c = Math.cos(angle);
  4562. var s = Math.sin(angle);
  4563. var t = 1 - c;
  4564. var x = axis.x,
  4565. y = axis.y,
  4566. z = axis.z;
  4567. var tx = t * x,
  4568. ty = t * y;
  4569. 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);
  4570. return this;
  4571. },
  4572. makeScale: function (x, y, z) {
  4573. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4574. return this;
  4575. },
  4576. makeShear: function (x, y, z) {
  4577. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  4578. return this;
  4579. },
  4580. compose: function (position, quaternion, scale) {
  4581. var te = this.elements;
  4582. var x = quaternion._x,
  4583. y = quaternion._y,
  4584. z = quaternion._z,
  4585. w = quaternion._w;
  4586. var x2 = x + x,
  4587. y2 = y + y,
  4588. z2 = z + z;
  4589. var xx = x * x2,
  4590. xy = x * y2,
  4591. xz = x * z2;
  4592. var yy = y * y2,
  4593. yz = y * z2,
  4594. zz = z * z2;
  4595. var wx = w * x2,
  4596. wy = w * y2,
  4597. wz = w * z2;
  4598. var sx = scale.x,
  4599. sy = scale.y,
  4600. sz = scale.z;
  4601. te[0] = (1 - (yy + zz)) * sx;
  4602. te[1] = (xy + wz) * sx;
  4603. te[2] = (xz - wy) * sx;
  4604. te[3] = 0;
  4605. te[4] = (xy - wz) * sy;
  4606. te[5] = (1 - (xx + zz)) * sy;
  4607. te[6] = (yz + wx) * sy;
  4608. te[7] = 0;
  4609. te[8] = (xz + wy) * sz;
  4610. te[9] = (yz - wx) * sz;
  4611. te[10] = (1 - (xx + yy)) * sz;
  4612. te[11] = 0;
  4613. te[12] = position.x;
  4614. te[13] = position.y;
  4615. te[14] = position.z;
  4616. te[15] = 1;
  4617. return this;
  4618. },
  4619. decompose: function (position, quaternion, scale) {
  4620. var te = this.elements;
  4621. var sx = _v1.set(te[0], te[1], te[2]).length();
  4622. var sy = _v1.set(te[4], te[5], te[6]).length();
  4623. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4624. var det = this.determinant();
  4625. if (det < 0) sx = -sx;
  4626. position.x = te[12];
  4627. position.y = te[13];
  4628. position.z = te[14]; // scale the rotation part
  4629. _m1.copy(this);
  4630. var invSX = 1 / sx;
  4631. var invSY = 1 / sy;
  4632. var invSZ = 1 / sz;
  4633. _m1.elements[0] *= invSX;
  4634. _m1.elements[1] *= invSX;
  4635. _m1.elements[2] *= invSX;
  4636. _m1.elements[4] *= invSY;
  4637. _m1.elements[5] *= invSY;
  4638. _m1.elements[6] *= invSY;
  4639. _m1.elements[8] *= invSZ;
  4640. _m1.elements[9] *= invSZ;
  4641. _m1.elements[10] *= invSZ;
  4642. quaternion.setFromRotationMatrix(_m1);
  4643. scale.x = sx;
  4644. scale.y = sy;
  4645. scale.z = sz;
  4646. return this;
  4647. },
  4648. makePerspective: function (left, right, top, bottom, near, far) {
  4649. if (far === undefined) {
  4650. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  4651. }
  4652. var te = this.elements;
  4653. var x = 2 * near / (right - left);
  4654. var y = 2 * near / (top - bottom);
  4655. var a = (right + left) / (right - left);
  4656. var b = (top + bottom) / (top - bottom);
  4657. var c = -(far + near) / (far - near);
  4658. var d = -2 * far * near / (far - near);
  4659. te[0] = x;
  4660. te[4] = 0;
  4661. te[8] = a;
  4662. te[12] = 0;
  4663. te[1] = 0;
  4664. te[5] = y;
  4665. te[9] = b;
  4666. te[13] = 0;
  4667. te[2] = 0;
  4668. te[6] = 0;
  4669. te[10] = c;
  4670. te[14] = d;
  4671. te[3] = 0;
  4672. te[7] = 0;
  4673. te[11] = -1;
  4674. te[15] = 0;
  4675. return this;
  4676. },
  4677. makeOrthographic: function (left, right, top, bottom, near, far) {
  4678. var te = this.elements;
  4679. var w = 1.0 / (right - left);
  4680. var h = 1.0 / (top - bottom);
  4681. var p = 1.0 / (far - near);
  4682. var x = (right + left) * w;
  4683. var y = (top + bottom) * h;
  4684. var z = (far + near) * p;
  4685. te[0] = 2 * w;
  4686. te[4] = 0;
  4687. te[8] = 0;
  4688. te[12] = -x;
  4689. te[1] = 0;
  4690. te[5] = 2 * h;
  4691. te[9] = 0;
  4692. te[13] = -y;
  4693. te[2] = 0;
  4694. te[6] = 0;
  4695. te[10] = -2 * p;
  4696. te[14] = -z;
  4697. te[3] = 0;
  4698. te[7] = 0;
  4699. te[11] = 0;
  4700. te[15] = 1;
  4701. return this;
  4702. },
  4703. equals: function (matrix) {
  4704. var te = this.elements;
  4705. var me = matrix.elements;
  4706. for (var i = 0; i < 16; i++) {
  4707. if (te[i] !== me[i]) return false;
  4708. }
  4709. return true;
  4710. },
  4711. fromArray: function (array, offset) {
  4712. if (offset === undefined) offset = 0;
  4713. for (var i = 0; i < 16; i++) {
  4714. this.elements[i] = array[i + offset];
  4715. }
  4716. return this;
  4717. },
  4718. toArray: function (array, offset) {
  4719. if (array === undefined) array = [];
  4720. if (offset === undefined) offset = 0;
  4721. var te = this.elements;
  4722. array[offset] = te[0];
  4723. array[offset + 1] = te[1];
  4724. array[offset + 2] = te[2];
  4725. array[offset + 3] = te[3];
  4726. array[offset + 4] = te[4];
  4727. array[offset + 5] = te[5];
  4728. array[offset + 6] = te[6];
  4729. array[offset + 7] = te[7];
  4730. array[offset + 8] = te[8];
  4731. array[offset + 9] = te[9];
  4732. array[offset + 10] = te[10];
  4733. array[offset + 11] = te[11];
  4734. array[offset + 12] = te[12];
  4735. array[offset + 13] = te[13];
  4736. array[offset + 14] = te[14];
  4737. array[offset + 15] = te[15];
  4738. return array;
  4739. }
  4740. });
  4741. /**
  4742. * @author mrdoob / http://mrdoob.com/
  4743. * @author WestLangley / http://github.com/WestLangley
  4744. * @author bhouston / http://clara.io
  4745. */
  4746. var _matrix = new Matrix4();
  4747. var _quaternion$1 = new Quaternion();
  4748. function Euler(x, y, z, order) {
  4749. this._x = x || 0;
  4750. this._y = y || 0;
  4751. this._z = z || 0;
  4752. this._order = order || Euler.DefaultOrder;
  4753. }
  4754. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4755. Euler.DefaultOrder = 'XYZ';
  4756. Object.defineProperties(Euler.prototype, {
  4757. x: {
  4758. get: function () {
  4759. return this._x;
  4760. },
  4761. set: function (value) {
  4762. this._x = value;
  4763. this._onChangeCallback();
  4764. }
  4765. },
  4766. y: {
  4767. get: function () {
  4768. return this._y;
  4769. },
  4770. set: function (value) {
  4771. this._y = value;
  4772. this._onChangeCallback();
  4773. }
  4774. },
  4775. z: {
  4776. get: function () {
  4777. return this._z;
  4778. },
  4779. set: function (value) {
  4780. this._z = value;
  4781. this._onChangeCallback();
  4782. }
  4783. },
  4784. order: {
  4785. get: function () {
  4786. return this._order;
  4787. },
  4788. set: function (value) {
  4789. this._order = value;
  4790. this._onChangeCallback();
  4791. }
  4792. }
  4793. });
  4794. Object.assign(Euler.prototype, {
  4795. isEuler: true,
  4796. set: function (x, y, z, order) {
  4797. this._x = x;
  4798. this._y = y;
  4799. this._z = z;
  4800. this._order = order || this._order;
  4801. this._onChangeCallback();
  4802. return this;
  4803. },
  4804. clone: function () {
  4805. return new this.constructor(this._x, this._y, this._z, this._order);
  4806. },
  4807. copy: function (euler) {
  4808. this._x = euler._x;
  4809. this._y = euler._y;
  4810. this._z = euler._z;
  4811. this._order = euler._order;
  4812. this._onChangeCallback();
  4813. return this;
  4814. },
  4815. setFromRotationMatrix: function (m, order, update) {
  4816. var clamp = _Math.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4817. var te = m.elements;
  4818. var m11 = te[0],
  4819. m12 = te[4],
  4820. m13 = te[8];
  4821. var m21 = te[1],
  4822. m22 = te[5],
  4823. m23 = te[9];
  4824. var m31 = te[2],
  4825. m32 = te[6],
  4826. m33 = te[10];
  4827. order = order || this._order;
  4828. if (order === 'XYZ') {
  4829. this._y = Math.asin(clamp(m13, -1, 1));
  4830. if (Math.abs(m13) < 0.9999999) {
  4831. this._x = Math.atan2(-m23, m33);
  4832. this._z = Math.atan2(-m12, m11);
  4833. } else {
  4834. this._x = Math.atan2(m32, m22);
  4835. this._z = 0;
  4836. }
  4837. } else if (order === 'YXZ') {
  4838. this._x = Math.asin(-clamp(m23, -1, 1));
  4839. if (Math.abs(m23) < 0.9999999) {
  4840. this._y = Math.atan2(m13, m33);
  4841. this._z = Math.atan2(m21, m22);
  4842. } else {
  4843. this._y = Math.atan2(-m31, m11);
  4844. this._z = 0;
  4845. }
  4846. } else if (order === 'ZXY') {
  4847. this._x = Math.asin(clamp(m32, -1, 1));
  4848. if (Math.abs(m32) < 0.9999999) {
  4849. this._y = Math.atan2(-m31, m33);
  4850. this._z = Math.atan2(-m12, m22);
  4851. } else {
  4852. this._y = 0;
  4853. this._z = Math.atan2(m21, m11);
  4854. }
  4855. } else if (order === 'ZYX') {
  4856. this._y = Math.asin(-clamp(m31, -1, 1));
  4857. if (Math.abs(m31) < 0.9999999) {
  4858. this._x = Math.atan2(m32, m33);
  4859. this._z = Math.atan2(m21, m11);
  4860. } else {
  4861. this._x = 0;
  4862. this._z = Math.atan2(-m12, m22);
  4863. }
  4864. } else if (order === 'YZX') {
  4865. this._z = Math.asin(clamp(m21, -1, 1));
  4866. if (Math.abs(m21) < 0.9999999) {
  4867. this._x = Math.atan2(-m23, m22);
  4868. this._y = Math.atan2(-m31, m11);
  4869. } else {
  4870. this._x = 0;
  4871. this._y = Math.atan2(m13, m33);
  4872. }
  4873. } else if (order === 'XZY') {
  4874. this._z = Math.asin(-clamp(m12, -1, 1));
  4875. if (Math.abs(m12) < 0.9999999) {
  4876. this._x = Math.atan2(m32, m22);
  4877. this._y = Math.atan2(m13, m11);
  4878. } else {
  4879. this._x = Math.atan2(-m23, m33);
  4880. this._y = 0;
  4881. }
  4882. } else {
  4883. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  4884. }
  4885. this._order = order;
  4886. if (update !== false) this._onChangeCallback();
  4887. return this;
  4888. },
  4889. setFromQuaternion: function (q, order, update) {
  4890. _matrix.makeRotationFromQuaternion(q);
  4891. return this.setFromRotationMatrix(_matrix, order, update);
  4892. },
  4893. setFromVector3: function (v, order) {
  4894. return this.set(v.x, v.y, v.z, order || this._order);
  4895. },
  4896. reorder: function (newOrder) {
  4897. // WARNING: this discards revolution information -bhouston
  4898. _quaternion$1.setFromEuler(this);
  4899. return this.setFromQuaternion(_quaternion$1, newOrder);
  4900. },
  4901. equals: function (euler) {
  4902. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4903. },
  4904. fromArray: function (array) {
  4905. this._x = array[0];
  4906. this._y = array[1];
  4907. this._z = array[2];
  4908. if (array[3] !== undefined) this._order = array[3];
  4909. this._onChangeCallback();
  4910. return this;
  4911. },
  4912. toArray: function (array, offset) {
  4913. if (array === undefined) array = [];
  4914. if (offset === undefined) offset = 0;
  4915. array[offset] = this._x;
  4916. array[offset + 1] = this._y;
  4917. array[offset + 2] = this._z;
  4918. array[offset + 3] = this._order;
  4919. return array;
  4920. },
  4921. toVector3: function (optionalResult) {
  4922. if (optionalResult) {
  4923. return optionalResult.set(this._x, this._y, this._z);
  4924. } else {
  4925. return new Vector3(this._x, this._y, this._z);
  4926. }
  4927. },
  4928. _onChange: function (callback) {
  4929. this._onChangeCallback = callback;
  4930. return this;
  4931. },
  4932. _onChangeCallback: function () {}
  4933. });
  4934. /**
  4935. * @author mrdoob / http://mrdoob.com/
  4936. */
  4937. function Layers() {
  4938. this.mask = 1 | 0;
  4939. }
  4940. Object.assign(Layers.prototype, {
  4941. set: function (channel) {
  4942. this.mask = 1 << channel | 0;
  4943. },
  4944. enable: function (channel) {
  4945. this.mask |= 1 << channel | 0;
  4946. },
  4947. enableAll: function () {
  4948. this.mask = 0xffffffff | 0;
  4949. },
  4950. toggle: function (channel) {
  4951. this.mask ^= 1 << channel | 0;
  4952. },
  4953. disable: function (channel) {
  4954. this.mask &= ~(1 << channel | 0);
  4955. },
  4956. disableAll: function () {
  4957. this.mask = 0;
  4958. },
  4959. test: function (layers) {
  4960. return (this.mask & layers.mask) !== 0;
  4961. }
  4962. });
  4963. var _object3DId = 0;
  4964. var _v1$1 = new Vector3();
  4965. var _q1 = new Quaternion();
  4966. var _m1$1 = new Matrix4();
  4967. var _target = new Vector3();
  4968. var _position = new Vector3();
  4969. var _scale = new Vector3();
  4970. var _quaternion$2 = new Quaternion();
  4971. var _xAxis = new Vector3(1, 0, 0);
  4972. var _yAxis = new Vector3(0, 1, 0);
  4973. var _zAxis = new Vector3(0, 0, 1);
  4974. var _addedEvent = {
  4975. type: 'added'
  4976. };
  4977. var _removedEvent = {
  4978. type: 'removed'
  4979. };
  4980. /**
  4981. * @author mrdoob / http://mrdoob.com/
  4982. * @author mikael emtinger / http://gomo.se/
  4983. * @author alteredq / http://alteredqualia.com/
  4984. * @author WestLangley / http://github.com/WestLangley
  4985. * @author elephantatwork / www.elephantatwork.ch
  4986. */
  4987. function Object3D() {
  4988. Object.defineProperty(this, 'id', {
  4989. value: _object3DId++
  4990. });
  4991. this.uuid = _Math.generateUUID();
  4992. this.name = '';
  4993. this.type = 'Object3D';
  4994. this.parent = null;
  4995. this.children = [];
  4996. this.up = Object3D.DefaultUp.clone();
  4997. var position = new Vector3();
  4998. var rotation = new Euler();
  4999. var quaternion = new Quaternion();
  5000. var scale = new Vector3(1, 1, 1);
  5001. function onRotationChange() {
  5002. quaternion.setFromEuler(rotation, false);
  5003. }
  5004. function onQuaternionChange() {
  5005. rotation.setFromQuaternion(quaternion, undefined, false);
  5006. }
  5007. rotation._onChange(onRotationChange);
  5008. quaternion._onChange(onQuaternionChange);
  5009. Object.defineProperties(this, {
  5010. position: {
  5011. configurable: true,
  5012. enumerable: true,
  5013. value: position
  5014. },
  5015. rotation: {
  5016. configurable: true,
  5017. enumerable: true,
  5018. value: rotation
  5019. },
  5020. quaternion: {
  5021. configurable: true,
  5022. enumerable: true,
  5023. value: quaternion
  5024. },
  5025. scale: {
  5026. configurable: true,
  5027. enumerable: true,
  5028. value: scale
  5029. },
  5030. modelViewMatrix: {
  5031. value: new Matrix4()
  5032. },
  5033. normalMatrix: {
  5034. value: new Matrix3()
  5035. }
  5036. });
  5037. this.matrix = new Matrix4();
  5038. this.matrixWorld = new Matrix4();
  5039. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  5040. this.matrixWorldNeedsUpdate = false;
  5041. this.layers = new Layers();
  5042. this.visible = true;
  5043. this.castShadow = false;
  5044. this.receiveShadow = false;
  5045. this.frustumCulled = true;
  5046. this.renderOrder = 0;
  5047. this.userData = {};
  5048. }
  5049. Object3D.DefaultUp = new Vector3(0, 1, 0);
  5050. Object3D.DefaultMatrixAutoUpdate = true;
  5051. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5052. constructor: Object3D,
  5053. isObject3D: true,
  5054. onBeforeRender: function () {},
  5055. onAfterRender: function () {},
  5056. applyMatrix: function (matrix) {
  5057. if (this.matrixAutoUpdate) this.updateMatrix();
  5058. this.matrix.premultiply(matrix);
  5059. this.matrix.decompose(this.position, this.quaternion, this.scale);
  5060. },
  5061. applyQuaternion: function (q) {
  5062. this.quaternion.premultiply(q);
  5063. return this;
  5064. },
  5065. setRotationFromAxisAngle: function (axis, angle) {
  5066. // assumes axis is normalized
  5067. this.quaternion.setFromAxisAngle(axis, angle);
  5068. },
  5069. setRotationFromEuler: function (euler) {
  5070. this.quaternion.setFromEuler(euler, true);
  5071. },
  5072. setRotationFromMatrix: function (m) {
  5073. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5074. this.quaternion.setFromRotationMatrix(m);
  5075. },
  5076. setRotationFromQuaternion: function (q) {
  5077. // assumes q is normalized
  5078. this.quaternion.copy(q);
  5079. },
  5080. rotateOnAxis: function (axis, angle) {
  5081. // rotate object on axis in object space
  5082. // axis is assumed to be normalized
  5083. _q1.setFromAxisAngle(axis, angle);
  5084. this.quaternion.multiply(_q1);
  5085. return this;
  5086. },
  5087. rotateOnWorldAxis: function (axis, angle) {
  5088. // rotate object on axis in world space
  5089. // axis is assumed to be normalized
  5090. // method assumes no rotated parent
  5091. _q1.setFromAxisAngle(axis, angle);
  5092. this.quaternion.premultiply(_q1);
  5093. return this;
  5094. },
  5095. rotateX: function (angle) {
  5096. return this.rotateOnAxis(_xAxis, angle);
  5097. },
  5098. rotateY: function (angle) {
  5099. return this.rotateOnAxis(_yAxis, angle);
  5100. },
  5101. rotateZ: function (angle) {
  5102. return this.rotateOnAxis(_zAxis, angle);
  5103. },
  5104. translateOnAxis: function (axis, distance) {
  5105. // translate object by distance along axis in object space
  5106. // axis is assumed to be normalized
  5107. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  5108. this.position.add(_v1$1.multiplyScalar(distance));
  5109. return this;
  5110. },
  5111. translateX: function (distance) {
  5112. return this.translateOnAxis(_xAxis, distance);
  5113. },
  5114. translateY: function (distance) {
  5115. return this.translateOnAxis(_yAxis, distance);
  5116. },
  5117. translateZ: function (distance) {
  5118. return this.translateOnAxis(_zAxis, distance);
  5119. },
  5120. localToWorld: function (vector) {
  5121. return vector.applyMatrix4(this.matrixWorld);
  5122. },
  5123. worldToLocal: function (vector) {
  5124. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  5125. },
  5126. lookAt: function (x, y, z) {
  5127. // This method does not support objects having non-uniformly-scaled parent(s)
  5128. if (x.isVector3) {
  5129. _target.copy(x);
  5130. } else {
  5131. _target.set(x, y, z);
  5132. }
  5133. var parent = this.parent;
  5134. this.updateWorldMatrix(true, false);
  5135. _position.setFromMatrixPosition(this.matrixWorld);
  5136. if (this.isCamera || this.isLight) {
  5137. _m1$1.lookAt(_position, _target, this.up);
  5138. } else {
  5139. _m1$1.lookAt(_target, _position, this.up);
  5140. }
  5141. this.quaternion.setFromRotationMatrix(_m1$1);
  5142. if (parent) {
  5143. _m1$1.extractRotation(parent.matrixWorld);
  5144. _q1.setFromRotationMatrix(_m1$1);
  5145. this.quaternion.premultiply(_q1.inverse());
  5146. }
  5147. },
  5148. add: function (object) {
  5149. if (arguments.length > 1) {
  5150. for (var i = 0; i < arguments.length; i++) {
  5151. this.add(arguments[i]);
  5152. }
  5153. return this;
  5154. }
  5155. if (object === this) {
  5156. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  5157. return this;
  5158. }
  5159. if (object && object.isObject3D) {
  5160. if (object.parent !== null) {
  5161. object.parent.remove(object);
  5162. }
  5163. object.parent = this;
  5164. this.children.push(object);
  5165. object.dispatchEvent(_addedEvent);
  5166. } else {
  5167. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  5168. }
  5169. return this;
  5170. },
  5171. remove: function (object) {
  5172. if (arguments.length > 1) {
  5173. for (var i = 0; i < arguments.length; i++) {
  5174. this.remove(arguments[i]);
  5175. }
  5176. return this;
  5177. }
  5178. var index = this.children.indexOf(object);
  5179. if (index !== -1) {
  5180. object.parent = null;
  5181. this.children.splice(index, 1);
  5182. object.dispatchEvent(_removedEvent);
  5183. }
  5184. return this;
  5185. },
  5186. attach: function (object) {
  5187. // adds object as a child of this, while maintaining the object's world transform
  5188. this.updateWorldMatrix(true, false);
  5189. _m1$1.getInverse(this.matrixWorld);
  5190. if (object.parent !== null) {
  5191. object.parent.updateWorldMatrix(true, false);
  5192. _m1$1.multiply(object.parent.matrixWorld);
  5193. }
  5194. object.applyMatrix(_m1$1);
  5195. object.updateWorldMatrix(false, false);
  5196. this.add(object);
  5197. return this;
  5198. },
  5199. getObjectById: function (id) {
  5200. return this.getObjectByProperty('id', id);
  5201. },
  5202. getObjectByName: function (name) {
  5203. return this.getObjectByProperty('name', name);
  5204. },
  5205. getObjectByProperty: function (name, value) {
  5206. if (this[name] === value) return this;
  5207. for (var i = 0, l = this.children.length; i < l; i++) {
  5208. var child = this.children[i];
  5209. var object = child.getObjectByProperty(name, value);
  5210. if (object !== undefined) {
  5211. return object;
  5212. }
  5213. }
  5214. return undefined;
  5215. },
  5216. getWorldPosition: function (target) {
  5217. if (target === undefined) {
  5218. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  5219. target = new Vector3();
  5220. }
  5221. this.updateMatrixWorld(true);
  5222. return target.setFromMatrixPosition(this.matrixWorld);
  5223. },
  5224. getWorldQuaternion: function (target) {
  5225. if (target === undefined) {
  5226. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  5227. target = new Quaternion();
  5228. }
  5229. this.updateMatrixWorld(true);
  5230. this.matrixWorld.decompose(_position, target, _scale);
  5231. return target;
  5232. },
  5233. getWorldScale: function (target) {
  5234. if (target === undefined) {
  5235. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  5236. target = new Vector3();
  5237. }
  5238. this.updateMatrixWorld(true);
  5239. this.matrixWorld.decompose(_position, _quaternion$2, target);
  5240. return target;
  5241. },
  5242. getWorldDirection: function (target) {
  5243. if (target === undefined) {
  5244. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  5245. target = new Vector3();
  5246. }
  5247. this.updateMatrixWorld(true);
  5248. var e = this.matrixWorld.elements;
  5249. return target.set(e[8], e[9], e[10]).normalize();
  5250. },
  5251. raycast: function () {},
  5252. traverse: function (callback) {
  5253. callback(this);
  5254. var children = this.children;
  5255. for (var i = 0, l = children.length; i < l; i++) {
  5256. children[i].traverse(callback);
  5257. }
  5258. },
  5259. traverseVisible: function (callback) {
  5260. if (this.visible === false) return;
  5261. callback(this);
  5262. var children = this.children;
  5263. for (var i = 0, l = children.length; i < l; i++) {
  5264. children[i].traverseVisible(callback);
  5265. }
  5266. },
  5267. traverseAncestors: function (callback) {
  5268. var parent = this.parent;
  5269. if (parent !== null) {
  5270. callback(parent);
  5271. parent.traverseAncestors(callback);
  5272. }
  5273. },
  5274. updateMatrix: function () {
  5275. this.matrix.compose(this.position, this.quaternion, this.scale);
  5276. this.matrixWorldNeedsUpdate = true;
  5277. },
  5278. updateMatrixWorld: function (force) {
  5279. if (this.matrixAutoUpdate) this.updateMatrix();
  5280. if (this.matrixWorldNeedsUpdate || force) {
  5281. if (this.parent === null) {
  5282. this.matrixWorld.copy(this.matrix);
  5283. } else {
  5284. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5285. }
  5286. this.matrixWorldNeedsUpdate = false;
  5287. force = true;
  5288. } // update children
  5289. var children = this.children;
  5290. for (var i = 0, l = children.length; i < l; i++) {
  5291. children[i].updateMatrixWorld(force);
  5292. }
  5293. },
  5294. updateWorldMatrix: function (updateParents, updateChildren) {
  5295. var parent = this.parent;
  5296. if (updateParents === true && parent !== null) {
  5297. parent.updateWorldMatrix(true, false);
  5298. }
  5299. if (this.matrixAutoUpdate) this.updateMatrix();
  5300. if (this.parent === null) {
  5301. this.matrixWorld.copy(this.matrix);
  5302. } else {
  5303. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5304. } // update children
  5305. if (updateChildren === true) {
  5306. var children = this.children;
  5307. for (var i = 0, l = children.length; i < l; i++) {
  5308. children[i].updateWorldMatrix(false, true);
  5309. }
  5310. }
  5311. },
  5312. toJSON: function (meta) {
  5313. // meta is a string when called from JSON.stringify
  5314. var isRootObject = meta === undefined || typeof meta === 'string';
  5315. var output = {}; // meta is a hash used to collect geometries, materials.
  5316. // not providing it implies that this is the root object
  5317. // being serialized.
  5318. if (isRootObject) {
  5319. // initialize meta obj
  5320. meta = {
  5321. geometries: {},
  5322. materials: {},
  5323. textures: {},
  5324. images: {},
  5325. shapes: {}
  5326. };
  5327. output.metadata = {
  5328. version: 4.5,
  5329. type: 'Object',
  5330. generator: 'Object3D.toJSON'
  5331. };
  5332. } // standard Object3D serialization
  5333. var object = {};
  5334. object.uuid = this.uuid;
  5335. object.type = this.type;
  5336. if (this.name !== '') object.name = this.name;
  5337. if (this.castShadow === true) object.castShadow = true;
  5338. if (this.receiveShadow === true) object.receiveShadow = true;
  5339. if (this.visible === false) object.visible = false;
  5340. if (this.frustumCulled === false) object.frustumCulled = false;
  5341. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5342. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5343. object.layers = this.layers.mask;
  5344. object.matrix = this.matrix.toArray();
  5345. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5346. if (this.isMesh && this.drawMode !== TrianglesDrawMode) object.drawMode = this.drawMode; //
  5347. function serialize(library, element) {
  5348. if (library[element.uuid] === undefined) {
  5349. library[element.uuid] = element.toJSON(meta);
  5350. }
  5351. return element.uuid;
  5352. }
  5353. if (this.isMesh || this.isLine || this.isPoints) {
  5354. object.geometry = serialize(meta.geometries, this.geometry);
  5355. var parameters = this.geometry.parameters;
  5356. if (parameters !== undefined && parameters.shapes !== undefined) {
  5357. var shapes = parameters.shapes;
  5358. if (Array.isArray(shapes)) {
  5359. for (var i = 0, l = shapes.length; i < l; i++) {
  5360. var shape = shapes[i];
  5361. serialize(meta.shapes, shape);
  5362. }
  5363. } else {
  5364. serialize(meta.shapes, shapes);
  5365. }
  5366. }
  5367. }
  5368. if (this.material !== undefined) {
  5369. if (Array.isArray(this.material)) {
  5370. var uuids = [];
  5371. for (var i = 0, l = this.material.length; i < l; i++) {
  5372. uuids.push(serialize(meta.materials, this.material[i]));
  5373. }
  5374. object.material = uuids;
  5375. } else {
  5376. object.material = serialize(meta.materials, this.material);
  5377. }
  5378. } //
  5379. if (this.children.length > 0) {
  5380. object.children = [];
  5381. for (var i = 0; i < this.children.length; i++) {
  5382. object.children.push(this.children[i].toJSON(meta).object);
  5383. }
  5384. }
  5385. if (isRootObject) {
  5386. var geometries = extractFromCache(meta.geometries);
  5387. var materials = extractFromCache(meta.materials);
  5388. var textures = extractFromCache(meta.textures);
  5389. var images = extractFromCache(meta.images);
  5390. var shapes = extractFromCache(meta.shapes);
  5391. if (geometries.length > 0) output.geometries = geometries;
  5392. if (materials.length > 0) output.materials = materials;
  5393. if (textures.length > 0) output.textures = textures;
  5394. if (images.length > 0) output.images = images;
  5395. if (shapes.length > 0) output.shapes = shapes;
  5396. }
  5397. output.object = object;
  5398. return output; // extract data from the cache hash
  5399. // remove metadata on each item
  5400. // and return as array
  5401. function extractFromCache(cache) {
  5402. var values = [];
  5403. for (var key in cache) {
  5404. var data = cache[key];
  5405. delete data.metadata;
  5406. values.push(data);
  5407. }
  5408. return values;
  5409. }
  5410. },
  5411. clone: function (recursive) {
  5412. return new this.constructor().copy(this, recursive);
  5413. },
  5414. copy: function (source, recursive) {
  5415. if (recursive === undefined) recursive = true;
  5416. this.name = source.name;
  5417. this.up.copy(source.up);
  5418. this.position.copy(source.position);
  5419. this.quaternion.copy(source.quaternion);
  5420. this.scale.copy(source.scale);
  5421. this.matrix.copy(source.matrix);
  5422. this.matrixWorld.copy(source.matrixWorld);
  5423. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5424. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5425. this.layers.mask = source.layers.mask;
  5426. this.visible = source.visible;
  5427. this.castShadow = source.castShadow;
  5428. this.receiveShadow = source.receiveShadow;
  5429. this.frustumCulled = source.frustumCulled;
  5430. this.renderOrder = source.renderOrder;
  5431. this.userData = JSON.parse(JSON.stringify(source.userData));
  5432. if (recursive === true) {
  5433. for (var i = 0; i < source.children.length; i++) {
  5434. var child = source.children[i];
  5435. this.add(child.clone());
  5436. }
  5437. }
  5438. return this;
  5439. }
  5440. });
  5441. /**
  5442. * @author mrdoob / http://mrdoob.com/
  5443. */
  5444. function Scene() {
  5445. Object3D.call(this);
  5446. this.type = 'Scene';
  5447. this.background = null;
  5448. this.fog = null;
  5449. this.overrideMaterial = null;
  5450. this.autoUpdate = true; // checked by the renderer
  5451. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  5452. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  5453. detail: this
  5454. })); // eslint-disable-line no-undef
  5455. }
  5456. }
  5457. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  5458. constructor: Scene,
  5459. isScene: true,
  5460. copy: function (source, recursive) {
  5461. Object3D.prototype.copy.call(this, source, recursive);
  5462. if (source.background !== null) this.background = source.background.clone();
  5463. if (source.fog !== null) this.fog = source.fog.clone();
  5464. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  5465. this.autoUpdate = source.autoUpdate;
  5466. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5467. return this;
  5468. },
  5469. toJSON: function (meta) {
  5470. var data = Object3D.prototype.toJSON.call(this, meta);
  5471. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  5472. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  5473. return data;
  5474. },
  5475. dispose: function () {
  5476. this.dispatchEvent({
  5477. type: 'dispose'
  5478. });
  5479. }
  5480. });
  5481. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  5482. var _vector$2 = new Vector3(); // triangle centered vertices
  5483. var _v0 = new Vector3();
  5484. var _v1$2 = new Vector3();
  5485. var _v2 = new Vector3(); // triangle edge vectors
  5486. var _f0 = new Vector3();
  5487. var _f1 = new Vector3();
  5488. var _f2 = new Vector3();
  5489. var _center = new Vector3();
  5490. var _extents = new Vector3();
  5491. var _triangleNormal = new Vector3();
  5492. var _testAxis = new Vector3();
  5493. /**
  5494. * @author bhouston / http://clara.io
  5495. * @author WestLangley / http://github.com/WestLangley
  5496. */
  5497. function Box3(min, max) {
  5498. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  5499. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  5500. }
  5501. Object.assign(Box3.prototype, {
  5502. isBox3: true,
  5503. set: function (min, max) {
  5504. this.min.copy(min);
  5505. this.max.copy(max);
  5506. return this;
  5507. },
  5508. setFromArray: function (array) {
  5509. var minX = +Infinity;
  5510. var minY = +Infinity;
  5511. var minZ = +Infinity;
  5512. var maxX = -Infinity;
  5513. var maxY = -Infinity;
  5514. var maxZ = -Infinity;
  5515. for (var i = 0, l = array.length; i < l; i += 3) {
  5516. var x = array[i];
  5517. var y = array[i + 1];
  5518. var z = array[i + 2];
  5519. if (x < minX) minX = x;
  5520. if (y < minY) minY = y;
  5521. if (z < minZ) minZ = z;
  5522. if (x > maxX) maxX = x;
  5523. if (y > maxY) maxY = y;
  5524. if (z > maxZ) maxZ = z;
  5525. }
  5526. this.min.set(minX, minY, minZ);
  5527. this.max.set(maxX, maxY, maxZ);
  5528. return this;
  5529. },
  5530. setFromBufferAttribute: function (attribute) {
  5531. var minX = +Infinity;
  5532. var minY = +Infinity;
  5533. var minZ = +Infinity;
  5534. var maxX = -Infinity;
  5535. var maxY = -Infinity;
  5536. var maxZ = -Infinity;
  5537. for (var i = 0, l = attribute.count; i < l; i++) {
  5538. var x = attribute.getX(i);
  5539. var y = attribute.getY(i);
  5540. var z = attribute.getZ(i);
  5541. if (x < minX) minX = x;
  5542. if (y < minY) minY = y;
  5543. if (z < minZ) minZ = z;
  5544. if (x > maxX) maxX = x;
  5545. if (y > maxY) maxY = y;
  5546. if (z > maxZ) maxZ = z;
  5547. }
  5548. this.min.set(minX, minY, minZ);
  5549. this.max.set(maxX, maxY, maxZ);
  5550. return this;
  5551. },
  5552. setFromPoints: function (points) {
  5553. this.makeEmpty();
  5554. for (var i = 0, il = points.length; i < il; i++) {
  5555. this.expandByPoint(points[i]);
  5556. }
  5557. return this;
  5558. },
  5559. setFromCenterAndSize: function (center, size) {
  5560. var halfSize = _vector$2.copy(size).multiplyScalar(0.5);
  5561. this.min.copy(center).sub(halfSize);
  5562. this.max.copy(center).add(halfSize);
  5563. return this;
  5564. },
  5565. setFromObject: function (object) {
  5566. this.makeEmpty();
  5567. return this.expandByObject(object);
  5568. },
  5569. clone: function () {
  5570. return new this.constructor().copy(this);
  5571. },
  5572. copy: function (box) {
  5573. this.min.copy(box.min);
  5574. this.max.copy(box.max);
  5575. return this;
  5576. },
  5577. makeEmpty: function () {
  5578. this.min.x = this.min.y = this.min.z = +Infinity;
  5579. this.max.x = this.max.y = this.max.z = -Infinity;
  5580. return this;
  5581. },
  5582. isEmpty: function () {
  5583. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5584. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  5585. },
  5586. getCenter: function (target) {
  5587. if (target === undefined) {
  5588. console.warn('THREE.Box3: .getCenter() target is now required');
  5589. target = new Vector3();
  5590. }
  5591. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  5592. },
  5593. getSize: function (target) {
  5594. if (target === undefined) {
  5595. console.warn('THREE.Box3: .getSize() target is now required');
  5596. target = new Vector3();
  5597. }
  5598. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  5599. },
  5600. expandByPoint: function (point) {
  5601. this.min.min(point);
  5602. this.max.max(point);
  5603. return this;
  5604. },
  5605. expandByVector: function (vector) {
  5606. this.min.sub(vector);
  5607. this.max.add(vector);
  5608. return this;
  5609. },
  5610. expandByScalar: function (scalar) {
  5611. this.min.addScalar(-scalar);
  5612. this.max.addScalar(scalar);
  5613. return this;
  5614. },
  5615. expandByObject: function (object) {
  5616. var i, l; // Computes the world-axis-aligned bounding box of an object (including its children),
  5617. // accounting for both the object's, and children's, world transforms
  5618. object.updateWorldMatrix(false, false);
  5619. var geometry = object.geometry;
  5620. if (geometry !== undefined) {
  5621. if (geometry.isGeometry) {
  5622. var vertices = geometry.vertices;
  5623. for (i = 0, l = vertices.length; i < l; i++) {
  5624. _vector$2.copy(vertices[i]);
  5625. _vector$2.applyMatrix4(object.matrixWorld);
  5626. this.expandByPoint(_vector$2);
  5627. }
  5628. } else if (geometry.isBufferGeometry) {
  5629. var attribute = geometry.attributes.position;
  5630. if (attribute !== undefined) {
  5631. for (i = 0, l = attribute.count; i < l; i++) {
  5632. _vector$2.fromBufferAttribute(attribute, i).applyMatrix4(object.matrixWorld);
  5633. this.expandByPoint(_vector$2);
  5634. }
  5635. }
  5636. }
  5637. } //
  5638. var children = object.children;
  5639. for (i = 0, l = children.length; i < l; i++) {
  5640. this.expandByObject(children[i]);
  5641. }
  5642. return this;
  5643. },
  5644. containsPoint: function (point) {
  5645. 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;
  5646. },
  5647. containsBox: function (box) {
  5648. 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;
  5649. },
  5650. getParameter: function (point, target) {
  5651. // This can potentially have a divide by zero if the box
  5652. // has a size dimension of 0.
  5653. if (target === undefined) {
  5654. console.warn('THREE.Box3: .getParameter() target is now required');
  5655. target = new Vector3();
  5656. }
  5657. 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));
  5658. },
  5659. intersectsBox: function (box) {
  5660. // using 6 splitting planes to rule out intersections.
  5661. 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;
  5662. },
  5663. intersectsSphere: function (sphere) {
  5664. // Find the point on the AABB closest to the sphere center.
  5665. this.clampPoint(sphere.center, _vector$2); // If that point is inside the sphere, the AABB and sphere intersect.
  5666. return _vector$2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  5667. },
  5668. intersectsPlane: function (plane) {
  5669. // We compute the minimum and maximum dot product values. If those values
  5670. // are on the same side (back or front) of the plane, then there is no intersection.
  5671. var min, max;
  5672. if (plane.normal.x > 0) {
  5673. min = plane.normal.x * this.min.x;
  5674. max = plane.normal.x * this.max.x;
  5675. } else {
  5676. min = plane.normal.x * this.max.x;
  5677. max = plane.normal.x * this.min.x;
  5678. }
  5679. if (plane.normal.y > 0) {
  5680. min += plane.normal.y * this.min.y;
  5681. max += plane.normal.y * this.max.y;
  5682. } else {
  5683. min += plane.normal.y * this.max.y;
  5684. max += plane.normal.y * this.min.y;
  5685. }
  5686. if (plane.normal.z > 0) {
  5687. min += plane.normal.z * this.min.z;
  5688. max += plane.normal.z * this.max.z;
  5689. } else {
  5690. min += plane.normal.z * this.max.z;
  5691. max += plane.normal.z * this.min.z;
  5692. }
  5693. return min <= -plane.constant && max >= -plane.constant;
  5694. },
  5695. intersectsTriangle: function (triangle) {
  5696. if (this.isEmpty()) {
  5697. return false;
  5698. } // compute box center and extents
  5699. this.getCenter(_center);
  5700. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  5701. _v0.subVectors(triangle.a, _center);
  5702. _v1$2.subVectors(triangle.b, _center);
  5703. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  5704. _f0.subVectors(_v1$2, _v0);
  5705. _f1.subVectors(_v2, _v1$2);
  5706. _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
  5707. // 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
  5708. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  5709. 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];
  5710. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5711. return false;
  5712. } // test 3 face normals from the aabb
  5713. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  5714. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  5715. return false;
  5716. } // finally testing the face normal of the triangle
  5717. // use already existing triangle edge vectors here
  5718. _triangleNormal.crossVectors(_f0, _f1);
  5719. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  5720. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  5721. },
  5722. clampPoint: function (point, target) {
  5723. if (target === undefined) {
  5724. console.warn('THREE.Box3: .clampPoint() target is now required');
  5725. target = new Vector3();
  5726. }
  5727. return target.copy(point).clamp(this.min, this.max);
  5728. },
  5729. distanceToPoint: function (point) {
  5730. var clampedPoint = _vector$2.copy(point).clamp(this.min, this.max);
  5731. return clampedPoint.sub(point).length();
  5732. },
  5733. getBoundingSphere: function (target) {
  5734. if (target === undefined) {
  5735. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  5736. }
  5737. this.getCenter(target.center);
  5738. target.radius = this.getSize(_vector$2).length() * 0.5;
  5739. return target;
  5740. },
  5741. intersect: function (box) {
  5742. this.min.max(box.min);
  5743. 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.
  5744. if (this.isEmpty()) this.makeEmpty();
  5745. return this;
  5746. },
  5747. union: function (box) {
  5748. this.min.min(box.min);
  5749. this.max.max(box.max);
  5750. return this;
  5751. },
  5752. applyMatrix4: function (matrix) {
  5753. // transform of empty box is an empty box.
  5754. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5755. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  5756. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  5757. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  5758. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  5759. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  5760. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  5761. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  5762. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  5763. this.setFromPoints(_points);
  5764. return this;
  5765. },
  5766. translate: function (offset) {
  5767. this.min.add(offset);
  5768. this.max.add(offset);
  5769. return this;
  5770. },
  5771. equals: function (box) {
  5772. return box.min.equals(this.min) && box.max.equals(this.max);
  5773. }
  5774. });
  5775. function satForAxes(axes, v0, v1, v2, extents) {
  5776. var i, j;
  5777. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  5778. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  5779. 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
  5780. var p0 = v0.dot(_testAxis);
  5781. var p1 = v1.dot(_testAxis);
  5782. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  5783. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  5784. // points of the projected triangle are outside the projected half-length of the aabb
  5785. // the axis is seperating and we can exit
  5786. return false;
  5787. }
  5788. }
  5789. return true;
  5790. }
  5791. var _box = new Box3();
  5792. /**
  5793. * @author bhouston / http://clara.io
  5794. * @author mrdoob / http://mrdoob.com/
  5795. */
  5796. function Sphere(center, radius) {
  5797. this.center = center !== undefined ? center : new Vector3();
  5798. this.radius = radius !== undefined ? radius : 0;
  5799. }
  5800. Object.assign(Sphere.prototype, {
  5801. set: function (center, radius) {
  5802. this.center.copy(center);
  5803. this.radius = radius;
  5804. return this;
  5805. },
  5806. setFromPoints: function (points, optionalCenter) {
  5807. var center = this.center;
  5808. if (optionalCenter !== undefined) {
  5809. center.copy(optionalCenter);
  5810. } else {
  5811. _box.setFromPoints(points).getCenter(center);
  5812. }
  5813. var maxRadiusSq = 0;
  5814. for (var i = 0, il = points.length; i < il; i++) {
  5815. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  5816. }
  5817. this.radius = Math.sqrt(maxRadiusSq);
  5818. return this;
  5819. },
  5820. clone: function () {
  5821. return new this.constructor().copy(this);
  5822. },
  5823. copy: function (sphere) {
  5824. this.center.copy(sphere.center);
  5825. this.radius = sphere.radius;
  5826. return this;
  5827. },
  5828. empty: function () {
  5829. return this.radius <= 0;
  5830. },
  5831. containsPoint: function (point) {
  5832. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  5833. },
  5834. distanceToPoint: function (point) {
  5835. return point.distanceTo(this.center) - this.radius;
  5836. },
  5837. intersectsSphere: function (sphere) {
  5838. var radiusSum = this.radius + sphere.radius;
  5839. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  5840. },
  5841. intersectsBox: function (box) {
  5842. return box.intersectsSphere(this);
  5843. },
  5844. intersectsPlane: function (plane) {
  5845. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  5846. },
  5847. clampPoint: function (point, target) {
  5848. var deltaLengthSq = this.center.distanceToSquared(point);
  5849. if (target === undefined) {
  5850. console.warn('THREE.Sphere: .clampPoint() target is now required');
  5851. target = new Vector3();
  5852. }
  5853. target.copy(point);
  5854. if (deltaLengthSq > this.radius * this.radius) {
  5855. target.sub(this.center).normalize();
  5856. target.multiplyScalar(this.radius).add(this.center);
  5857. }
  5858. return target;
  5859. },
  5860. getBoundingBox: function (target) {
  5861. if (target === undefined) {
  5862. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  5863. target = new Box3();
  5864. }
  5865. target.set(this.center, this.center);
  5866. target.expandByScalar(this.radius);
  5867. return target;
  5868. },
  5869. applyMatrix4: function (matrix) {
  5870. this.center.applyMatrix4(matrix);
  5871. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5872. return this;
  5873. },
  5874. translate: function (offset) {
  5875. this.center.add(offset);
  5876. return this;
  5877. },
  5878. equals: function (sphere) {
  5879. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  5880. }
  5881. });
  5882. var _vector$3 = new Vector3();
  5883. var _segCenter = new Vector3();
  5884. var _segDir = new Vector3();
  5885. var _diff = new Vector3();
  5886. var _edge1 = new Vector3();
  5887. var _edge2 = new Vector3();
  5888. var _normal = new Vector3();
  5889. /**
  5890. * @author bhouston / http://clara.io
  5891. */
  5892. function Ray(origin, direction) {
  5893. this.origin = origin !== undefined ? origin : new Vector3();
  5894. this.direction = direction !== undefined ? direction : new Vector3();
  5895. }
  5896. Object.assign(Ray.prototype, {
  5897. set: function (origin, direction) {
  5898. this.origin.copy(origin);
  5899. this.direction.copy(direction);
  5900. return this;
  5901. },
  5902. clone: function () {
  5903. return new this.constructor().copy(this);
  5904. },
  5905. copy: function (ray) {
  5906. this.origin.copy(ray.origin);
  5907. this.direction.copy(ray.direction);
  5908. return this;
  5909. },
  5910. at: function (t, target) {
  5911. if (target === undefined) {
  5912. console.warn('THREE.Ray: .at() target is now required');
  5913. target = new Vector3();
  5914. }
  5915. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  5916. },
  5917. lookAt: function (v) {
  5918. this.direction.copy(v).sub(this.origin).normalize();
  5919. return this;
  5920. },
  5921. recast: function (t) {
  5922. this.origin.copy(this.at(t, _vector$3));
  5923. return this;
  5924. },
  5925. closestPointToPoint: function (point, target) {
  5926. if (target === undefined) {
  5927. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  5928. target = new Vector3();
  5929. }
  5930. target.subVectors(point, this.origin);
  5931. var directionDistance = target.dot(this.direction);
  5932. if (directionDistance < 0) {
  5933. return target.copy(this.origin);
  5934. }
  5935. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5936. },
  5937. distanceToPoint: function (point) {
  5938. return Math.sqrt(this.distanceSqToPoint(point));
  5939. },
  5940. distanceSqToPoint: function (point) {
  5941. var directionDistance = _vector$3.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  5942. if (directionDistance < 0) {
  5943. return this.origin.distanceToSquared(point);
  5944. }
  5945. _vector$3.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  5946. return _vector$3.distanceToSquared(point);
  5947. },
  5948. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  5949. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  5950. // It returns the min distance between the ray and the segment
  5951. // defined by v0 and v1
  5952. // It can also set two optional targets :
  5953. // - The closest point on the ray
  5954. // - The closest point on the segment
  5955. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  5956. _segDir.copy(v1).sub(v0).normalize();
  5957. _diff.copy(this.origin).sub(_segCenter);
  5958. var segExtent = v0.distanceTo(v1) * 0.5;
  5959. var a01 = -this.direction.dot(_segDir);
  5960. var b0 = _diff.dot(this.direction);
  5961. var b1 = -_diff.dot(_segDir);
  5962. var c = _diff.lengthSq();
  5963. var det = Math.abs(1 - a01 * a01);
  5964. var s0, s1, sqrDist, extDet;
  5965. if (det > 0) {
  5966. // The ray and segment are not parallel.
  5967. s0 = a01 * b1 - b0;
  5968. s1 = a01 * b0 - b1;
  5969. extDet = segExtent * det;
  5970. if (s0 >= 0) {
  5971. if (s1 >= -extDet) {
  5972. if (s1 <= extDet) {
  5973. // region 0
  5974. // Minimum at interior points of ray and segment.
  5975. var invDet = 1 / det;
  5976. s0 *= invDet;
  5977. s1 *= invDet;
  5978. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  5979. } else {
  5980. // region 1
  5981. s1 = segExtent;
  5982. s0 = Math.max(0, -(a01 * s1 + b0));
  5983. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5984. }
  5985. } else {
  5986. // region 5
  5987. s1 = -segExtent;
  5988. s0 = Math.max(0, -(a01 * s1 + b0));
  5989. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5990. }
  5991. } else {
  5992. if (s1 <= -extDet) {
  5993. // region 4
  5994. s0 = Math.max(0, -(-a01 * segExtent + b0));
  5995. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  5996. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  5997. } else if (s1 <= extDet) {
  5998. // region 3
  5999. s0 = 0;
  6000. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  6001. sqrDist = s1 * (s1 + 2 * b1) + c;
  6002. } else {
  6003. // region 2
  6004. s0 = Math.max(0, -(a01 * segExtent + b0));
  6005. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  6006. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6007. }
  6008. }
  6009. } else {
  6010. // Ray and segment are parallel.
  6011. s1 = a01 > 0 ? -segExtent : segExtent;
  6012. s0 = Math.max(0, -(a01 * s1 + b0));
  6013. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  6014. }
  6015. if (optionalPointOnRay) {
  6016. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  6017. }
  6018. if (optionalPointOnSegment) {
  6019. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  6020. }
  6021. return sqrDist;
  6022. },
  6023. intersectSphere: function (sphere, target) {
  6024. _vector$3.subVectors(sphere.center, this.origin);
  6025. var tca = _vector$3.dot(this.direction);
  6026. var d2 = _vector$3.dot(_vector$3) - tca * tca;
  6027. var radius2 = sphere.radius * sphere.radius;
  6028. if (d2 > radius2) return null;
  6029. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  6030. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  6031. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  6032. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  6033. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6034. // in order to always return an intersect point that is in front of the ray.
  6035. 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
  6036. return this.at(t0, target);
  6037. },
  6038. intersectsSphere: function (sphere) {
  6039. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  6040. },
  6041. distanceToPlane: function (plane) {
  6042. var denominator = plane.normal.dot(this.direction);
  6043. if (denominator === 0) {
  6044. // line is coplanar, return origin
  6045. if (plane.distanceToPoint(this.origin) === 0) {
  6046. return 0;
  6047. } // Null is preferable to undefined since undefined means.... it is undefined
  6048. return null;
  6049. }
  6050. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  6051. return t >= 0 ? t : null;
  6052. },
  6053. intersectPlane: function (plane, target) {
  6054. var t = this.distanceToPlane(plane);
  6055. if (t === null) {
  6056. return null;
  6057. }
  6058. return this.at(t, target);
  6059. },
  6060. intersectsPlane: function (plane) {
  6061. // check if the ray lies on the plane first
  6062. var distToPoint = plane.distanceToPoint(this.origin);
  6063. if (distToPoint === 0) {
  6064. return true;
  6065. }
  6066. var denominator = plane.normal.dot(this.direction);
  6067. if (denominator * distToPoint < 0) {
  6068. return true;
  6069. } // ray origin is behind the plane (and is pointing behind it)
  6070. return false;
  6071. },
  6072. intersectBox: function (box, target) {
  6073. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6074. var invdirx = 1 / this.direction.x,
  6075. invdiry = 1 / this.direction.y,
  6076. invdirz = 1 / this.direction.z;
  6077. var origin = this.origin;
  6078. if (invdirx >= 0) {
  6079. tmin = (box.min.x - origin.x) * invdirx;
  6080. tmax = (box.max.x - origin.x) * invdirx;
  6081. } else {
  6082. tmin = (box.max.x - origin.x) * invdirx;
  6083. tmax = (box.min.x - origin.x) * invdirx;
  6084. }
  6085. if (invdiry >= 0) {
  6086. tymin = (box.min.y - origin.y) * invdiry;
  6087. tymax = (box.max.y - origin.y) * invdiry;
  6088. } else {
  6089. tymin = (box.max.y - origin.y) * invdiry;
  6090. tymax = (box.min.y - origin.y) * invdiry;
  6091. }
  6092. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  6093. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6094. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  6095. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  6096. if (invdirz >= 0) {
  6097. tzmin = (box.min.z - origin.z) * invdirz;
  6098. tzmax = (box.max.z - origin.z) * invdirz;
  6099. } else {
  6100. tzmin = (box.max.z - origin.z) * invdirz;
  6101. tzmax = (box.min.z - origin.z) * invdirz;
  6102. }
  6103. if (tmin > tzmax || tzmin > tmax) return null;
  6104. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  6105. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  6106. if (tmax < 0) return null;
  6107. return this.at(tmin >= 0 ? tmin : tmax, target);
  6108. },
  6109. intersectsBox: function (box) {
  6110. return this.intersectBox(box, _vector$3) !== null;
  6111. },
  6112. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  6113. // Compute the offset origin, edges, and normal.
  6114. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6115. _edge1.subVectors(b, a);
  6116. _edge2.subVectors(c, a);
  6117. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6118. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6119. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6120. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6121. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6122. var DdN = this.direction.dot(_normal);
  6123. var sign;
  6124. if (DdN > 0) {
  6125. if (backfaceCulling) return null;
  6126. sign = 1;
  6127. } else if (DdN < 0) {
  6128. sign = -1;
  6129. DdN = -DdN;
  6130. } else {
  6131. return null;
  6132. }
  6133. _diff.subVectors(this.origin, a);
  6134. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  6135. if (DdQxE2 < 0) {
  6136. return null;
  6137. }
  6138. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  6139. if (DdE1xQ < 0) {
  6140. return null;
  6141. } // b1+b2 > 1, no intersection
  6142. if (DdQxE2 + DdE1xQ > DdN) {
  6143. return null;
  6144. } // Line intersects triangle, check if ray does.
  6145. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  6146. if (QdN < 0) {
  6147. return null;
  6148. } // Ray intersects triangle.
  6149. return this.at(QdN / DdN, target);
  6150. },
  6151. applyMatrix4: function (matrix4) {
  6152. this.origin.applyMatrix4(matrix4);
  6153. this.direction.transformDirection(matrix4);
  6154. return this;
  6155. },
  6156. equals: function (ray) {
  6157. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  6158. }
  6159. });
  6160. /**
  6161. * @author bhouston / http://clara.io
  6162. * @author mrdoob / http://mrdoob.com/
  6163. */
  6164. var _v0$1 = new Vector3();
  6165. var _v1$3 = new Vector3();
  6166. var _v2$1 = new Vector3();
  6167. var _v3 = new Vector3();
  6168. var _vab = new Vector3();
  6169. var _vac = new Vector3();
  6170. var _vbc = new Vector3();
  6171. var _vap = new Vector3();
  6172. var _vbp = new Vector3();
  6173. var _vcp = new Vector3();
  6174. function Triangle(a, b, c) {
  6175. this.a = a !== undefined ? a : new Vector3();
  6176. this.b = b !== undefined ? b : new Vector3();
  6177. this.c = c !== undefined ? c : new Vector3();
  6178. }
  6179. Object.assign(Triangle, {
  6180. getNormal: function (a, b, c, target) {
  6181. if (target === undefined) {
  6182. console.warn('THREE.Triangle: .getNormal() target is now required');
  6183. target = new Vector3();
  6184. }
  6185. target.subVectors(c, b);
  6186. _v0$1.subVectors(a, b);
  6187. target.cross(_v0$1);
  6188. var targetLengthSq = target.lengthSq();
  6189. if (targetLengthSq > 0) {
  6190. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  6191. }
  6192. return target.set(0, 0, 0);
  6193. },
  6194. // static/instance method to calculate barycentric coordinates
  6195. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6196. getBarycoord: function (point, a, b, c, target) {
  6197. _v0$1.subVectors(c, a);
  6198. _v1$3.subVectors(b, a);
  6199. _v2$1.subVectors(point, a);
  6200. var dot00 = _v0$1.dot(_v0$1);
  6201. var dot01 = _v0$1.dot(_v1$3);
  6202. var dot02 = _v0$1.dot(_v2$1);
  6203. var dot11 = _v1$3.dot(_v1$3);
  6204. var dot12 = _v1$3.dot(_v2$1);
  6205. var denom = dot00 * dot11 - dot01 * dot01;
  6206. if (target === undefined) {
  6207. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  6208. target = new Vector3();
  6209. } // collinear or singular triangle
  6210. if (denom === 0) {
  6211. // arbitrary location outside of triangle?
  6212. // not sure if this is the best idea, maybe should be returning undefined
  6213. return target.set(-2, -1, -1);
  6214. }
  6215. var invDenom = 1 / denom;
  6216. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  6217. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  6218. return target.set(1 - u - v, v, u);
  6219. },
  6220. containsPoint: function (point, a, b, c) {
  6221. Triangle.getBarycoord(point, a, b, c, _v3);
  6222. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  6223. },
  6224. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  6225. this.getBarycoord(point, p1, p2, p3, _v3);
  6226. target.set(0, 0);
  6227. target.addScaledVector(uv1, _v3.x);
  6228. target.addScaledVector(uv2, _v3.y);
  6229. target.addScaledVector(uv3, _v3.z);
  6230. return target;
  6231. },
  6232. isFrontFacing: function (a, b, c, direction) {
  6233. _v0$1.subVectors(c, b);
  6234. _v1$3.subVectors(a, b); // strictly front facing
  6235. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  6236. }
  6237. });
  6238. Object.assign(Triangle.prototype, {
  6239. set: function (a, b, c) {
  6240. this.a.copy(a);
  6241. this.b.copy(b);
  6242. this.c.copy(c);
  6243. return this;
  6244. },
  6245. setFromPointsAndIndices: function (points, i0, i1, i2) {
  6246. this.a.copy(points[i0]);
  6247. this.b.copy(points[i1]);
  6248. this.c.copy(points[i2]);
  6249. return this;
  6250. },
  6251. clone: function () {
  6252. return new this.constructor().copy(this);
  6253. },
  6254. copy: function (triangle) {
  6255. this.a.copy(triangle.a);
  6256. this.b.copy(triangle.b);
  6257. this.c.copy(triangle.c);
  6258. return this;
  6259. },
  6260. getArea: function () {
  6261. _v0$1.subVectors(this.c, this.b);
  6262. _v1$3.subVectors(this.a, this.b);
  6263. return _v0$1.cross(_v1$3).length() * 0.5;
  6264. },
  6265. getMidpoint: function (target) {
  6266. if (target === undefined) {
  6267. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  6268. target = new Vector3();
  6269. }
  6270. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  6271. },
  6272. getNormal: function (target) {
  6273. return Triangle.getNormal(this.a, this.b, this.c, target);
  6274. },
  6275. getPlane: function (target) {
  6276. if (target === undefined) {
  6277. console.warn('THREE.Triangle: .getPlane() target is now required');
  6278. target = new Vector3();
  6279. }
  6280. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  6281. },
  6282. getBarycoord: function (point, target) {
  6283. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  6284. },
  6285. getUV: function (point, uv1, uv2, uv3, target) {
  6286. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  6287. },
  6288. containsPoint: function (point) {
  6289. return Triangle.containsPoint(point, this.a, this.b, this.c);
  6290. },
  6291. isFrontFacing: function (direction) {
  6292. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  6293. },
  6294. intersectsBox: function (box) {
  6295. return box.intersectsTriangle(this);
  6296. },
  6297. closestPointToPoint: function (p, target) {
  6298. if (target === undefined) {
  6299. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  6300. target = new Vector3();
  6301. }
  6302. var a = this.a,
  6303. b = this.b,
  6304. c = this.c;
  6305. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  6306. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  6307. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  6308. // basically, we're distinguishing which of the voronoi regions of the triangle
  6309. // the point lies in with the minimum amount of redundant computation.
  6310. _vab.subVectors(b, a);
  6311. _vac.subVectors(c, a);
  6312. _vap.subVectors(p, a);
  6313. var d1 = _vab.dot(_vap);
  6314. var d2 = _vac.dot(_vap);
  6315. if (d1 <= 0 && d2 <= 0) {
  6316. // vertex region of A; barycentric coords (1, 0, 0)
  6317. return target.copy(a);
  6318. }
  6319. _vbp.subVectors(p, b);
  6320. var d3 = _vab.dot(_vbp);
  6321. var d4 = _vac.dot(_vbp);
  6322. if (d3 >= 0 && d4 <= d3) {
  6323. // vertex region of B; barycentric coords (0, 1, 0)
  6324. return target.copy(b);
  6325. }
  6326. var vc = d1 * d4 - d3 * d2;
  6327. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  6328. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  6329. return target.copy(a).addScaledVector(_vab, v);
  6330. }
  6331. _vcp.subVectors(p, c);
  6332. var d5 = _vab.dot(_vcp);
  6333. var d6 = _vac.dot(_vcp);
  6334. if (d6 >= 0 && d5 <= d6) {
  6335. // vertex region of C; barycentric coords (0, 0, 1)
  6336. return target.copy(c);
  6337. }
  6338. var vb = d5 * d2 - d1 * d6;
  6339. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  6340. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  6341. return target.copy(a).addScaledVector(_vac, w);
  6342. }
  6343. var va = d3 * d6 - d5 * d4;
  6344. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  6345. _vbc.subVectors(c, b);
  6346. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  6347. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  6348. } // face region
  6349. var denom = 1 / (va + vb + vc); // u = va * denom
  6350. v = vb * denom;
  6351. w = vc * denom;
  6352. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  6353. },
  6354. equals: function (triangle) {
  6355. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  6356. }
  6357. });
  6358. /**
  6359. * @author mrdoob / http://mrdoob.com/
  6360. */
  6361. var _colorKeywords = {
  6362. 'aliceblue': 0xF0F8FF,
  6363. 'antiquewhite': 0xFAEBD7,
  6364. 'aqua': 0x00FFFF,
  6365. 'aquamarine': 0x7FFFD4,
  6366. 'azure': 0xF0FFFF,
  6367. 'beige': 0xF5F5DC,
  6368. 'bisque': 0xFFE4C4,
  6369. 'black': 0x000000,
  6370. 'blanchedalmond': 0xFFEBCD,
  6371. 'blue': 0x0000FF,
  6372. 'blueviolet': 0x8A2BE2,
  6373. 'brown': 0xA52A2A,
  6374. 'burlywood': 0xDEB887,
  6375. 'cadetblue': 0x5F9EA0,
  6376. 'chartreuse': 0x7FFF00,
  6377. 'chocolate': 0xD2691E,
  6378. 'coral': 0xFF7F50,
  6379. 'cornflowerblue': 0x6495ED,
  6380. 'cornsilk': 0xFFF8DC,
  6381. 'crimson': 0xDC143C,
  6382. 'cyan': 0x00FFFF,
  6383. 'darkblue': 0x00008B,
  6384. 'darkcyan': 0x008B8B,
  6385. 'darkgoldenrod': 0xB8860B,
  6386. 'darkgray': 0xA9A9A9,
  6387. 'darkgreen': 0x006400,
  6388. 'darkgrey': 0xA9A9A9,
  6389. 'darkkhaki': 0xBDB76B,
  6390. 'darkmagenta': 0x8B008B,
  6391. 'darkolivegreen': 0x556B2F,
  6392. 'darkorange': 0xFF8C00,
  6393. 'darkorchid': 0x9932CC,
  6394. 'darkred': 0x8B0000,
  6395. 'darksalmon': 0xE9967A,
  6396. 'darkseagreen': 0x8FBC8F,
  6397. 'darkslateblue': 0x483D8B,
  6398. 'darkslategray': 0x2F4F4F,
  6399. 'darkslategrey': 0x2F4F4F,
  6400. 'darkturquoise': 0x00CED1,
  6401. 'darkviolet': 0x9400D3,
  6402. 'deeppink': 0xFF1493,
  6403. 'deepskyblue': 0x00BFFF,
  6404. 'dimgray': 0x696969,
  6405. 'dimgrey': 0x696969,
  6406. 'dodgerblue': 0x1E90FF,
  6407. 'firebrick': 0xB22222,
  6408. 'floralwhite': 0xFFFAF0,
  6409. 'forestgreen': 0x228B22,
  6410. 'fuchsia': 0xFF00FF,
  6411. 'gainsboro': 0xDCDCDC,
  6412. 'ghostwhite': 0xF8F8FF,
  6413. 'gold': 0xFFD700,
  6414. 'goldenrod': 0xDAA520,
  6415. 'gray': 0x808080,
  6416. 'green': 0x008000,
  6417. 'greenyellow': 0xADFF2F,
  6418. 'grey': 0x808080,
  6419. 'honeydew': 0xF0FFF0,
  6420. 'hotpink': 0xFF69B4,
  6421. 'indianred': 0xCD5C5C,
  6422. 'indigo': 0x4B0082,
  6423. 'ivory': 0xFFFFF0,
  6424. 'khaki': 0xF0E68C,
  6425. 'lavender': 0xE6E6FA,
  6426. 'lavenderblush': 0xFFF0F5,
  6427. 'lawngreen': 0x7CFC00,
  6428. 'lemonchiffon': 0xFFFACD,
  6429. 'lightblue': 0xADD8E6,
  6430. 'lightcoral': 0xF08080,
  6431. 'lightcyan': 0xE0FFFF,
  6432. 'lightgoldenrodyellow': 0xFAFAD2,
  6433. 'lightgray': 0xD3D3D3,
  6434. 'lightgreen': 0x90EE90,
  6435. 'lightgrey': 0xD3D3D3,
  6436. 'lightpink': 0xFFB6C1,
  6437. 'lightsalmon': 0xFFA07A,
  6438. 'lightseagreen': 0x20B2AA,
  6439. 'lightskyblue': 0x87CEFA,
  6440. 'lightslategray': 0x778899,
  6441. 'lightslategrey': 0x778899,
  6442. 'lightsteelblue': 0xB0C4DE,
  6443. 'lightyellow': 0xFFFFE0,
  6444. 'lime': 0x00FF00,
  6445. 'limegreen': 0x32CD32,
  6446. 'linen': 0xFAF0E6,
  6447. 'magenta': 0xFF00FF,
  6448. 'maroon': 0x800000,
  6449. 'mediumaquamarine': 0x66CDAA,
  6450. 'mediumblue': 0x0000CD,
  6451. 'mediumorchid': 0xBA55D3,
  6452. 'mediumpurple': 0x9370DB,
  6453. 'mediumseagreen': 0x3CB371,
  6454. 'mediumslateblue': 0x7B68EE,
  6455. 'mediumspringgreen': 0x00FA9A,
  6456. 'mediumturquoise': 0x48D1CC,
  6457. 'mediumvioletred': 0xC71585,
  6458. 'midnightblue': 0x191970,
  6459. 'mintcream': 0xF5FFFA,
  6460. 'mistyrose': 0xFFE4E1,
  6461. 'moccasin': 0xFFE4B5,
  6462. 'navajowhite': 0xFFDEAD,
  6463. 'navy': 0x000080,
  6464. 'oldlace': 0xFDF5E6,
  6465. 'olive': 0x808000,
  6466. 'olivedrab': 0x6B8E23,
  6467. 'orange': 0xFFA500,
  6468. 'orangered': 0xFF4500,
  6469. 'orchid': 0xDA70D6,
  6470. 'palegoldenrod': 0xEEE8AA,
  6471. 'palegreen': 0x98FB98,
  6472. 'paleturquoise': 0xAFEEEE,
  6473. 'palevioletred': 0xDB7093,
  6474. 'papayawhip': 0xFFEFD5,
  6475. 'peachpuff': 0xFFDAB9,
  6476. 'peru': 0xCD853F,
  6477. 'pink': 0xFFC0CB,
  6478. 'plum': 0xDDA0DD,
  6479. 'powderblue': 0xB0E0E6,
  6480. 'purple': 0x800080,
  6481. 'rebeccapurple': 0x663399,
  6482. 'red': 0xFF0000,
  6483. 'rosybrown': 0xBC8F8F,
  6484. 'royalblue': 0x4169E1,
  6485. 'saddlebrown': 0x8B4513,
  6486. 'salmon': 0xFA8072,
  6487. 'sandybrown': 0xF4A460,
  6488. 'seagreen': 0x2E8B57,
  6489. 'seashell': 0xFFF5EE,
  6490. 'sienna': 0xA0522D,
  6491. 'silver': 0xC0C0C0,
  6492. 'skyblue': 0x87CEEB,
  6493. 'slateblue': 0x6A5ACD,
  6494. 'slategray': 0x708090,
  6495. 'slategrey': 0x708090,
  6496. 'snow': 0xFFFAFA,
  6497. 'springgreen': 0x00FF7F,
  6498. 'steelblue': 0x4682B4,
  6499. 'tan': 0xD2B48C,
  6500. 'teal': 0x008080,
  6501. 'thistle': 0xD8BFD8,
  6502. 'tomato': 0xFF6347,
  6503. 'turquoise': 0x40E0D0,
  6504. 'violet': 0xEE82EE,
  6505. 'wheat': 0xF5DEB3,
  6506. 'white': 0xFFFFFF,
  6507. 'whitesmoke': 0xF5F5F5,
  6508. 'yellow': 0xFFFF00,
  6509. 'yellowgreen': 0x9ACD32
  6510. };
  6511. var _hslA = {
  6512. h: 0,
  6513. s: 0,
  6514. l: 0
  6515. };
  6516. var _hslB = {
  6517. h: 0,
  6518. s: 0,
  6519. l: 0
  6520. };
  6521. function Color(r, g, b) {
  6522. if (g === undefined && b === undefined) {
  6523. // r is THREE.Color, hex or string
  6524. return this.set(r);
  6525. }
  6526. return this.setRGB(r, g, b);
  6527. }
  6528. function hue2rgb(p, q, t) {
  6529. if (t < 0) t += 1;
  6530. if (t > 1) t -= 1;
  6531. if (t < 1 / 6) return p + (q - p) * 6 * t;
  6532. if (t < 1 / 2) return q;
  6533. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  6534. return p;
  6535. }
  6536. function SRGBToLinear(c) {
  6537. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  6538. }
  6539. function LinearToSRGB(c) {
  6540. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  6541. }
  6542. Object.assign(Color.prototype, {
  6543. isColor: true,
  6544. r: 1,
  6545. g: 1,
  6546. b: 1,
  6547. set: function (value) {
  6548. if (value && value.isColor) {
  6549. this.copy(value);
  6550. } else if (typeof value === 'number') {
  6551. this.setHex(value);
  6552. } else if (typeof value === 'string') {
  6553. this.setStyle(value);
  6554. }
  6555. return this;
  6556. },
  6557. setScalar: function (scalar) {
  6558. this.r = scalar;
  6559. this.g = scalar;
  6560. this.b = scalar;
  6561. return this;
  6562. },
  6563. setHex: function (hex) {
  6564. hex = Math.floor(hex);
  6565. this.r = (hex >> 16 & 255) / 255;
  6566. this.g = (hex >> 8 & 255) / 255;
  6567. this.b = (hex & 255) / 255;
  6568. return this;
  6569. },
  6570. setRGB: function (r, g, b) {
  6571. this.r = r;
  6572. this.g = g;
  6573. this.b = b;
  6574. return this;
  6575. },
  6576. setHSL: function (h, s, l) {
  6577. // h,s,l ranges are in 0.0 - 1.0
  6578. h = _Math.euclideanModulo(h, 1);
  6579. s = _Math.clamp(s, 0, 1);
  6580. l = _Math.clamp(l, 0, 1);
  6581. if (s === 0) {
  6582. this.r = this.g = this.b = l;
  6583. } else {
  6584. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  6585. var q = 2 * l - p;
  6586. this.r = hue2rgb(q, p, h + 1 / 3);
  6587. this.g = hue2rgb(q, p, h);
  6588. this.b = hue2rgb(q, p, h - 1 / 3);
  6589. }
  6590. return this;
  6591. },
  6592. setStyle: function (style) {
  6593. function handleAlpha(string) {
  6594. if (string === undefined) return;
  6595. if (parseFloat(string) < 1) {
  6596. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  6597. }
  6598. }
  6599. var m;
  6600. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  6601. // rgb / hsl
  6602. var color;
  6603. var name = m[1];
  6604. var components = m[2];
  6605. switch (name) {
  6606. case 'rgb':
  6607. case 'rgba':
  6608. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6609. // rgb(255,0,0) rgba(255,0,0,0.5)
  6610. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  6611. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  6612. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  6613. handleAlpha(color[5]);
  6614. return this;
  6615. }
  6616. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6617. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  6618. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  6619. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  6620. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  6621. handleAlpha(color[5]);
  6622. return this;
  6623. }
  6624. break;
  6625. case 'hsl':
  6626. case 'hsla':
  6627. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  6628. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  6629. var h = parseFloat(color[1]) / 360;
  6630. var s = parseInt(color[2], 10) / 100;
  6631. var l = parseInt(color[3], 10) / 100;
  6632. handleAlpha(color[5]);
  6633. return this.setHSL(h, s, l);
  6634. }
  6635. break;
  6636. }
  6637. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  6638. // hex color
  6639. var hex = m[1];
  6640. var size = hex.length;
  6641. if (size === 3) {
  6642. // #ff0
  6643. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  6644. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  6645. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  6646. return this;
  6647. } else if (size === 6) {
  6648. // #ff0000
  6649. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  6650. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  6651. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  6652. return this;
  6653. }
  6654. }
  6655. if (style && style.length > 0) {
  6656. // color keywords
  6657. var hex = _colorKeywords[style];
  6658. if (hex !== undefined) {
  6659. // red
  6660. this.setHex(hex);
  6661. } else {
  6662. // unknown color
  6663. console.warn('THREE.Color: Unknown color ' + style);
  6664. }
  6665. }
  6666. return this;
  6667. },
  6668. clone: function () {
  6669. return new this.constructor(this.r, this.g, this.b);
  6670. },
  6671. copy: function (color) {
  6672. this.r = color.r;
  6673. this.g = color.g;
  6674. this.b = color.b;
  6675. return this;
  6676. },
  6677. copyGammaToLinear: function (color, gammaFactor) {
  6678. if (gammaFactor === undefined) gammaFactor = 2.0;
  6679. this.r = Math.pow(color.r, gammaFactor);
  6680. this.g = Math.pow(color.g, gammaFactor);
  6681. this.b = Math.pow(color.b, gammaFactor);
  6682. return this;
  6683. },
  6684. copyLinearToGamma: function (color, gammaFactor) {
  6685. if (gammaFactor === undefined) gammaFactor = 2.0;
  6686. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  6687. this.r = Math.pow(color.r, safeInverse);
  6688. this.g = Math.pow(color.g, safeInverse);
  6689. this.b = Math.pow(color.b, safeInverse);
  6690. return this;
  6691. },
  6692. convertGammaToLinear: function (gammaFactor) {
  6693. this.copyGammaToLinear(this, gammaFactor);
  6694. return this;
  6695. },
  6696. convertLinearToGamma: function (gammaFactor) {
  6697. this.copyLinearToGamma(this, gammaFactor);
  6698. return this;
  6699. },
  6700. copySRGBToLinear: function (color) {
  6701. this.r = SRGBToLinear(color.r);
  6702. this.g = SRGBToLinear(color.g);
  6703. this.b = SRGBToLinear(color.b);
  6704. return this;
  6705. },
  6706. copyLinearToSRGB: function (color) {
  6707. this.r = LinearToSRGB(color.r);
  6708. this.g = LinearToSRGB(color.g);
  6709. this.b = LinearToSRGB(color.b);
  6710. return this;
  6711. },
  6712. convertSRGBToLinear: function () {
  6713. this.copySRGBToLinear(this);
  6714. return this;
  6715. },
  6716. convertLinearToSRGB: function () {
  6717. this.copyLinearToSRGB(this);
  6718. return this;
  6719. },
  6720. getHex: function () {
  6721. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  6722. },
  6723. getHexString: function () {
  6724. return ('000000' + this.getHex().toString(16)).slice(-6);
  6725. },
  6726. getHSL: function (target) {
  6727. // h,s,l ranges are in 0.0 - 1.0
  6728. if (target === undefined) {
  6729. console.warn('THREE.Color: .getHSL() target is now required');
  6730. target = {
  6731. h: 0,
  6732. s: 0,
  6733. l: 0
  6734. };
  6735. }
  6736. var r = this.r,
  6737. g = this.g,
  6738. b = this.b;
  6739. var max = Math.max(r, g, b);
  6740. var min = Math.min(r, g, b);
  6741. var hue, saturation;
  6742. var lightness = (min + max) / 2.0;
  6743. if (min === max) {
  6744. hue = 0;
  6745. saturation = 0;
  6746. } else {
  6747. var delta = max - min;
  6748. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  6749. switch (max) {
  6750. case r:
  6751. hue = (g - b) / delta + (g < b ? 6 : 0);
  6752. break;
  6753. case g:
  6754. hue = (b - r) / delta + 2;
  6755. break;
  6756. case b:
  6757. hue = (r - g) / delta + 4;
  6758. break;
  6759. }
  6760. hue /= 6;
  6761. }
  6762. target.h = hue;
  6763. target.s = saturation;
  6764. target.l = lightness;
  6765. return target;
  6766. },
  6767. getStyle: function () {
  6768. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  6769. },
  6770. offsetHSL: function (h, s, l) {
  6771. this.getHSL(_hslA);
  6772. _hslA.h += h;
  6773. _hslA.s += s;
  6774. _hslA.l += l;
  6775. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  6776. return this;
  6777. },
  6778. add: function (color) {
  6779. this.r += color.r;
  6780. this.g += color.g;
  6781. this.b += color.b;
  6782. return this;
  6783. },
  6784. addColors: function (color1, color2) {
  6785. this.r = color1.r + color2.r;
  6786. this.g = color1.g + color2.g;
  6787. this.b = color1.b + color2.b;
  6788. return this;
  6789. },
  6790. addScalar: function (s) {
  6791. this.r += s;
  6792. this.g += s;
  6793. this.b += s;
  6794. return this;
  6795. },
  6796. sub: function (color) {
  6797. this.r = Math.max(0, this.r - color.r);
  6798. this.g = Math.max(0, this.g - color.g);
  6799. this.b = Math.max(0, this.b - color.b);
  6800. return this;
  6801. },
  6802. multiply: function (color) {
  6803. this.r *= color.r;
  6804. this.g *= color.g;
  6805. this.b *= color.b;
  6806. return this;
  6807. },
  6808. multiplyScalar: function (s) {
  6809. this.r *= s;
  6810. this.g *= s;
  6811. this.b *= s;
  6812. return this;
  6813. },
  6814. lerp: function (color, alpha) {
  6815. this.r += (color.r - this.r) * alpha;
  6816. this.g += (color.g - this.g) * alpha;
  6817. this.b += (color.b - this.b) * alpha;
  6818. return this;
  6819. },
  6820. lerpHSL: function (color, alpha) {
  6821. this.getHSL(_hslA);
  6822. color.getHSL(_hslB);
  6823. var h = _Math.lerp(_hslA.h, _hslB.h, alpha);
  6824. var s = _Math.lerp(_hslA.s, _hslB.s, alpha);
  6825. var l = _Math.lerp(_hslA.l, _hslB.l, alpha);
  6826. this.setHSL(h, s, l);
  6827. return this;
  6828. },
  6829. equals: function (c) {
  6830. return c.r === this.r && c.g === this.g && c.b === this.b;
  6831. },
  6832. fromArray: function (array, offset) {
  6833. if (offset === undefined) offset = 0;
  6834. this.r = array[offset];
  6835. this.g = array[offset + 1];
  6836. this.b = array[offset + 2];
  6837. return this;
  6838. },
  6839. toArray: function (array, offset) {
  6840. if (array === undefined) array = [];
  6841. if (offset === undefined) offset = 0;
  6842. array[offset] = this.r;
  6843. array[offset + 1] = this.g;
  6844. array[offset + 2] = this.b;
  6845. return array;
  6846. },
  6847. toJSON: function () {
  6848. return this.getHex();
  6849. }
  6850. });
  6851. /**
  6852. * @author mrdoob / http://mrdoob.com/
  6853. * @author alteredq / http://alteredqualia.com/
  6854. */
  6855. function Face3(a, b, c, normal, color, materialIndex) {
  6856. this.a = a;
  6857. this.b = b;
  6858. this.c = c;
  6859. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  6860. this.vertexNormals = Array.isArray(normal) ? normal : [];
  6861. this.color = color && color.isColor ? color : new Color();
  6862. this.vertexColors = Array.isArray(color) ? color : [];
  6863. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  6864. }
  6865. Object.assign(Face3.prototype, {
  6866. clone: function () {
  6867. return new this.constructor().copy(this);
  6868. },
  6869. copy: function (source) {
  6870. this.a = source.a;
  6871. this.b = source.b;
  6872. this.c = source.c;
  6873. this.normal.copy(source.normal);
  6874. this.color.copy(source.color);
  6875. this.materialIndex = source.materialIndex;
  6876. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  6877. this.vertexNormals[i] = source.vertexNormals[i].clone();
  6878. }
  6879. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  6880. this.vertexColors[i] = source.vertexColors[i].clone();
  6881. }
  6882. return this;
  6883. }
  6884. });
  6885. /**
  6886. * @author mrdoob / http://mrdoob.com/
  6887. * @author alteredq / http://alteredqualia.com/
  6888. */
  6889. var materialId = 0;
  6890. function Material() {
  6891. Object.defineProperty(this, 'id', {
  6892. value: materialId++
  6893. });
  6894. this.uuid = _Math.generateUUID();
  6895. this.name = '';
  6896. this.type = 'Material';
  6897. this.fog = true;
  6898. this.blending = NormalBlending;
  6899. this.side = FrontSide;
  6900. this.flatShading = false;
  6901. this.vertexTangents = false;
  6902. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  6903. this.opacity = 1;
  6904. this.transparent = false;
  6905. this.blendSrc = SrcAlphaFactor;
  6906. this.blendDst = OneMinusSrcAlphaFactor;
  6907. this.blendEquation = AddEquation;
  6908. this.blendSrcAlpha = null;
  6909. this.blendDstAlpha = null;
  6910. this.blendEquationAlpha = null;
  6911. this.depthFunc = LessEqualDepth;
  6912. this.depthTest = true;
  6913. this.depthWrite = true;
  6914. this.stencilWriteMask = 0xff;
  6915. this.stencilFunc = AlwaysStencilFunc;
  6916. this.stencilRef = 0;
  6917. this.stencilFuncMask = 0xff;
  6918. this.stencilFail = KeepStencilOp;
  6919. this.stencilZFail = KeepStencilOp;
  6920. this.stencilZPass = KeepStencilOp;
  6921. this.stencilWrite = false;
  6922. this.clippingPlanes = null;
  6923. this.clipIntersection = false;
  6924. this.clipShadows = false;
  6925. this.shadowSide = null;
  6926. this.colorWrite = true;
  6927. this.precision = null; // override the renderer's default precision for this material
  6928. this.polygonOffset = false;
  6929. this.polygonOffsetFactor = 0;
  6930. this.polygonOffsetUnits = 0;
  6931. this.dithering = false;
  6932. this.alphaTest = 0;
  6933. this.premultipliedAlpha = false;
  6934. this.visible = true;
  6935. this.toneMapped = true;
  6936. this.userData = {};
  6937. this.needsUpdate = true;
  6938. }
  6939. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6940. constructor: Material,
  6941. isMaterial: true,
  6942. onBeforeCompile: function () {},
  6943. setValues: function (values) {
  6944. if (values === undefined) return;
  6945. for (var key in values) {
  6946. var newValue = values[key];
  6947. if (newValue === undefined) {
  6948. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  6949. continue;
  6950. } // for backward compatability if shading is set in the constructor
  6951. if (key === 'shading') {
  6952. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  6953. this.flatShading = newValue === FlatShading ? true : false;
  6954. continue;
  6955. }
  6956. var currentValue = this[key];
  6957. if (currentValue === undefined) {
  6958. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6959. continue;
  6960. }
  6961. if (currentValue && currentValue.isColor) {
  6962. currentValue.set(newValue);
  6963. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6964. currentValue.copy(newValue);
  6965. } else {
  6966. this[key] = newValue;
  6967. }
  6968. }
  6969. },
  6970. toJSON: function (meta) {
  6971. var isRoot = meta === undefined || typeof meta === 'string';
  6972. if (isRoot) {
  6973. meta = {
  6974. textures: {},
  6975. images: {}
  6976. };
  6977. }
  6978. var data = {
  6979. metadata: {
  6980. version: 4.5,
  6981. type: 'Material',
  6982. generator: 'Material.toJSON'
  6983. }
  6984. }; // standard Material serialization
  6985. data.uuid = this.uuid;
  6986. data.type = this.type;
  6987. if (this.name !== '') data.name = this.name;
  6988. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6989. if (this.roughness !== undefined) data.roughness = this.roughness;
  6990. if (this.metalness !== undefined) data.metalness = this.metalness;
  6991. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6992. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6993. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6994. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6995. if (this.shininess !== undefined) data.shininess = this.shininess;
  6996. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  6997. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  6998. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  6999. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  7000. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  7001. }
  7002. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  7003. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  7004. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  7005. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  7006. if (this.aoMap && this.aoMap.isTexture) {
  7007. data.aoMap = this.aoMap.toJSON(meta).uuid;
  7008. data.aoMapIntensity = this.aoMapIntensity;
  7009. }
  7010. if (this.bumpMap && this.bumpMap.isTexture) {
  7011. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  7012. data.bumpScale = this.bumpScale;
  7013. }
  7014. if (this.normalMap && this.normalMap.isTexture) {
  7015. data.normalMap = this.normalMap.toJSON(meta).uuid;
  7016. data.normalMapType = this.normalMapType;
  7017. data.normalScale = this.normalScale.toArray();
  7018. }
  7019. if (this.displacementMap && this.displacementMap.isTexture) {
  7020. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  7021. data.displacementScale = this.displacementScale;
  7022. data.displacementBias = this.displacementBias;
  7023. }
  7024. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  7025. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  7026. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  7027. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  7028. if (this.envMap && this.envMap.isTexture) {
  7029. data.envMap = this.envMap.toJSON(meta).uuid;
  7030. data.reflectivity = this.reflectivity; // Scale behind envMap
  7031. data.refractionRatio = this.refractionRatio;
  7032. if (this.combine !== undefined) data.combine = this.combine;
  7033. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  7034. }
  7035. if (this.gradientMap && this.gradientMap.isTexture) {
  7036. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  7037. }
  7038. if (this.size !== undefined) data.size = this.size;
  7039. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  7040. if (this.blending !== NormalBlending) data.blending = this.blending;
  7041. if (this.flatShading === true) data.flatShading = this.flatShading;
  7042. if (this.side !== FrontSide) data.side = this.side;
  7043. if (this.vertexColors !== NoColors) data.vertexColors = this.vertexColors;
  7044. if (this.opacity < 1) data.opacity = this.opacity;
  7045. if (this.transparent === true) data.transparent = this.transparent;
  7046. data.depthFunc = this.depthFunc;
  7047. data.depthTest = this.depthTest;
  7048. data.depthWrite = this.depthWrite;
  7049. data.stencilWrite = this.stencilWrite;
  7050. data.stencilWriteMask = this.stencilWriteMask;
  7051. data.stencilFunc = this.stencilFunc;
  7052. data.stencilRef = this.stencilRef;
  7053. data.stencilFuncMask = this.stencilFuncMask;
  7054. data.stencilFail = this.stencilFail;
  7055. data.stencilZFail = this.stencilZFail;
  7056. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  7057. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  7058. if (this.polygonOffset === true) data.polygonOffset = true;
  7059. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  7060. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  7061. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  7062. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  7063. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  7064. if (this.scale !== undefined) data.scale = this.scale;
  7065. if (this.dithering === true) data.dithering = true;
  7066. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  7067. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  7068. if (this.wireframe === true) data.wireframe = this.wireframe;
  7069. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  7070. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  7071. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  7072. if (this.morphTargets === true) data.morphTargets = true;
  7073. if (this.morphNormals === true) data.morphNormals = true;
  7074. if (this.skinning === true) data.skinning = true;
  7075. if (this.visible === false) data.visible = false;
  7076. if (this.toneMapped === false) data.toneMapped = false;
  7077. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  7078. function extractFromCache(cache) {
  7079. var values = [];
  7080. for (var key in cache) {
  7081. var data = cache[key];
  7082. delete data.metadata;
  7083. values.push(data);
  7084. }
  7085. return values;
  7086. }
  7087. if (isRoot) {
  7088. var textures = extractFromCache(meta.textures);
  7089. var images = extractFromCache(meta.images);
  7090. if (textures.length > 0) data.textures = textures;
  7091. if (images.length > 0) data.images = images;
  7092. }
  7093. return data;
  7094. },
  7095. clone: function () {
  7096. return new this.constructor().copy(this);
  7097. },
  7098. copy: function (source) {
  7099. this.name = source.name;
  7100. this.fog = source.fog;
  7101. this.blending = source.blending;
  7102. this.side = source.side;
  7103. this.flatShading = source.flatShading;
  7104. this.vertexColors = source.vertexColors;
  7105. this.opacity = source.opacity;
  7106. this.transparent = source.transparent;
  7107. this.blendSrc = source.blendSrc;
  7108. this.blendDst = source.blendDst;
  7109. this.blendEquation = source.blendEquation;
  7110. this.blendSrcAlpha = source.blendSrcAlpha;
  7111. this.blendDstAlpha = source.blendDstAlpha;
  7112. this.blendEquationAlpha = source.blendEquationAlpha;
  7113. this.depthFunc = source.depthFunc;
  7114. this.depthTest = source.depthTest;
  7115. this.depthWrite = source.depthWrite;
  7116. this.stencilWrite = source.stencilWrite;
  7117. this.stencilWriteMask = source.stencilWriteMask;
  7118. this.stencilFunc = source.stencilFunc;
  7119. this.stencilRef = source.stencilRef;
  7120. this.stencilFuncMask = source.stencilFuncMask;
  7121. this.stencilFail = source.stencilFail;
  7122. this.stencilZFail = source.stencilZFail;
  7123. this.stencilZPass = source.stencilZPass;
  7124. this.colorWrite = source.colorWrite;
  7125. this.precision = source.precision;
  7126. this.polygonOffset = source.polygonOffset;
  7127. this.polygonOffsetFactor = source.polygonOffsetFactor;
  7128. this.polygonOffsetUnits = source.polygonOffsetUnits;
  7129. this.dithering = source.dithering;
  7130. this.alphaTest = source.alphaTest;
  7131. this.premultipliedAlpha = source.premultipliedAlpha;
  7132. this.visible = source.visible;
  7133. this.toneMapped = source.toneMapped;
  7134. this.userData = JSON.parse(JSON.stringify(source.userData));
  7135. this.clipShadows = source.clipShadows;
  7136. this.clipIntersection = source.clipIntersection;
  7137. var srcPlanes = source.clippingPlanes,
  7138. dstPlanes = null;
  7139. if (srcPlanes !== null) {
  7140. var n = srcPlanes.length;
  7141. dstPlanes = new Array(n);
  7142. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  7143. }
  7144. this.clippingPlanes = dstPlanes;
  7145. this.shadowSide = source.shadowSide;
  7146. return this;
  7147. },
  7148. dispose: function () {
  7149. this.dispatchEvent({
  7150. type: 'dispose'
  7151. });
  7152. }
  7153. });
  7154. /**
  7155. * @author mrdoob / http://mrdoob.com/
  7156. * @author alteredq / http://alteredqualia.com/
  7157. *
  7158. * parameters = {
  7159. * color: <hex>,
  7160. * opacity: <float>,
  7161. * map: new THREE.Texture( <Image> ),
  7162. *
  7163. * lightMap: new THREE.Texture( <Image> ),
  7164. * lightMapIntensity: <float>
  7165. *
  7166. * aoMap: new THREE.Texture( <Image> ),
  7167. * aoMapIntensity: <float>
  7168. *
  7169. * specularMap: new THREE.Texture( <Image> ),
  7170. *
  7171. * alphaMap: new THREE.Texture( <Image> ),
  7172. *
  7173. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  7174. * combine: THREE.Multiply,
  7175. * reflectivity: <float>,
  7176. * refractionRatio: <float>,
  7177. *
  7178. * depthTest: <bool>,
  7179. * depthWrite: <bool>,
  7180. *
  7181. * wireframe: <boolean>,
  7182. * wireframeLinewidth: <float>,
  7183. *
  7184. * skinning: <bool>,
  7185. * morphTargets: <bool>
  7186. * }
  7187. */
  7188. function MeshBasicMaterial(parameters) {
  7189. Material.call(this);
  7190. this.type = 'MeshBasicMaterial';
  7191. this.color = new Color(0xffffff); // emissive
  7192. this.map = null;
  7193. this.lightMap = null;
  7194. this.lightMapIntensity = 1.0;
  7195. this.aoMap = null;
  7196. this.aoMapIntensity = 1.0;
  7197. this.specularMap = null;
  7198. this.alphaMap = null;
  7199. this.envMap = null;
  7200. this.combine = MultiplyOperation;
  7201. this.reflectivity = 1;
  7202. this.refractionRatio = 0.98;
  7203. this.wireframe = false;
  7204. this.wireframeLinewidth = 1;
  7205. this.wireframeLinecap = 'round';
  7206. this.wireframeLinejoin = 'round';
  7207. this.skinning = false;
  7208. this.morphTargets = false;
  7209. this.setValues(parameters);
  7210. }
  7211. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  7212. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  7213. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  7214. MeshBasicMaterial.prototype.copy = function (source) {
  7215. Material.prototype.copy.call(this, source);
  7216. this.color.copy(source.color);
  7217. this.map = source.map;
  7218. this.lightMap = source.lightMap;
  7219. this.lightMapIntensity = source.lightMapIntensity;
  7220. this.aoMap = source.aoMap;
  7221. this.aoMapIntensity = source.aoMapIntensity;
  7222. this.specularMap = source.specularMap;
  7223. this.alphaMap = source.alphaMap;
  7224. this.envMap = source.envMap;
  7225. this.combine = source.combine;
  7226. this.reflectivity = source.reflectivity;
  7227. this.refractionRatio = source.refractionRatio;
  7228. this.wireframe = source.wireframe;
  7229. this.wireframeLinewidth = source.wireframeLinewidth;
  7230. this.wireframeLinecap = source.wireframeLinecap;
  7231. this.wireframeLinejoin = source.wireframeLinejoin;
  7232. this.skinning = source.skinning;
  7233. this.morphTargets = source.morphTargets;
  7234. return this;
  7235. };
  7236. /**
  7237. * @author mrdoob / http://mrdoob.com/
  7238. */
  7239. function BufferAttribute(array, itemSize, normalized) {
  7240. if (Array.isArray(array)) {
  7241. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  7242. }
  7243. this.name = '';
  7244. this.array = array;
  7245. this.itemSize = itemSize;
  7246. this.count = array !== undefined ? array.length / itemSize : 0;
  7247. this.normalized = normalized === true;
  7248. this.dynamic = false;
  7249. this.updateRange = {
  7250. offset: 0,
  7251. count: -1
  7252. };
  7253. this.version = 0;
  7254. }
  7255. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  7256. set: function (value) {
  7257. if (value === true) this.version++;
  7258. }
  7259. });
  7260. Object.assign(BufferAttribute.prototype, {
  7261. isBufferAttribute: true,
  7262. onUploadCallback: function () {},
  7263. setDynamic: function (value) {
  7264. this.dynamic = value;
  7265. return this;
  7266. },
  7267. copy: function (source) {
  7268. this.name = source.name;
  7269. this.array = new source.array.constructor(source.array);
  7270. this.itemSize = source.itemSize;
  7271. this.count = source.count;
  7272. this.normalized = source.normalized;
  7273. this.dynamic = source.dynamic;
  7274. return this;
  7275. },
  7276. copyAt: function (index1, attribute, index2) {
  7277. index1 *= this.itemSize;
  7278. index2 *= attribute.itemSize;
  7279. for (var i = 0, l = this.itemSize; i < l; i++) {
  7280. this.array[index1 + i] = attribute.array[index2 + i];
  7281. }
  7282. return this;
  7283. },
  7284. copyArray: function (array) {
  7285. this.array.set(array);
  7286. return this;
  7287. },
  7288. copyColorsArray: function (colors) {
  7289. var array = this.array,
  7290. offset = 0;
  7291. for (var i = 0, l = colors.length; i < l; i++) {
  7292. var color = colors[i];
  7293. if (color === undefined) {
  7294. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  7295. color = new Color();
  7296. }
  7297. array[offset++] = color.r;
  7298. array[offset++] = color.g;
  7299. array[offset++] = color.b;
  7300. }
  7301. return this;
  7302. },
  7303. copyVector2sArray: function (vectors) {
  7304. var array = this.array,
  7305. offset = 0;
  7306. for (var i = 0, l = vectors.length; i < l; i++) {
  7307. var vector = vectors[i];
  7308. if (vector === undefined) {
  7309. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  7310. vector = new Vector2();
  7311. }
  7312. array[offset++] = vector.x;
  7313. array[offset++] = vector.y;
  7314. }
  7315. return this;
  7316. },
  7317. copyVector3sArray: function (vectors) {
  7318. var array = this.array,
  7319. offset = 0;
  7320. for (var i = 0, l = vectors.length; i < l; i++) {
  7321. var vector = vectors[i];
  7322. if (vector === undefined) {
  7323. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  7324. vector = new Vector3();
  7325. }
  7326. array[offset++] = vector.x;
  7327. array[offset++] = vector.y;
  7328. array[offset++] = vector.z;
  7329. }
  7330. return this;
  7331. },
  7332. copyVector4sArray: function (vectors) {
  7333. var array = this.array,
  7334. offset = 0;
  7335. for (var i = 0, l = vectors.length; i < l; i++) {
  7336. var vector = vectors[i];
  7337. if (vector === undefined) {
  7338. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  7339. vector = new Vector4();
  7340. }
  7341. array[offset++] = vector.x;
  7342. array[offset++] = vector.y;
  7343. array[offset++] = vector.z;
  7344. array[offset++] = vector.w;
  7345. }
  7346. return this;
  7347. },
  7348. set: function (value, offset) {
  7349. if (offset === undefined) offset = 0;
  7350. this.array.set(value, offset);
  7351. return this;
  7352. },
  7353. getX: function (index) {
  7354. return this.array[index * this.itemSize];
  7355. },
  7356. setX: function (index, x) {
  7357. this.array[index * this.itemSize] = x;
  7358. return this;
  7359. },
  7360. getY: function (index) {
  7361. return this.array[index * this.itemSize + 1];
  7362. },
  7363. setY: function (index, y) {
  7364. this.array[index * this.itemSize + 1] = y;
  7365. return this;
  7366. },
  7367. getZ: function (index) {
  7368. return this.array[index * this.itemSize + 2];
  7369. },
  7370. setZ: function (index, z) {
  7371. this.array[index * this.itemSize + 2] = z;
  7372. return this;
  7373. },
  7374. getW: function (index) {
  7375. return this.array[index * this.itemSize + 3];
  7376. },
  7377. setW: function (index, w) {
  7378. this.array[index * this.itemSize + 3] = w;
  7379. return this;
  7380. },
  7381. setXY: function (index, x, y) {
  7382. index *= this.itemSize;
  7383. this.array[index + 0] = x;
  7384. this.array[index + 1] = y;
  7385. return this;
  7386. },
  7387. setXYZ: function (index, x, y, z) {
  7388. index *= this.itemSize;
  7389. this.array[index + 0] = x;
  7390. this.array[index + 1] = y;
  7391. this.array[index + 2] = z;
  7392. return this;
  7393. },
  7394. setXYZW: function (index, x, y, z, w) {
  7395. index *= this.itemSize;
  7396. this.array[index + 0] = x;
  7397. this.array[index + 1] = y;
  7398. this.array[index + 2] = z;
  7399. this.array[index + 3] = w;
  7400. return this;
  7401. },
  7402. onUpload: function (callback) {
  7403. this.onUploadCallback = callback;
  7404. return this;
  7405. },
  7406. clone: function () {
  7407. return new this.constructor(this.array, this.itemSize).copy(this);
  7408. },
  7409. toJSON: function () {
  7410. return {
  7411. itemSize: this.itemSize,
  7412. type: this.array.constructor.name,
  7413. array: Array.prototype.slice.call(this.array),
  7414. normalized: this.normalized
  7415. };
  7416. }
  7417. }); //
  7418. function Int8BufferAttribute(array, itemSize, normalized) {
  7419. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  7420. }
  7421. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7422. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  7423. function Uint8BufferAttribute(array, itemSize, normalized) {
  7424. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  7425. }
  7426. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7427. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  7428. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  7429. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  7430. }
  7431. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7432. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  7433. function Int16BufferAttribute(array, itemSize, normalized) {
  7434. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  7435. }
  7436. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7437. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  7438. function Uint16BufferAttribute(array, itemSize, normalized) {
  7439. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  7440. }
  7441. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7442. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  7443. function Int32BufferAttribute(array, itemSize, normalized) {
  7444. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  7445. }
  7446. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7447. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  7448. function Uint32BufferAttribute(array, itemSize, normalized) {
  7449. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  7450. }
  7451. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7452. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  7453. function Float32BufferAttribute(array, itemSize, normalized) {
  7454. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  7455. }
  7456. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7457. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  7458. function Float64BufferAttribute(array, itemSize, normalized) {
  7459. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  7460. }
  7461. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  7462. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  7463. /**
  7464. * @author mrdoob / http://mrdoob.com/
  7465. */
  7466. function DirectGeometry() {
  7467. this.vertices = [];
  7468. this.normals = [];
  7469. this.colors = [];
  7470. this.uvs = [];
  7471. this.uvs2 = [];
  7472. this.groups = [];
  7473. this.morphTargets = {};
  7474. this.skinWeights = [];
  7475. this.skinIndices = []; // this.lineDistances = [];
  7476. this.boundingBox = null;
  7477. this.boundingSphere = null; // update flags
  7478. this.verticesNeedUpdate = false;
  7479. this.normalsNeedUpdate = false;
  7480. this.colorsNeedUpdate = false;
  7481. this.uvsNeedUpdate = false;
  7482. this.groupsNeedUpdate = false;
  7483. }
  7484. Object.assign(DirectGeometry.prototype, {
  7485. computeGroups: function (geometry) {
  7486. var group;
  7487. var groups = [];
  7488. var materialIndex = undefined;
  7489. var faces = geometry.faces;
  7490. for (var i = 0; i < faces.length; i++) {
  7491. var face = faces[i]; // materials
  7492. if (face.materialIndex !== materialIndex) {
  7493. materialIndex = face.materialIndex;
  7494. if (group !== undefined) {
  7495. group.count = i * 3 - group.start;
  7496. groups.push(group);
  7497. }
  7498. group = {
  7499. start: i * 3,
  7500. materialIndex: materialIndex
  7501. };
  7502. }
  7503. }
  7504. if (group !== undefined) {
  7505. group.count = i * 3 - group.start;
  7506. groups.push(group);
  7507. }
  7508. this.groups = groups;
  7509. },
  7510. fromGeometry: function (geometry) {
  7511. var faces = geometry.faces;
  7512. var vertices = geometry.vertices;
  7513. var faceVertexUvs = geometry.faceVertexUvs;
  7514. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  7515. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  7516. var morphTargets = geometry.morphTargets;
  7517. var morphTargetsLength = morphTargets.length;
  7518. var morphTargetsPosition;
  7519. if (morphTargetsLength > 0) {
  7520. morphTargetsPosition = [];
  7521. for (var i = 0; i < morphTargetsLength; i++) {
  7522. morphTargetsPosition[i] = {
  7523. name: morphTargets[i].name,
  7524. data: []
  7525. };
  7526. }
  7527. this.morphTargets.position = morphTargetsPosition;
  7528. }
  7529. var morphNormals = geometry.morphNormals;
  7530. var morphNormalsLength = morphNormals.length;
  7531. var morphTargetsNormal;
  7532. if (morphNormalsLength > 0) {
  7533. morphTargetsNormal = [];
  7534. for (var i = 0; i < morphNormalsLength; i++) {
  7535. morphTargetsNormal[i] = {
  7536. name: morphNormals[i].name,
  7537. data: []
  7538. };
  7539. }
  7540. this.morphTargets.normal = morphTargetsNormal;
  7541. } // skins
  7542. var skinIndices = geometry.skinIndices;
  7543. var skinWeights = geometry.skinWeights;
  7544. var hasSkinIndices = skinIndices.length === vertices.length;
  7545. var hasSkinWeights = skinWeights.length === vertices.length; //
  7546. if (vertices.length > 0 && faces.length === 0) {
  7547. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  7548. }
  7549. for (var i = 0; i < faces.length; i++) {
  7550. var face = faces[i];
  7551. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  7552. var vertexNormals = face.vertexNormals;
  7553. if (vertexNormals.length === 3) {
  7554. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  7555. } else {
  7556. var normal = face.normal;
  7557. this.normals.push(normal, normal, normal);
  7558. }
  7559. var vertexColors = face.vertexColors;
  7560. if (vertexColors.length === 3) {
  7561. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  7562. } else {
  7563. var color = face.color;
  7564. this.colors.push(color, color, color);
  7565. }
  7566. if (hasFaceVertexUv === true) {
  7567. var vertexUvs = faceVertexUvs[0][i];
  7568. if (vertexUvs !== undefined) {
  7569. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7570. } else {
  7571. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  7572. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  7573. }
  7574. }
  7575. if (hasFaceVertexUv2 === true) {
  7576. var vertexUvs = faceVertexUvs[1][i];
  7577. if (vertexUvs !== undefined) {
  7578. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  7579. } else {
  7580. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  7581. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  7582. }
  7583. } // morphs
  7584. for (var j = 0; j < morphTargetsLength; j++) {
  7585. var morphTarget = morphTargets[j].vertices;
  7586. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  7587. }
  7588. for (var j = 0; j < morphNormalsLength; j++) {
  7589. var morphNormal = morphNormals[j].vertexNormals[i];
  7590. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  7591. } // skins
  7592. if (hasSkinIndices) {
  7593. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  7594. }
  7595. if (hasSkinWeights) {
  7596. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  7597. }
  7598. }
  7599. this.computeGroups(geometry);
  7600. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7601. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7602. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7603. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7604. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7605. if (geometry.boundingSphere !== null) {
  7606. this.boundingSphere = geometry.boundingSphere.clone();
  7607. }
  7608. if (geometry.boundingBox !== null) {
  7609. this.boundingBox = geometry.boundingBox.clone();
  7610. }
  7611. return this;
  7612. }
  7613. });
  7614. /**
  7615. * @author mrdoob / http://mrdoob.com/
  7616. */
  7617. function arrayMax(array) {
  7618. if (array.length === 0) return -Infinity;
  7619. var max = array[0];
  7620. for (var i = 1, l = array.length; i < l; ++i) {
  7621. if (array[i] > max) max = array[i];
  7622. }
  7623. return max;
  7624. }
  7625. /**
  7626. * @author alteredq / http://alteredqualia.com/
  7627. * @author mrdoob / http://mrdoob.com/
  7628. */
  7629. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  7630. var _m1$2 = new Matrix4();
  7631. var _obj = new Object3D();
  7632. var _offset = new Vector3();
  7633. var _box$1 = new Box3();
  7634. var _boxMorphTargets = new Box3();
  7635. var _vector$4 = new Vector3();
  7636. function BufferGeometry() {
  7637. Object.defineProperty(this, 'id', {
  7638. value: _bufferGeometryId += 2
  7639. });
  7640. this.uuid = _Math.generateUUID();
  7641. this.name = '';
  7642. this.type = 'BufferGeometry';
  7643. this.index = null;
  7644. this.attributes = {};
  7645. this.morphAttributes = {};
  7646. this.groups = [];
  7647. this.boundingBox = null;
  7648. this.boundingSphere = null;
  7649. this.drawRange = {
  7650. start: 0,
  7651. count: Infinity
  7652. };
  7653. this.userData = {};
  7654. }
  7655. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7656. constructor: BufferGeometry,
  7657. isBufferGeometry: true,
  7658. getIndex: function () {
  7659. return this.index;
  7660. },
  7661. setIndex: function (index) {
  7662. if (Array.isArray(index)) {
  7663. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  7664. } else {
  7665. this.index = index;
  7666. }
  7667. },
  7668. addAttribute: function (name, attribute) {
  7669. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  7670. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  7671. return this.addAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  7672. }
  7673. if (name === 'index') {
  7674. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  7675. this.setIndex(attribute);
  7676. return this;
  7677. }
  7678. return this.setAttribute(name, attribute);
  7679. },
  7680. getAttribute: function (name) {
  7681. return this.attributes[name];
  7682. },
  7683. setAttribute: function (name, attribute) {
  7684. this.attributes[name] = attribute;
  7685. return this;
  7686. },
  7687. removeAttribute: function (name) {
  7688. delete this.attributes[name];
  7689. return this;
  7690. },
  7691. addGroup: function (start, count, materialIndex) {
  7692. this.groups.push({
  7693. start: start,
  7694. count: count,
  7695. materialIndex: materialIndex !== undefined ? materialIndex : 0
  7696. });
  7697. },
  7698. clearGroups: function () {
  7699. this.groups = [];
  7700. },
  7701. setDrawRange: function (start, count) {
  7702. this.drawRange.start = start;
  7703. this.drawRange.count = count;
  7704. },
  7705. applyMatrix: function (matrix) {
  7706. var position = this.attributes.position;
  7707. if (position !== undefined) {
  7708. matrix.applyToBufferAttribute(position);
  7709. position.needsUpdate = true;
  7710. }
  7711. var normal = this.attributes.normal;
  7712. if (normal !== undefined) {
  7713. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7714. normalMatrix.applyToBufferAttribute(normal);
  7715. normal.needsUpdate = true;
  7716. }
  7717. var tangent = this.attributes.tangent;
  7718. if (tangent !== undefined) {
  7719. var normalMatrix = new Matrix3().getNormalMatrix(matrix); // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  7720. normalMatrix.applyToBufferAttribute(tangent);
  7721. tangent.needsUpdate = true;
  7722. }
  7723. if (this.boundingBox !== null) {
  7724. this.computeBoundingBox();
  7725. }
  7726. if (this.boundingSphere !== null) {
  7727. this.computeBoundingSphere();
  7728. }
  7729. return this;
  7730. },
  7731. rotateX: function (angle) {
  7732. // rotate geometry around world x-axis
  7733. _m1$2.makeRotationX(angle);
  7734. this.applyMatrix(_m1$2);
  7735. return this;
  7736. },
  7737. rotateY: function (angle) {
  7738. // rotate geometry around world y-axis
  7739. _m1$2.makeRotationY(angle);
  7740. this.applyMatrix(_m1$2);
  7741. return this;
  7742. },
  7743. rotateZ: function (angle) {
  7744. // rotate geometry around world z-axis
  7745. _m1$2.makeRotationZ(angle);
  7746. this.applyMatrix(_m1$2);
  7747. return this;
  7748. },
  7749. translate: function (x, y, z) {
  7750. // translate geometry
  7751. _m1$2.makeTranslation(x, y, z);
  7752. this.applyMatrix(_m1$2);
  7753. return this;
  7754. },
  7755. scale: function (x, y, z) {
  7756. // scale geometry
  7757. _m1$2.makeScale(x, y, z);
  7758. this.applyMatrix(_m1$2);
  7759. return this;
  7760. },
  7761. lookAt: function (vector) {
  7762. _obj.lookAt(vector);
  7763. _obj.updateMatrix();
  7764. this.applyMatrix(_obj.matrix);
  7765. return this;
  7766. },
  7767. center: function () {
  7768. this.computeBoundingBox();
  7769. this.boundingBox.getCenter(_offset).negate();
  7770. this.translate(_offset.x, _offset.y, _offset.z);
  7771. return this;
  7772. },
  7773. setFromObject: function (object) {
  7774. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  7775. var geometry = object.geometry;
  7776. if (object.isPoints || object.isLine) {
  7777. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  7778. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  7779. this.addAttribute('position', positions.copyVector3sArray(geometry.vertices));
  7780. this.addAttribute('color', colors.copyColorsArray(geometry.colors));
  7781. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  7782. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  7783. this.addAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  7784. }
  7785. if (geometry.boundingSphere !== null) {
  7786. this.boundingSphere = geometry.boundingSphere.clone();
  7787. }
  7788. if (geometry.boundingBox !== null) {
  7789. this.boundingBox = geometry.boundingBox.clone();
  7790. }
  7791. } else if (object.isMesh) {
  7792. if (geometry && geometry.isGeometry) {
  7793. this.fromGeometry(geometry);
  7794. }
  7795. }
  7796. return this;
  7797. },
  7798. setFromPoints: function (points) {
  7799. var position = [];
  7800. for (var i = 0, l = points.length; i < l; i++) {
  7801. var point = points[i];
  7802. position.push(point.x, point.y, point.z || 0);
  7803. }
  7804. this.addAttribute('position', new Float32BufferAttribute(position, 3));
  7805. return this;
  7806. },
  7807. updateFromObject: function (object) {
  7808. var geometry = object.geometry;
  7809. if (object.isMesh) {
  7810. var direct = geometry.__directGeometry;
  7811. if (geometry.elementsNeedUpdate === true) {
  7812. direct = undefined;
  7813. geometry.elementsNeedUpdate = false;
  7814. }
  7815. if (direct === undefined) {
  7816. return this.fromGeometry(geometry);
  7817. }
  7818. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  7819. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  7820. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  7821. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  7822. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  7823. geometry.verticesNeedUpdate = false;
  7824. geometry.normalsNeedUpdate = false;
  7825. geometry.colorsNeedUpdate = false;
  7826. geometry.uvsNeedUpdate = false;
  7827. geometry.groupsNeedUpdate = false;
  7828. geometry = direct;
  7829. }
  7830. var attribute;
  7831. if (geometry.verticesNeedUpdate === true) {
  7832. attribute = this.attributes.position;
  7833. if (attribute !== undefined) {
  7834. attribute.copyVector3sArray(geometry.vertices);
  7835. attribute.needsUpdate = true;
  7836. }
  7837. geometry.verticesNeedUpdate = false;
  7838. }
  7839. if (geometry.normalsNeedUpdate === true) {
  7840. attribute = this.attributes.normal;
  7841. if (attribute !== undefined) {
  7842. attribute.copyVector3sArray(geometry.normals);
  7843. attribute.needsUpdate = true;
  7844. }
  7845. geometry.normalsNeedUpdate = false;
  7846. }
  7847. if (geometry.colorsNeedUpdate === true) {
  7848. attribute = this.attributes.color;
  7849. if (attribute !== undefined) {
  7850. attribute.copyColorsArray(geometry.colors);
  7851. attribute.needsUpdate = true;
  7852. }
  7853. geometry.colorsNeedUpdate = false;
  7854. }
  7855. if (geometry.uvsNeedUpdate) {
  7856. attribute = this.attributes.uv;
  7857. if (attribute !== undefined) {
  7858. attribute.copyVector2sArray(geometry.uvs);
  7859. attribute.needsUpdate = true;
  7860. }
  7861. geometry.uvsNeedUpdate = false;
  7862. }
  7863. if (geometry.lineDistancesNeedUpdate) {
  7864. attribute = this.attributes.lineDistance;
  7865. if (attribute !== undefined) {
  7866. attribute.copyArray(geometry.lineDistances);
  7867. attribute.needsUpdate = true;
  7868. }
  7869. geometry.lineDistancesNeedUpdate = false;
  7870. }
  7871. if (geometry.groupsNeedUpdate) {
  7872. geometry.computeGroups(object.geometry);
  7873. this.groups = geometry.groups;
  7874. geometry.groupsNeedUpdate = false;
  7875. }
  7876. return this;
  7877. },
  7878. fromGeometry: function (geometry) {
  7879. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  7880. return this.fromDirectGeometry(geometry.__directGeometry);
  7881. },
  7882. fromDirectGeometry: function (geometry) {
  7883. var positions = new Float32Array(geometry.vertices.length * 3);
  7884. this.addAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  7885. if (geometry.normals.length > 0) {
  7886. var normals = new Float32Array(geometry.normals.length * 3);
  7887. this.addAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  7888. }
  7889. if (geometry.colors.length > 0) {
  7890. var colors = new Float32Array(geometry.colors.length * 3);
  7891. this.addAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  7892. }
  7893. if (geometry.uvs.length > 0) {
  7894. var uvs = new Float32Array(geometry.uvs.length * 2);
  7895. this.addAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  7896. }
  7897. if (geometry.uvs2.length > 0) {
  7898. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  7899. this.addAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7900. } // groups
  7901. this.groups = geometry.groups; // morphs
  7902. for (var name in geometry.morphTargets) {
  7903. var array = [];
  7904. var morphTargets = geometry.morphTargets[name];
  7905. for (var i = 0, l = morphTargets.length; i < l; i++) {
  7906. var morphTarget = morphTargets[i];
  7907. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7908. attribute.name = morphTarget.name;
  7909. array.push(attribute.copyVector3sArray(morphTarget.data));
  7910. }
  7911. this.morphAttributes[name] = array;
  7912. } // skinning
  7913. if (geometry.skinIndices.length > 0) {
  7914. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7915. this.addAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7916. }
  7917. if (geometry.skinWeights.length > 0) {
  7918. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7919. this.addAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7920. } //
  7921. if (geometry.boundingSphere !== null) {
  7922. this.boundingSphere = geometry.boundingSphere.clone();
  7923. }
  7924. if (geometry.boundingBox !== null) {
  7925. this.boundingBox = geometry.boundingBox.clone();
  7926. }
  7927. return this;
  7928. },
  7929. computeBoundingBox: function () {
  7930. if (this.boundingBox === null) {
  7931. this.boundingBox = new Box3();
  7932. }
  7933. var position = this.attributes.position;
  7934. var morphAttributesPosition = this.morphAttributes.position;
  7935. if (position !== undefined) {
  7936. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7937. if (morphAttributesPosition) {
  7938. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7939. var morphAttribute = morphAttributesPosition[i];
  7940. _box$1.setFromBufferAttribute(morphAttribute);
  7941. this.boundingBox.expandByPoint(_box$1.min);
  7942. this.boundingBox.expandByPoint(_box$1.max);
  7943. }
  7944. }
  7945. } else {
  7946. this.boundingBox.makeEmpty();
  7947. }
  7948. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7949. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7950. }
  7951. },
  7952. computeBoundingSphere: function () {
  7953. if (this.boundingSphere === null) {
  7954. this.boundingSphere = new Sphere();
  7955. }
  7956. var position = this.attributes.position;
  7957. var morphAttributesPosition = this.morphAttributes.position;
  7958. if (position) {
  7959. // first, find the center of the bounding sphere
  7960. var center = this.boundingSphere.center;
  7961. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  7962. if (morphAttributesPosition) {
  7963. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7964. var morphAttribute = morphAttributesPosition[i];
  7965. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7966. _box$1.expandByPoint(_boxMorphTargets.min);
  7967. _box$1.expandByPoint(_boxMorphTargets.max);
  7968. }
  7969. }
  7970. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7971. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7972. var maxRadiusSq = 0;
  7973. for (var i = 0, il = position.count; i < il; i++) {
  7974. _vector$4.fromBufferAttribute(position, i);
  7975. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7976. } // process morph attributes if present
  7977. if (morphAttributesPosition) {
  7978. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7979. var morphAttribute = morphAttributesPosition[i];
  7980. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  7981. _vector$4.fromBufferAttribute(morphAttribute, j);
  7982. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7983. }
  7984. }
  7985. }
  7986. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7987. if (isNaN(this.boundingSphere.radius)) {
  7988. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7989. }
  7990. }
  7991. },
  7992. computeFaceNormals: function () {// backwards compatibility
  7993. },
  7994. computeVertexNormals: function () {
  7995. var index = this.index;
  7996. var attributes = this.attributes;
  7997. if (attributes.position) {
  7998. var positions = attributes.position.array;
  7999. if (attributes.normal === undefined) {
  8000. this.addAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  8001. } else {
  8002. // reset existing normals to zero
  8003. var array = attributes.normal.array;
  8004. for (var i = 0, il = array.length; i < il; i++) {
  8005. array[i] = 0;
  8006. }
  8007. }
  8008. var normals = attributes.normal.array;
  8009. var vA, vB, vC;
  8010. var pA = new Vector3(),
  8011. pB = new Vector3(),
  8012. pC = new Vector3();
  8013. var cb = new Vector3(),
  8014. ab = new Vector3(); // indexed elements
  8015. if (index) {
  8016. var indices = index.array;
  8017. for (var i = 0, il = index.count; i < il; i += 3) {
  8018. vA = indices[i + 0] * 3;
  8019. vB = indices[i + 1] * 3;
  8020. vC = indices[i + 2] * 3;
  8021. pA.fromArray(positions, vA);
  8022. pB.fromArray(positions, vB);
  8023. pC.fromArray(positions, vC);
  8024. cb.subVectors(pC, pB);
  8025. ab.subVectors(pA, pB);
  8026. cb.cross(ab);
  8027. normals[vA] += cb.x;
  8028. normals[vA + 1] += cb.y;
  8029. normals[vA + 2] += cb.z;
  8030. normals[vB] += cb.x;
  8031. normals[vB + 1] += cb.y;
  8032. normals[vB + 2] += cb.z;
  8033. normals[vC] += cb.x;
  8034. normals[vC + 1] += cb.y;
  8035. normals[vC + 2] += cb.z;
  8036. }
  8037. } else {
  8038. // non-indexed elements (unconnected triangle soup)
  8039. for (var i = 0, il = positions.length; i < il; i += 9) {
  8040. pA.fromArray(positions, i);
  8041. pB.fromArray(positions, i + 3);
  8042. pC.fromArray(positions, i + 6);
  8043. cb.subVectors(pC, pB);
  8044. ab.subVectors(pA, pB);
  8045. cb.cross(ab);
  8046. normals[i] = cb.x;
  8047. normals[i + 1] = cb.y;
  8048. normals[i + 2] = cb.z;
  8049. normals[i + 3] = cb.x;
  8050. normals[i + 4] = cb.y;
  8051. normals[i + 5] = cb.z;
  8052. normals[i + 6] = cb.x;
  8053. normals[i + 7] = cb.y;
  8054. normals[i + 8] = cb.z;
  8055. }
  8056. }
  8057. this.normalizeNormals();
  8058. attributes.normal.needsUpdate = true;
  8059. }
  8060. },
  8061. merge: function (geometry, offset) {
  8062. if (!(geometry && geometry.isBufferGeometry)) {
  8063. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  8064. return;
  8065. }
  8066. if (offset === undefined) {
  8067. offset = 0;
  8068. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  8069. }
  8070. var attributes = this.attributes;
  8071. for (var key in attributes) {
  8072. if (geometry.attributes[key] === undefined) continue;
  8073. var attribute1 = attributes[key];
  8074. var attributeArray1 = attribute1.array;
  8075. var attribute2 = geometry.attributes[key];
  8076. var attributeArray2 = attribute2.array;
  8077. var attributeOffset = attribute2.itemSize * offset;
  8078. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  8079. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  8080. attributeArray1[j] = attributeArray2[i];
  8081. }
  8082. }
  8083. return this;
  8084. },
  8085. normalizeNormals: function () {
  8086. var normals = this.attributes.normal;
  8087. for (var i = 0, il = normals.count; i < il; i++) {
  8088. _vector$4.x = normals.getX(i);
  8089. _vector$4.y = normals.getY(i);
  8090. _vector$4.z = normals.getZ(i);
  8091. _vector$4.normalize();
  8092. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  8093. }
  8094. },
  8095. toNonIndexed: function () {
  8096. function convertBufferAttribute(attribute, indices) {
  8097. var array = attribute.array;
  8098. var itemSize = attribute.itemSize;
  8099. var array2 = new array.constructor(indices.length * itemSize);
  8100. var index = 0,
  8101. index2 = 0;
  8102. for (var i = 0, l = indices.length; i < l; i++) {
  8103. index = indices[i] * itemSize;
  8104. for (var j = 0; j < itemSize; j++) {
  8105. array2[index2++] = array[index++];
  8106. }
  8107. }
  8108. return new BufferAttribute(array2, itemSize);
  8109. } //
  8110. if (this.index === null) {
  8111. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  8112. return this;
  8113. }
  8114. var geometry2 = new BufferGeometry();
  8115. var indices = this.index.array;
  8116. var attributes = this.attributes; // attributes
  8117. for (var name in attributes) {
  8118. var attribute = attributes[name];
  8119. var newAttribute = convertBufferAttribute(attribute, indices);
  8120. geometry2.addAttribute(name, newAttribute);
  8121. } // morph attributes
  8122. var morphAttributes = this.morphAttributes;
  8123. for (name in morphAttributes) {
  8124. var morphArray = [];
  8125. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8126. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  8127. var attribute = morphAttribute[i];
  8128. var newAttribute = convertBufferAttribute(attribute, indices);
  8129. morphArray.push(newAttribute);
  8130. }
  8131. geometry2.morphAttributes[name] = morphArray;
  8132. } // groups
  8133. var groups = this.groups;
  8134. for (var i = 0, l = groups.length; i < l; i++) {
  8135. var group = groups[i];
  8136. geometry2.addGroup(group.start, group.count, group.materialIndex);
  8137. }
  8138. return geometry2;
  8139. },
  8140. toJSON: function () {
  8141. var data = {
  8142. metadata: {
  8143. version: 4.5,
  8144. type: 'BufferGeometry',
  8145. generator: 'BufferGeometry.toJSON'
  8146. }
  8147. }; // standard BufferGeometry serialization
  8148. data.uuid = this.uuid;
  8149. data.type = this.type;
  8150. if (this.name !== '') data.name = this.name;
  8151. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  8152. if (this.parameters !== undefined) {
  8153. var parameters = this.parameters;
  8154. for (var key in parameters) {
  8155. if (parameters[key] !== undefined) data[key] = parameters[key];
  8156. }
  8157. return data;
  8158. }
  8159. data.data = {
  8160. attributes: {}
  8161. };
  8162. var index = this.index;
  8163. if (index !== null) {
  8164. data.data.index = {
  8165. type: index.array.constructor.name,
  8166. array: Array.prototype.slice.call(index.array)
  8167. };
  8168. }
  8169. var attributes = this.attributes;
  8170. for (var key in attributes) {
  8171. var attribute = attributes[key];
  8172. var attributeData = attribute.toJSON();
  8173. if (attribute.name !== '') attributeData.name = attribute.name;
  8174. data.data.attributes[key] = attributeData;
  8175. }
  8176. var morphAttributes = {};
  8177. var hasMorphAttributes = false;
  8178. for (var key in this.morphAttributes) {
  8179. var attributeArray = this.morphAttributes[key];
  8180. var array = [];
  8181. for (var i = 0, il = attributeArray.length; i < il; i++) {
  8182. var attribute = attributeArray[i];
  8183. var attributeData = attribute.toJSON();
  8184. if (attribute.name !== '') attributeData.name = attribute.name;
  8185. array.push(attributeData);
  8186. }
  8187. if (array.length > 0) {
  8188. morphAttributes[key] = array;
  8189. hasMorphAttributes = true;
  8190. }
  8191. }
  8192. if (hasMorphAttributes) data.data.morphAttributes = morphAttributes;
  8193. var groups = this.groups;
  8194. if (groups.length > 0) {
  8195. data.data.groups = JSON.parse(JSON.stringify(groups));
  8196. }
  8197. var boundingSphere = this.boundingSphere;
  8198. if (boundingSphere !== null) {
  8199. data.data.boundingSphere = {
  8200. center: boundingSphere.center.toArray(),
  8201. radius: boundingSphere.radius
  8202. };
  8203. }
  8204. return data;
  8205. },
  8206. clone: function () {
  8207. /*
  8208. // Handle primitives
  8209. var parameters = this.parameters;
  8210. if ( parameters !== undefined ) {
  8211. var values = [];
  8212. for ( var key in parameters ) {
  8213. values.push( parameters[ key ] );
  8214. }
  8215. var geometry = Object.create( this.constructor.prototype );
  8216. this.constructor.apply( geometry, values );
  8217. return geometry;
  8218. }
  8219. return new this.constructor().copy( this );
  8220. */
  8221. return new BufferGeometry().copy(this);
  8222. },
  8223. copy: function (source) {
  8224. var name, i, l; // reset
  8225. this.index = null;
  8226. this.attributes = {};
  8227. this.morphAttributes = {};
  8228. this.groups = [];
  8229. this.boundingBox = null;
  8230. this.boundingSphere = null; // name
  8231. this.name = source.name; // index
  8232. var index = source.index;
  8233. if (index !== null) {
  8234. this.setIndex(index.clone());
  8235. } // attributes
  8236. var attributes = source.attributes;
  8237. for (name in attributes) {
  8238. var attribute = attributes[name];
  8239. this.addAttribute(name, attribute.clone());
  8240. } // morph attributes
  8241. var morphAttributes = source.morphAttributes;
  8242. for (name in morphAttributes) {
  8243. var array = [];
  8244. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  8245. for (i = 0, l = morphAttribute.length; i < l; i++) {
  8246. array.push(morphAttribute[i].clone());
  8247. }
  8248. this.morphAttributes[name] = array;
  8249. } // groups
  8250. var groups = source.groups;
  8251. for (i = 0, l = groups.length; i < l; i++) {
  8252. var group = groups[i];
  8253. this.addGroup(group.start, group.count, group.materialIndex);
  8254. } // bounding box
  8255. var boundingBox = source.boundingBox;
  8256. if (boundingBox !== null) {
  8257. this.boundingBox = boundingBox.clone();
  8258. } // bounding sphere
  8259. var boundingSphere = source.boundingSphere;
  8260. if (boundingSphere !== null) {
  8261. this.boundingSphere = boundingSphere.clone();
  8262. } // draw range
  8263. this.drawRange.start = source.drawRange.start;
  8264. this.drawRange.count = source.drawRange.count; // user data
  8265. this.userData = source.userData;
  8266. return this;
  8267. },
  8268. dispose: function () {
  8269. this.dispatchEvent({
  8270. type: 'dispose'
  8271. });
  8272. }
  8273. });
  8274. /**
  8275. * @author mrdoob / http://mrdoob.com/
  8276. * @author alteredq / http://alteredqualia.com/
  8277. * @author mikael emtinger / http://gomo.se/
  8278. * @author jonobr1 / http://jonobr1.com/
  8279. */
  8280. var _inverseMatrix = new Matrix4();
  8281. var _ray = new Ray();
  8282. var _sphere = new Sphere();
  8283. var _vA = new Vector3();
  8284. var _vB = new Vector3();
  8285. var _vC = new Vector3();
  8286. var _tempA = new Vector3();
  8287. var _tempB = new Vector3();
  8288. var _tempC = new Vector3();
  8289. var _morphA = new Vector3();
  8290. var _morphB = new Vector3();
  8291. var _morphC = new Vector3();
  8292. var _uvA = new Vector2();
  8293. var _uvB = new Vector2();
  8294. var _uvC = new Vector2();
  8295. var _intersectionPoint = new Vector3();
  8296. var _intersectionPointWorld = new Vector3();
  8297. function Mesh(geometry, material) {
  8298. Object3D.call(this);
  8299. this.type = 'Mesh';
  8300. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  8301. this.material = material !== undefined ? material : new MeshBasicMaterial({
  8302. color: Math.random() * 0xffffff
  8303. });
  8304. this.drawMode = TrianglesDrawMode;
  8305. this.updateMorphTargets();
  8306. }
  8307. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  8308. constructor: Mesh,
  8309. isMesh: true,
  8310. setDrawMode: function (value) {
  8311. this.drawMode = value;
  8312. },
  8313. copy: function (source) {
  8314. Object3D.prototype.copy.call(this, source);
  8315. this.drawMode = source.drawMode;
  8316. if (source.morphTargetInfluences !== undefined) {
  8317. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  8318. }
  8319. if (source.morphTargetDictionary !== undefined) {
  8320. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  8321. }
  8322. return this;
  8323. },
  8324. updateMorphTargets: function () {
  8325. var geometry = this.geometry;
  8326. var m, ml, name;
  8327. if (geometry.isBufferGeometry) {
  8328. var morphAttributes = geometry.morphAttributes;
  8329. var keys = Object.keys(morphAttributes);
  8330. if (keys.length > 0) {
  8331. var morphAttribute = morphAttributes[keys[0]];
  8332. if (morphAttribute !== undefined) {
  8333. this.morphTargetInfluences = [];
  8334. this.morphTargetDictionary = {};
  8335. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  8336. name = morphAttribute[m].name || String(m);
  8337. this.morphTargetInfluences.push(0);
  8338. this.morphTargetDictionary[name] = m;
  8339. }
  8340. }
  8341. }
  8342. } else {
  8343. var morphTargets = geometry.morphTargets;
  8344. if (morphTargets !== undefined && morphTargets.length > 0) {
  8345. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  8346. }
  8347. }
  8348. },
  8349. raycast: function (raycaster, intersects) {
  8350. var geometry = this.geometry;
  8351. var material = this.material;
  8352. var matrixWorld = this.matrixWorld;
  8353. if (material === undefined) return; // Checking boundingSphere distance to ray
  8354. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8355. _sphere.copy(geometry.boundingSphere);
  8356. _sphere.applyMatrix4(matrixWorld);
  8357. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  8358. _inverseMatrix.getInverse(matrixWorld);
  8359. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  8360. if (geometry.boundingBox !== null) {
  8361. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  8362. }
  8363. var intersection;
  8364. if (geometry.isBufferGeometry) {
  8365. var a, b, c;
  8366. var index = geometry.index;
  8367. var position = geometry.attributes.position;
  8368. var morphPosition = geometry.morphAttributes.position;
  8369. var uv = geometry.attributes.uv;
  8370. var uv2 = geometry.attributes.uv2;
  8371. var groups = geometry.groups;
  8372. var drawRange = geometry.drawRange;
  8373. var i, j, il, jl;
  8374. var group, groupMaterial;
  8375. var start, end;
  8376. if (index !== null) {
  8377. // indexed buffer geometry
  8378. if (Array.isArray(material)) {
  8379. for (i = 0, il = groups.length; i < il; i++) {
  8380. group = groups[i];
  8381. groupMaterial = material[group.materialIndex];
  8382. start = Math.max(group.start, drawRange.start);
  8383. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8384. for (j = start, jl = end; j < jl; j += 3) {
  8385. a = index.getX(j);
  8386. b = index.getX(j + 1);
  8387. c = index.getX(j + 2);
  8388. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8389. if (intersection) {
  8390. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  8391. intersection.face.materialIndex = group.materialIndex;
  8392. intersects.push(intersection);
  8393. }
  8394. }
  8395. }
  8396. } else {
  8397. start = Math.max(0, drawRange.start);
  8398. end = Math.min(index.count, drawRange.start + drawRange.count);
  8399. for (i = start, il = end; i < il; i += 3) {
  8400. a = index.getX(i);
  8401. b = index.getX(i + 1);
  8402. c = index.getX(i + 2);
  8403. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8404. if (intersection) {
  8405. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  8406. intersects.push(intersection);
  8407. }
  8408. }
  8409. }
  8410. } else if (position !== undefined) {
  8411. // non-indexed buffer geometry
  8412. if (Array.isArray(material)) {
  8413. for (i = 0, il = groups.length; i < il; i++) {
  8414. group = groups[i];
  8415. groupMaterial = material[group.materialIndex];
  8416. start = Math.max(group.start, drawRange.start);
  8417. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  8418. for (j = start, jl = end; j < jl; j += 3) {
  8419. a = j;
  8420. b = j + 1;
  8421. c = j + 2;
  8422. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8423. if (intersection) {
  8424. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  8425. intersection.face.materialIndex = group.materialIndex;
  8426. intersects.push(intersection);
  8427. }
  8428. }
  8429. }
  8430. } else {
  8431. start = Math.max(0, drawRange.start);
  8432. end = Math.min(position.count, drawRange.start + drawRange.count);
  8433. for (i = start, il = end; i < il; i += 3) {
  8434. a = i;
  8435. b = i + 1;
  8436. c = i + 2;
  8437. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, uv, uv2, a, b, c);
  8438. if (intersection) {
  8439. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  8440. intersects.push(intersection);
  8441. }
  8442. }
  8443. }
  8444. }
  8445. } else if (geometry.isGeometry) {
  8446. var fvA, fvB, fvC;
  8447. var isMultiMaterial = Array.isArray(material);
  8448. var vertices = geometry.vertices;
  8449. var faces = geometry.faces;
  8450. var uvs;
  8451. var faceVertexUvs = geometry.faceVertexUvs[0];
  8452. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  8453. for (var f = 0, fl = faces.length; f < fl; f++) {
  8454. var face = faces[f];
  8455. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  8456. if (faceMaterial === undefined) continue;
  8457. fvA = vertices[face.a];
  8458. fvB = vertices[face.b];
  8459. fvC = vertices[face.c];
  8460. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  8461. if (intersection) {
  8462. if (uvs && uvs[f]) {
  8463. var uvs_f = uvs[f];
  8464. _uvA.copy(uvs_f[0]);
  8465. _uvB.copy(uvs_f[1]);
  8466. _uvC.copy(uvs_f[2]);
  8467. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  8468. }
  8469. intersection.face = face;
  8470. intersection.faceIndex = f;
  8471. intersects.push(intersection);
  8472. }
  8473. }
  8474. }
  8475. },
  8476. clone: function () {
  8477. return new this.constructor(this.geometry, this.material).copy(this);
  8478. }
  8479. });
  8480. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  8481. var intersect;
  8482. if (material.side === BackSide) {
  8483. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  8484. } else {
  8485. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  8486. }
  8487. if (intersect === null) return null;
  8488. _intersectionPointWorld.copy(point);
  8489. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  8490. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  8491. if (distance < raycaster.near || distance > raycaster.far) return null;
  8492. return {
  8493. distance: distance,
  8494. point: _intersectionPointWorld.clone(),
  8495. object: object
  8496. };
  8497. }
  8498. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, uv, uv2, a, b, c) {
  8499. _vA.fromBufferAttribute(position, a);
  8500. _vB.fromBufferAttribute(position, b);
  8501. _vC.fromBufferAttribute(position, c);
  8502. var morphInfluences = object.morphTargetInfluences;
  8503. if (material.morphTargets && morphPosition && morphInfluences) {
  8504. _morphA.set(0, 0, 0);
  8505. _morphB.set(0, 0, 0);
  8506. _morphC.set(0, 0, 0);
  8507. for (var i = 0, il = morphPosition.length; i < il; i++) {
  8508. var influence = morphInfluences[i];
  8509. var morphAttribute = morphPosition[i];
  8510. if (influence === 0) continue;
  8511. _tempA.fromBufferAttribute(morphAttribute, a);
  8512. _tempB.fromBufferAttribute(morphAttribute, b);
  8513. _tempC.fromBufferAttribute(morphAttribute, c);
  8514. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  8515. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  8516. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  8517. }
  8518. _vA.add(_morphA);
  8519. _vB.add(_morphB);
  8520. _vC.add(_morphC);
  8521. }
  8522. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  8523. if (intersection) {
  8524. if (uv) {
  8525. _uvA.fromBufferAttribute(uv, a);
  8526. _uvB.fromBufferAttribute(uv, b);
  8527. _uvC.fromBufferAttribute(uv, c);
  8528. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8529. }
  8530. if (uv2) {
  8531. _uvA.fromBufferAttribute(uv2, a);
  8532. _uvB.fromBufferAttribute(uv2, b);
  8533. _uvC.fromBufferAttribute(uv2, c);
  8534. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  8535. }
  8536. var face = new Face3(a, b, c);
  8537. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  8538. intersection.face = face;
  8539. }
  8540. return intersection;
  8541. }
  8542. /**
  8543. * @author mrdoob / http://mrdoob.com/
  8544. * @author kile / http://kile.stravaganza.org/
  8545. * @author alteredq / http://alteredqualia.com/
  8546. * @author mikael emtinger / http://gomo.se/
  8547. * @author zz85 / http://www.lab4games.net/zz85/blog
  8548. * @author bhouston / http://clara.io
  8549. */
  8550. var _geometryId = 0; // Geometry uses even numbers as Id
  8551. var _m1$3 = new Matrix4();
  8552. var _obj$1 = new Object3D();
  8553. var _offset$1 = new Vector3();
  8554. function Geometry() {
  8555. Object.defineProperty(this, 'id', {
  8556. value: _geometryId += 2
  8557. });
  8558. this.uuid = _Math.generateUUID();
  8559. this.name = '';
  8560. this.type = 'Geometry';
  8561. this.vertices = [];
  8562. this.colors = [];
  8563. this.faces = [];
  8564. this.faceVertexUvs = [[]];
  8565. this.morphTargets = [];
  8566. this.morphNormals = [];
  8567. this.skinWeights = [];
  8568. this.skinIndices = [];
  8569. this.lineDistances = [];
  8570. this.boundingBox = null;
  8571. this.boundingSphere = null; // update flags
  8572. this.elementsNeedUpdate = false;
  8573. this.verticesNeedUpdate = false;
  8574. this.uvsNeedUpdate = false;
  8575. this.normalsNeedUpdate = false;
  8576. this.colorsNeedUpdate = false;
  8577. this.lineDistancesNeedUpdate = false;
  8578. this.groupsNeedUpdate = false;
  8579. }
  8580. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  8581. constructor: Geometry,
  8582. isGeometry: true,
  8583. applyMatrix: function (matrix) {
  8584. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8585. for (var i = 0, il = this.vertices.length; i < il; i++) {
  8586. var vertex = this.vertices[i];
  8587. vertex.applyMatrix4(matrix);
  8588. }
  8589. for (var i = 0, il = this.faces.length; i < il; i++) {
  8590. var face = this.faces[i];
  8591. face.normal.applyMatrix3(normalMatrix).normalize();
  8592. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  8593. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  8594. }
  8595. }
  8596. if (this.boundingBox !== null) {
  8597. this.computeBoundingBox();
  8598. }
  8599. if (this.boundingSphere !== null) {
  8600. this.computeBoundingSphere();
  8601. }
  8602. this.verticesNeedUpdate = true;
  8603. this.normalsNeedUpdate = true;
  8604. return this;
  8605. },
  8606. rotateX: function (angle) {
  8607. // rotate geometry around world x-axis
  8608. _m1$3.makeRotationX(angle);
  8609. this.applyMatrix(_m1$3);
  8610. return this;
  8611. },
  8612. rotateY: function (angle) {
  8613. // rotate geometry around world y-axis
  8614. _m1$3.makeRotationY(angle);
  8615. this.applyMatrix(_m1$3);
  8616. return this;
  8617. },
  8618. rotateZ: function (angle) {
  8619. // rotate geometry around world z-axis
  8620. _m1$3.makeRotationZ(angle);
  8621. this.applyMatrix(_m1$3);
  8622. return this;
  8623. },
  8624. translate: function (x, y, z) {
  8625. // translate geometry
  8626. _m1$3.makeTranslation(x, y, z);
  8627. this.applyMatrix(_m1$3);
  8628. return this;
  8629. },
  8630. scale: function (x, y, z) {
  8631. // scale geometry
  8632. _m1$3.makeScale(x, y, z);
  8633. this.applyMatrix(_m1$3);
  8634. return this;
  8635. },
  8636. lookAt: function (vector) {
  8637. _obj$1.lookAt(vector);
  8638. _obj$1.updateMatrix();
  8639. this.applyMatrix(_obj$1.matrix);
  8640. return this;
  8641. },
  8642. fromBufferGeometry: function (geometry) {
  8643. var scope = this;
  8644. var indices = geometry.index !== null ? geometry.index.array : undefined;
  8645. var attributes = geometry.attributes;
  8646. if (attributes.position === undefined) {
  8647. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  8648. return this;
  8649. }
  8650. var positions = attributes.position.array;
  8651. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  8652. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  8653. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  8654. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  8655. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  8656. for (var i = 0; i < positions.length; i += 3) {
  8657. scope.vertices.push(new Vector3().fromArray(positions, i));
  8658. if (colors !== undefined) {
  8659. scope.colors.push(new Color().fromArray(colors, i));
  8660. }
  8661. }
  8662. function addFace(a, b, c, materialIndex) {
  8663. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  8664. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  8665. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  8666. scope.faces.push(face);
  8667. if (uvs !== undefined) {
  8668. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  8669. }
  8670. if (uvs2 !== undefined) {
  8671. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  8672. }
  8673. }
  8674. var groups = geometry.groups;
  8675. if (groups.length > 0) {
  8676. for (var i = 0; i < groups.length; i++) {
  8677. var group = groups[i];
  8678. var start = group.start;
  8679. var count = group.count;
  8680. for (var j = start, jl = start + count; j < jl; j += 3) {
  8681. if (indices !== undefined) {
  8682. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  8683. } else {
  8684. addFace(j, j + 1, j + 2, group.materialIndex);
  8685. }
  8686. }
  8687. }
  8688. } else {
  8689. if (indices !== undefined) {
  8690. for (var i = 0; i < indices.length; i += 3) {
  8691. addFace(indices[i], indices[i + 1], indices[i + 2]);
  8692. }
  8693. } else {
  8694. for (var i = 0; i < positions.length / 3; i += 3) {
  8695. addFace(i, i + 1, i + 2);
  8696. }
  8697. }
  8698. }
  8699. this.computeFaceNormals();
  8700. if (geometry.boundingBox !== null) {
  8701. this.boundingBox = geometry.boundingBox.clone();
  8702. }
  8703. if (geometry.boundingSphere !== null) {
  8704. this.boundingSphere = geometry.boundingSphere.clone();
  8705. }
  8706. return this;
  8707. },
  8708. center: function () {
  8709. this.computeBoundingBox();
  8710. this.boundingBox.getCenter(_offset$1).negate();
  8711. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  8712. return this;
  8713. },
  8714. normalize: function () {
  8715. this.computeBoundingSphere();
  8716. var center = this.boundingSphere.center;
  8717. var radius = this.boundingSphere.radius;
  8718. var s = radius === 0 ? 1 : 1.0 / radius;
  8719. var matrix = new Matrix4();
  8720. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  8721. this.applyMatrix(matrix);
  8722. return this;
  8723. },
  8724. computeFaceNormals: function () {
  8725. var cb = new Vector3(),
  8726. ab = new Vector3();
  8727. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  8728. var face = this.faces[f];
  8729. var vA = this.vertices[face.a];
  8730. var vB = this.vertices[face.b];
  8731. var vC = this.vertices[face.c];
  8732. cb.subVectors(vC, vB);
  8733. ab.subVectors(vA, vB);
  8734. cb.cross(ab);
  8735. cb.normalize();
  8736. face.normal.copy(cb);
  8737. }
  8738. },
  8739. computeVertexNormals: function (areaWeighted) {
  8740. if (areaWeighted === undefined) areaWeighted = true;
  8741. var v, vl, f, fl, face, vertices;
  8742. vertices = new Array(this.vertices.length);
  8743. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8744. vertices[v] = new Vector3();
  8745. }
  8746. if (areaWeighted) {
  8747. // vertex normals weighted by triangle areas
  8748. // http://www.iquilezles.org/www/articles/normals/normals.htm
  8749. var vA, vB, vC;
  8750. var cb = new Vector3(),
  8751. ab = new Vector3();
  8752. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8753. face = this.faces[f];
  8754. vA = this.vertices[face.a];
  8755. vB = this.vertices[face.b];
  8756. vC = this.vertices[face.c];
  8757. cb.subVectors(vC, vB);
  8758. ab.subVectors(vA, vB);
  8759. cb.cross(ab);
  8760. vertices[face.a].add(cb);
  8761. vertices[face.b].add(cb);
  8762. vertices[face.c].add(cb);
  8763. }
  8764. } else {
  8765. this.computeFaceNormals();
  8766. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8767. face = this.faces[f];
  8768. vertices[face.a].add(face.normal);
  8769. vertices[face.b].add(face.normal);
  8770. vertices[face.c].add(face.normal);
  8771. }
  8772. }
  8773. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  8774. vertices[v].normalize();
  8775. }
  8776. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8777. face = this.faces[f];
  8778. var vertexNormals = face.vertexNormals;
  8779. if (vertexNormals.length === 3) {
  8780. vertexNormals[0].copy(vertices[face.a]);
  8781. vertexNormals[1].copy(vertices[face.b]);
  8782. vertexNormals[2].copy(vertices[face.c]);
  8783. } else {
  8784. vertexNormals[0] = vertices[face.a].clone();
  8785. vertexNormals[1] = vertices[face.b].clone();
  8786. vertexNormals[2] = vertices[face.c].clone();
  8787. }
  8788. }
  8789. if (this.faces.length > 0) {
  8790. this.normalsNeedUpdate = true;
  8791. }
  8792. },
  8793. computeFlatVertexNormals: function () {
  8794. var f, fl, face;
  8795. this.computeFaceNormals();
  8796. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8797. face = this.faces[f];
  8798. var vertexNormals = face.vertexNormals;
  8799. if (vertexNormals.length === 3) {
  8800. vertexNormals[0].copy(face.normal);
  8801. vertexNormals[1].copy(face.normal);
  8802. vertexNormals[2].copy(face.normal);
  8803. } else {
  8804. vertexNormals[0] = face.normal.clone();
  8805. vertexNormals[1] = face.normal.clone();
  8806. vertexNormals[2] = face.normal.clone();
  8807. }
  8808. }
  8809. if (this.faces.length > 0) {
  8810. this.normalsNeedUpdate = true;
  8811. }
  8812. },
  8813. computeMorphNormals: function () {
  8814. var i, il, f, fl, face; // save original normals
  8815. // - create temp variables on first access
  8816. // otherwise just copy (for faster repeated calls)
  8817. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8818. face = this.faces[f];
  8819. if (!face.__originalFaceNormal) {
  8820. face.__originalFaceNormal = face.normal.clone();
  8821. } else {
  8822. face.__originalFaceNormal.copy(face.normal);
  8823. }
  8824. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  8825. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  8826. if (!face.__originalVertexNormals[i]) {
  8827. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  8828. } else {
  8829. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  8830. }
  8831. }
  8832. } // use temp geometry to compute face and vertex normals for each morph
  8833. var tmpGeo = new Geometry();
  8834. tmpGeo.faces = this.faces;
  8835. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  8836. // create on first access
  8837. if (!this.morphNormals[i]) {
  8838. this.morphNormals[i] = {};
  8839. this.morphNormals[i].faceNormals = [];
  8840. this.morphNormals[i].vertexNormals = [];
  8841. var dstNormalsFace = this.morphNormals[i].faceNormals;
  8842. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  8843. var faceNormal, vertexNormals;
  8844. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8845. faceNormal = new Vector3();
  8846. vertexNormals = {
  8847. a: new Vector3(),
  8848. b: new Vector3(),
  8849. c: new Vector3()
  8850. };
  8851. dstNormalsFace.push(faceNormal);
  8852. dstNormalsVertex.push(vertexNormals);
  8853. }
  8854. }
  8855. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  8856. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  8857. tmpGeo.computeFaceNormals();
  8858. tmpGeo.computeVertexNormals(); // store morph normals
  8859. var faceNormal, vertexNormals;
  8860. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8861. face = this.faces[f];
  8862. faceNormal = morphNormals.faceNormals[f];
  8863. vertexNormals = morphNormals.vertexNormals[f];
  8864. faceNormal.copy(face.normal);
  8865. vertexNormals.a.copy(face.vertexNormals[0]);
  8866. vertexNormals.b.copy(face.vertexNormals[1]);
  8867. vertexNormals.c.copy(face.vertexNormals[2]);
  8868. }
  8869. } // restore original normals
  8870. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8871. face = this.faces[f];
  8872. face.normal = face.__originalFaceNormal;
  8873. face.vertexNormals = face.__originalVertexNormals;
  8874. }
  8875. },
  8876. computeBoundingBox: function () {
  8877. if (this.boundingBox === null) {
  8878. this.boundingBox = new Box3();
  8879. }
  8880. this.boundingBox.setFromPoints(this.vertices);
  8881. },
  8882. computeBoundingSphere: function () {
  8883. if (this.boundingSphere === null) {
  8884. this.boundingSphere = new Sphere();
  8885. }
  8886. this.boundingSphere.setFromPoints(this.vertices);
  8887. },
  8888. merge: function (geometry, matrix, materialIndexOffset) {
  8889. if (!(geometry && geometry.isGeometry)) {
  8890. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  8891. return;
  8892. }
  8893. var normalMatrix,
  8894. vertexOffset = this.vertices.length,
  8895. vertices1 = this.vertices,
  8896. vertices2 = geometry.vertices,
  8897. faces1 = this.faces,
  8898. faces2 = geometry.faces,
  8899. colors1 = this.colors,
  8900. colors2 = geometry.colors;
  8901. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  8902. if (matrix !== undefined) {
  8903. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8904. } // vertices
  8905. for (var i = 0, il = vertices2.length; i < il; i++) {
  8906. var vertex = vertices2[i];
  8907. var vertexCopy = vertex.clone();
  8908. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  8909. vertices1.push(vertexCopy);
  8910. } // colors
  8911. for (var i = 0, il = colors2.length; i < il; i++) {
  8912. colors1.push(colors2[i].clone());
  8913. } // faces
  8914. for (i = 0, il = faces2.length; i < il; i++) {
  8915. var face = faces2[i],
  8916. faceCopy,
  8917. normal,
  8918. color,
  8919. faceVertexNormals = face.vertexNormals,
  8920. faceVertexColors = face.vertexColors;
  8921. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  8922. faceCopy.normal.copy(face.normal);
  8923. if (normalMatrix !== undefined) {
  8924. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  8925. }
  8926. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  8927. normal = faceVertexNormals[j].clone();
  8928. if (normalMatrix !== undefined) {
  8929. normal.applyMatrix3(normalMatrix).normalize();
  8930. }
  8931. faceCopy.vertexNormals.push(normal);
  8932. }
  8933. faceCopy.color.copy(face.color);
  8934. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  8935. color = faceVertexColors[j];
  8936. faceCopy.vertexColors.push(color.clone());
  8937. }
  8938. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8939. faces1.push(faceCopy);
  8940. } // uvs
  8941. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  8942. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  8943. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  8944. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  8945. var uvs2 = faceVertexUvs2[j],
  8946. uvsCopy = [];
  8947. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  8948. uvsCopy.push(uvs2[k].clone());
  8949. }
  8950. this.faceVertexUvs[i].push(uvsCopy);
  8951. }
  8952. }
  8953. },
  8954. mergeMesh: function (mesh) {
  8955. if (!(mesh && mesh.isMesh)) {
  8956. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  8957. return;
  8958. }
  8959. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  8960. this.merge(mesh.geometry, mesh.matrix);
  8961. },
  8962. /*
  8963. * Checks for duplicate vertices with hashmap.
  8964. * Duplicated vertices are removed
  8965. * and faces' vertices are updated.
  8966. */
  8967. mergeVertices: function () {
  8968. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8969. var unique = [],
  8970. changes = [];
  8971. var v, key;
  8972. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  8973. var precision = Math.pow(10, precisionPoints);
  8974. var i, il, face;
  8975. var indices, j, jl;
  8976. for (i = 0, il = this.vertices.length; i < il; i++) {
  8977. v = this.vertices[i];
  8978. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  8979. if (verticesMap[key] === undefined) {
  8980. verticesMap[key] = i;
  8981. unique.push(this.vertices[i]);
  8982. changes[i] = unique.length - 1;
  8983. } else {
  8984. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  8985. changes[i] = changes[verticesMap[key]];
  8986. }
  8987. } // if faces are completely degenerate after merging vertices, we
  8988. // have to remove them from the geometry.
  8989. var faceIndicesToRemove = [];
  8990. for (i = 0, il = this.faces.length; i < il; i++) {
  8991. face = this.faces[i];
  8992. face.a = changes[face.a];
  8993. face.b = changes[face.b];
  8994. face.c = changes[face.c];
  8995. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  8996. // we have to remove the face as nothing can be saved
  8997. for (var n = 0; n < 3; n++) {
  8998. if (indices[n] === indices[(n + 1) % 3]) {
  8999. faceIndicesToRemove.push(i);
  9000. break;
  9001. }
  9002. }
  9003. }
  9004. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  9005. var idx = faceIndicesToRemove[i];
  9006. this.faces.splice(idx, 1);
  9007. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  9008. this.faceVertexUvs[j].splice(idx, 1);
  9009. }
  9010. } // Use unique set of vertices
  9011. var diff = this.vertices.length - unique.length;
  9012. this.vertices = unique;
  9013. return diff;
  9014. },
  9015. setFromPoints: function (points) {
  9016. this.vertices = [];
  9017. for (var i = 0, l = points.length; i < l; i++) {
  9018. var point = points[i];
  9019. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  9020. }
  9021. return this;
  9022. },
  9023. sortFacesByMaterialIndex: function () {
  9024. var faces = this.faces;
  9025. var length = faces.length; // tag faces
  9026. for (var i = 0; i < length; i++) {
  9027. faces[i]._id = i;
  9028. } // sort faces
  9029. function materialIndexSort(a, b) {
  9030. return a.materialIndex - b.materialIndex;
  9031. }
  9032. faces.sort(materialIndexSort); // sort uvs
  9033. var uvs1 = this.faceVertexUvs[0];
  9034. var uvs2 = this.faceVertexUvs[1];
  9035. var newUvs1, newUvs2;
  9036. if (uvs1 && uvs1.length === length) newUvs1 = [];
  9037. if (uvs2 && uvs2.length === length) newUvs2 = [];
  9038. for (var i = 0; i < length; i++) {
  9039. var id = faces[i]._id;
  9040. if (newUvs1) newUvs1.push(uvs1[id]);
  9041. if (newUvs2) newUvs2.push(uvs2[id]);
  9042. }
  9043. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  9044. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  9045. },
  9046. toJSON: function () {
  9047. var data = {
  9048. metadata: {
  9049. version: 4.5,
  9050. type: 'Geometry',
  9051. generator: 'Geometry.toJSON'
  9052. }
  9053. }; // standard Geometry serialization
  9054. data.uuid = this.uuid;
  9055. data.type = this.type;
  9056. if (this.name !== '') data.name = this.name;
  9057. if (this.parameters !== undefined) {
  9058. var parameters = this.parameters;
  9059. for (var key in parameters) {
  9060. if (parameters[key] !== undefined) data[key] = parameters[key];
  9061. }
  9062. return data;
  9063. }
  9064. var vertices = [];
  9065. for (var i = 0; i < this.vertices.length; i++) {
  9066. var vertex = this.vertices[i];
  9067. vertices.push(vertex.x, vertex.y, vertex.z);
  9068. }
  9069. var faces = [];
  9070. var normals = [];
  9071. var normalsHash = {};
  9072. var colors = [];
  9073. var colorsHash = {};
  9074. var uvs = [];
  9075. var uvsHash = {};
  9076. for (var i = 0; i < this.faces.length; i++) {
  9077. var face = this.faces[i];
  9078. var hasMaterial = true;
  9079. var hasFaceUv = false; // deprecated
  9080. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  9081. var hasFaceNormal = face.normal.length() > 0;
  9082. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  9083. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  9084. var hasFaceVertexColor = face.vertexColors.length > 0;
  9085. var faceType = 0;
  9086. faceType = setBit(faceType, 0, 0); // isQuad
  9087. faceType = setBit(faceType, 1, hasMaterial);
  9088. faceType = setBit(faceType, 2, hasFaceUv);
  9089. faceType = setBit(faceType, 3, hasFaceVertexUv);
  9090. faceType = setBit(faceType, 4, hasFaceNormal);
  9091. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  9092. faceType = setBit(faceType, 6, hasFaceColor);
  9093. faceType = setBit(faceType, 7, hasFaceVertexColor);
  9094. faces.push(faceType);
  9095. faces.push(face.a, face.b, face.c);
  9096. faces.push(face.materialIndex);
  9097. if (hasFaceVertexUv) {
  9098. var faceVertexUvs = this.faceVertexUvs[0][i];
  9099. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  9100. }
  9101. if (hasFaceNormal) {
  9102. faces.push(getNormalIndex(face.normal));
  9103. }
  9104. if (hasFaceVertexNormal) {
  9105. var vertexNormals = face.vertexNormals;
  9106. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  9107. }
  9108. if (hasFaceColor) {
  9109. faces.push(getColorIndex(face.color));
  9110. }
  9111. if (hasFaceVertexColor) {
  9112. var vertexColors = face.vertexColors;
  9113. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  9114. }
  9115. }
  9116. function setBit(value, position, enabled) {
  9117. return enabled ? value | 1 << position : value & ~(1 << position);
  9118. }
  9119. function getNormalIndex(normal) {
  9120. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  9121. if (normalsHash[hash] !== undefined) {
  9122. return normalsHash[hash];
  9123. }
  9124. normalsHash[hash] = normals.length / 3;
  9125. normals.push(normal.x, normal.y, normal.z);
  9126. return normalsHash[hash];
  9127. }
  9128. function getColorIndex(color) {
  9129. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  9130. if (colorsHash[hash] !== undefined) {
  9131. return colorsHash[hash];
  9132. }
  9133. colorsHash[hash] = colors.length;
  9134. colors.push(color.getHex());
  9135. return colorsHash[hash];
  9136. }
  9137. function getUvIndex(uv) {
  9138. var hash = uv.x.toString() + uv.y.toString();
  9139. if (uvsHash[hash] !== undefined) {
  9140. return uvsHash[hash];
  9141. }
  9142. uvsHash[hash] = uvs.length / 2;
  9143. uvs.push(uv.x, uv.y);
  9144. return uvsHash[hash];
  9145. }
  9146. data.data = {};
  9147. data.data.vertices = vertices;
  9148. data.data.normals = normals;
  9149. if (colors.length > 0) data.data.colors = colors;
  9150. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  9151. data.data.faces = faces;
  9152. return data;
  9153. },
  9154. clone: function () {
  9155. /*
  9156. // Handle primitives
  9157. var parameters = this.parameters;
  9158. if ( parameters !== undefined ) {
  9159. var values = [];
  9160. for ( var key in parameters ) {
  9161. values.push( parameters[ key ] );
  9162. }
  9163. var geometry = Object.create( this.constructor.prototype );
  9164. this.constructor.apply( geometry, values );
  9165. return geometry;
  9166. }
  9167. return new this.constructor().copy( this );
  9168. */
  9169. return new Geometry().copy(this);
  9170. },
  9171. copy: function (source) {
  9172. var i, il, j, jl, k, kl; // reset
  9173. this.vertices = [];
  9174. this.colors = [];
  9175. this.faces = [];
  9176. this.faceVertexUvs = [[]];
  9177. this.morphTargets = [];
  9178. this.morphNormals = [];
  9179. this.skinWeights = [];
  9180. this.skinIndices = [];
  9181. this.lineDistances = [];
  9182. this.boundingBox = null;
  9183. this.boundingSphere = null; // name
  9184. this.name = source.name; // vertices
  9185. var vertices = source.vertices;
  9186. for (i = 0, il = vertices.length; i < il; i++) {
  9187. this.vertices.push(vertices[i].clone());
  9188. } // colors
  9189. var colors = source.colors;
  9190. for (i = 0, il = colors.length; i < il; i++) {
  9191. this.colors.push(colors[i].clone());
  9192. } // faces
  9193. var faces = source.faces;
  9194. for (i = 0, il = faces.length; i < il; i++) {
  9195. this.faces.push(faces[i].clone());
  9196. } // face vertex uvs
  9197. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  9198. var faceVertexUvs = source.faceVertexUvs[i];
  9199. if (this.faceVertexUvs[i] === undefined) {
  9200. this.faceVertexUvs[i] = [];
  9201. }
  9202. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  9203. var uvs = faceVertexUvs[j],
  9204. uvsCopy = [];
  9205. for (k = 0, kl = uvs.length; k < kl; k++) {
  9206. var uv = uvs[k];
  9207. uvsCopy.push(uv.clone());
  9208. }
  9209. this.faceVertexUvs[i].push(uvsCopy);
  9210. }
  9211. } // morph targets
  9212. var morphTargets = source.morphTargets;
  9213. for (i = 0, il = morphTargets.length; i < il; i++) {
  9214. var morphTarget = {};
  9215. morphTarget.name = morphTargets[i].name; // vertices
  9216. if (morphTargets[i].vertices !== undefined) {
  9217. morphTarget.vertices = [];
  9218. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  9219. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  9220. }
  9221. } // normals
  9222. if (morphTargets[i].normals !== undefined) {
  9223. morphTarget.normals = [];
  9224. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  9225. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  9226. }
  9227. }
  9228. this.morphTargets.push(morphTarget);
  9229. } // morph normals
  9230. var morphNormals = source.morphNormals;
  9231. for (i = 0, il = morphNormals.length; i < il; i++) {
  9232. var morphNormal = {}; // vertex normals
  9233. if (morphNormals[i].vertexNormals !== undefined) {
  9234. morphNormal.vertexNormals = [];
  9235. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  9236. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  9237. var destVertexNormal = {};
  9238. destVertexNormal.a = srcVertexNormal.a.clone();
  9239. destVertexNormal.b = srcVertexNormal.b.clone();
  9240. destVertexNormal.c = srcVertexNormal.c.clone();
  9241. morphNormal.vertexNormals.push(destVertexNormal);
  9242. }
  9243. } // face normals
  9244. if (morphNormals[i].faceNormals !== undefined) {
  9245. morphNormal.faceNormals = [];
  9246. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  9247. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  9248. }
  9249. }
  9250. this.morphNormals.push(morphNormal);
  9251. } // skin weights
  9252. var skinWeights = source.skinWeights;
  9253. for (i = 0, il = skinWeights.length; i < il; i++) {
  9254. this.skinWeights.push(skinWeights[i].clone());
  9255. } // skin indices
  9256. var skinIndices = source.skinIndices;
  9257. for (i = 0, il = skinIndices.length; i < il; i++) {
  9258. this.skinIndices.push(skinIndices[i].clone());
  9259. } // line distances
  9260. var lineDistances = source.lineDistances;
  9261. for (i = 0, il = lineDistances.length; i < il; i++) {
  9262. this.lineDistances.push(lineDistances[i]);
  9263. } // bounding box
  9264. var boundingBox = source.boundingBox;
  9265. if (boundingBox !== null) {
  9266. this.boundingBox = boundingBox.clone();
  9267. } // bounding sphere
  9268. var boundingSphere = source.boundingSphere;
  9269. if (boundingSphere !== null) {
  9270. this.boundingSphere = boundingSphere.clone();
  9271. } // update flags
  9272. this.elementsNeedUpdate = source.elementsNeedUpdate;
  9273. this.verticesNeedUpdate = source.verticesNeedUpdate;
  9274. this.uvsNeedUpdate = source.uvsNeedUpdate;
  9275. this.normalsNeedUpdate = source.normalsNeedUpdate;
  9276. this.colorsNeedUpdate = source.colorsNeedUpdate;
  9277. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  9278. this.groupsNeedUpdate = source.groupsNeedUpdate;
  9279. return this;
  9280. },
  9281. dispose: function () {
  9282. this.dispatchEvent({
  9283. type: 'dispose'
  9284. });
  9285. }
  9286. });
  9287. /**
  9288. * @author mrdoob / http://mrdoob.com/
  9289. * @author Mugen87 / https://github.com/Mugen87
  9290. */
  9291. // BoxGeometry
  9292. class BoxGeometry extends Geometry {
  9293. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9294. super();
  9295. this.type = 'BoxGeometry';
  9296. this.parameters = {
  9297. width: width,
  9298. height: height,
  9299. depth: depth,
  9300. widthSegments: widthSegments,
  9301. heightSegments: heightSegments,
  9302. depthSegments: depthSegments
  9303. };
  9304. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  9305. this.mergeVertices();
  9306. }
  9307. } // BoxBufferGeometry
  9308. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  9309. class BoxBufferGeometry extends BufferGeometry {
  9310. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  9311. super();
  9312. this.type = 'BoxBufferGeometry';
  9313. this.parameters = {
  9314. width: width,
  9315. height: height,
  9316. depth: depth,
  9317. widthSegments: widthSegments,
  9318. heightSegments: heightSegments,
  9319. depthSegments: depthSegments
  9320. };
  9321. var scope = this;
  9322. width = width || 1;
  9323. height = height || 1;
  9324. depth = depth || 1; // segments
  9325. widthSegments = Math.floor(widthSegments) || 1;
  9326. heightSegments = Math.floor(heightSegments) || 1;
  9327. depthSegments = Math.floor(depthSegments) || 1; // buffers
  9328. var indices = [];
  9329. var vertices = [];
  9330. var normals = [];
  9331. var uvs = []; // helper variables
  9332. var numberOfVertices = 0;
  9333. var groupStart = 0; // build each side of the box geometry
  9334. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  9335. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  9336. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  9337. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  9338. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  9339. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  9340. // build geometry
  9341. this.setIndex(indices);
  9342. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  9343. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  9344. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9345. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  9346. var segmentWidth = width / gridX;
  9347. var segmentHeight = height / gridY;
  9348. var widthHalf = width / 2;
  9349. var heightHalf = height / 2;
  9350. var depthHalf = depth / 2;
  9351. var gridX1 = gridX + 1;
  9352. var gridY1 = gridY + 1;
  9353. var vertexCounter = 0;
  9354. var groupCount = 0;
  9355. var ix, iy;
  9356. var vector = new Vector3(); // generate vertices, normals and uvs
  9357. for (iy = 0; iy < gridY1; iy++) {
  9358. var y = iy * segmentHeight - heightHalf;
  9359. for (ix = 0; ix < gridX1; ix++) {
  9360. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  9361. vector[u] = x * udir;
  9362. vector[v] = y * vdir;
  9363. vector[w] = depthHalf; // now apply vector to vertex buffer
  9364. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  9365. vector[u] = 0;
  9366. vector[v] = 0;
  9367. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  9368. normals.push(vector.x, vector.y, vector.z); // uvs
  9369. uvs.push(ix / gridX);
  9370. uvs.push(1 - iy / gridY); // counters
  9371. vertexCounter += 1;
  9372. }
  9373. } // indices
  9374. // 1. you need three indices to draw a single face
  9375. // 2. a single segment consists of two faces
  9376. // 3. so we need to generate six (2*3) indices per segment
  9377. for (iy = 0; iy < gridY; iy++) {
  9378. for (ix = 0; ix < gridX; ix++) {
  9379. var a = numberOfVertices + ix + gridX1 * iy;
  9380. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  9381. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  9382. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  9383. indices.push(a, b, d);
  9384. indices.push(b, c, d); // increase counter
  9385. groupCount += 6;
  9386. }
  9387. } // add a group to the geometry. this will ensure multi material support
  9388. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  9389. groupStart += groupCount; // update total number of vertices
  9390. numberOfVertices += vertexCounter;
  9391. }
  9392. }
  9393. }
  9394. /**
  9395. * Uniform Utilities
  9396. */
  9397. exports.BoxBufferGeometry = BoxBufferGeometry;
  9398. function cloneUniforms(src) {
  9399. var dst = {};
  9400. for (var u in src) {
  9401. dst[u] = {};
  9402. for (var p in src[u]) {
  9403. var property = src[u][p];
  9404. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  9405. dst[u][p] = property.clone();
  9406. } else if (Array.isArray(property)) {
  9407. dst[u][p] = property.slice();
  9408. } else {
  9409. dst[u][p] = property;
  9410. }
  9411. }
  9412. }
  9413. return dst;
  9414. }
  9415. function mergeUniforms(uniforms) {
  9416. var merged = {};
  9417. for (var u = 0; u < uniforms.length; u++) {
  9418. var tmp = cloneUniforms(uniforms[u]);
  9419. for (var p in tmp) {
  9420. merged[p] = tmp[p];
  9421. }
  9422. }
  9423. return merged;
  9424. } // Legacy
  9425. var UniformsUtils = {
  9426. clone: cloneUniforms,
  9427. merge: mergeUniforms
  9428. };
  9429. exports.UniformsUtils = UniformsUtils;
  9430. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  9431. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  9432. /**
  9433. * @author alteredq / http://alteredqualia.com/
  9434. *
  9435. * parameters = {
  9436. * defines: { "label" : "value" },
  9437. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  9438. *
  9439. * fragmentShader: <string>,
  9440. * vertexShader: <string>,
  9441. *
  9442. * wireframe: <boolean>,
  9443. * wireframeLinewidth: <float>,
  9444. *
  9445. * lights: <bool>,
  9446. *
  9447. * skinning: <bool>,
  9448. * morphTargets: <bool>,
  9449. * morphNormals: <bool>
  9450. * }
  9451. */
  9452. function ShaderMaterial(parameters) {
  9453. Material.call(this);
  9454. this.type = 'ShaderMaterial';
  9455. this.defines = {};
  9456. this.uniforms = {};
  9457. this.vertexShader = default_vertex;
  9458. this.fragmentShader = default_fragment;
  9459. this.linewidth = 1;
  9460. this.wireframe = false;
  9461. this.wireframeLinewidth = 1;
  9462. this.fog = false; // set to use scene fog
  9463. this.lights = false; // set to use scene lights
  9464. this.clipping = false; // set to use user-defined clipping planes
  9465. this.skinning = false; // set to use skinning attribute streams
  9466. this.morphTargets = false; // set to use morph targets
  9467. this.morphNormals = false; // set to use morph normals
  9468. this.extensions = {
  9469. derivatives: false,
  9470. // set to use derivatives
  9471. fragDepth: false,
  9472. // set to use fragment depth values
  9473. drawBuffers: false,
  9474. // set to use draw buffers
  9475. shaderTextureLOD: false // set to use shader texture LOD
  9476. }; // When rendered geometry doesn't include these attributes but the material does,
  9477. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9478. this.defaultAttributeValues = {
  9479. 'color': [1, 1, 1],
  9480. 'uv': [0, 0],
  9481. 'uv2': [0, 0]
  9482. };
  9483. this.index0AttributeName = undefined;
  9484. this.uniformsNeedUpdate = false;
  9485. if (parameters !== undefined) {
  9486. if (parameters.attributes !== undefined) {
  9487. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  9488. }
  9489. this.setValues(parameters);
  9490. }
  9491. }
  9492. ShaderMaterial.prototype = Object.create(Material.prototype);
  9493. ShaderMaterial.prototype.constructor = ShaderMaterial;
  9494. ShaderMaterial.prototype.isShaderMaterial = true;
  9495. ShaderMaterial.prototype.copy = function (source) {
  9496. Material.prototype.copy.call(this, source);
  9497. this.fragmentShader = source.fragmentShader;
  9498. this.vertexShader = source.vertexShader;
  9499. this.uniforms = cloneUniforms(source.uniforms);
  9500. this.defines = Object.assign({}, source.defines);
  9501. this.wireframe = source.wireframe;
  9502. this.wireframeLinewidth = source.wireframeLinewidth;
  9503. this.lights = source.lights;
  9504. this.clipping = source.clipping;
  9505. this.skinning = source.skinning;
  9506. this.morphTargets = source.morphTargets;
  9507. this.morphNormals = source.morphNormals;
  9508. this.extensions = source.extensions;
  9509. return this;
  9510. };
  9511. ShaderMaterial.prototype.toJSON = function (meta) {
  9512. var data = Material.prototype.toJSON.call(this, meta);
  9513. data.uniforms = {};
  9514. for (var name in this.uniforms) {
  9515. var uniform = this.uniforms[name];
  9516. var value = uniform.value;
  9517. if (value && value.isTexture) {
  9518. data.uniforms[name] = {
  9519. type: 't',
  9520. value: value.toJSON(meta).uuid
  9521. };
  9522. } else if (value && value.isColor) {
  9523. data.uniforms[name] = {
  9524. type: 'c',
  9525. value: value.getHex()
  9526. };
  9527. } else if (value && value.isVector2) {
  9528. data.uniforms[name] = {
  9529. type: 'v2',
  9530. value: value.toArray()
  9531. };
  9532. } else if (value && value.isVector3) {
  9533. data.uniforms[name] = {
  9534. type: 'v3',
  9535. value: value.toArray()
  9536. };
  9537. } else if (value && value.isVector4) {
  9538. data.uniforms[name] = {
  9539. type: 'v4',
  9540. value: value.toArray()
  9541. };
  9542. } else if (value && value.isMatrix3) {
  9543. data.uniforms[name] = {
  9544. type: 'm3',
  9545. value: value.toArray()
  9546. };
  9547. } else if (value && value.isMatrix4) {
  9548. data.uniforms[name] = {
  9549. type: 'm4',
  9550. value: value.toArray()
  9551. };
  9552. } else {
  9553. data.uniforms[name] = {
  9554. value: value
  9555. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  9556. }
  9557. }
  9558. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  9559. data.vertexShader = this.vertexShader;
  9560. data.fragmentShader = this.fragmentShader;
  9561. var extensions = {};
  9562. for (var key in this.extensions) {
  9563. if (this.extensions[key] === true) extensions[key] = true;
  9564. }
  9565. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  9566. return data;
  9567. };
  9568. /**
  9569. * @author mrdoob / http://mrdoob.com/
  9570. * @author mikael emtinger / http://gomo.se/
  9571. * @author WestLangley / http://github.com/WestLangley
  9572. */
  9573. function Camera() {
  9574. Object3D.call(this);
  9575. this.type = 'Camera';
  9576. this.matrixWorldInverse = new Matrix4();
  9577. this.projectionMatrix = new Matrix4();
  9578. this.projectionMatrixInverse = new Matrix4();
  9579. }
  9580. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  9581. constructor: Camera,
  9582. isCamera: true,
  9583. copy: function (source, recursive) {
  9584. Object3D.prototype.copy.call(this, source, recursive);
  9585. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  9586. this.projectionMatrix.copy(source.projectionMatrix);
  9587. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  9588. return this;
  9589. },
  9590. getWorldDirection: function (target) {
  9591. if (target === undefined) {
  9592. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  9593. target = new Vector3();
  9594. }
  9595. this.updateMatrixWorld(true);
  9596. var e = this.matrixWorld.elements;
  9597. return target.set(-e[8], -e[9], -e[10]).normalize();
  9598. },
  9599. updateMatrixWorld: function (force) {
  9600. Object3D.prototype.updateMatrixWorld.call(this, force);
  9601. this.matrixWorldInverse.getInverse(this.matrixWorld);
  9602. },
  9603. clone: function () {
  9604. return new this.constructor().copy(this);
  9605. }
  9606. });
  9607. /**
  9608. * @author mrdoob / http://mrdoob.com/
  9609. * @author greggman / http://games.greggman.com/
  9610. * @author zz85 / http://www.lab4games.net/zz85/blog
  9611. * @author tschw
  9612. */
  9613. function PerspectiveCamera(fov, aspect, near, far) {
  9614. Camera.call(this);
  9615. this.type = 'PerspectiveCamera';
  9616. this.fov = fov !== undefined ? fov : 50;
  9617. this.zoom = 1;
  9618. this.near = near !== undefined ? near : 0.1;
  9619. this.far = far !== undefined ? far : 2000;
  9620. this.focus = 10;
  9621. this.aspect = aspect !== undefined ? aspect : 1;
  9622. this.view = null;
  9623. this.filmGauge = 35; // width of the film (default in millimeters)
  9624. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9625. this.updateProjectionMatrix();
  9626. }
  9627. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  9628. constructor: PerspectiveCamera,
  9629. isPerspectiveCamera: true,
  9630. copy: function (source, recursive) {
  9631. Camera.prototype.copy.call(this, source, recursive);
  9632. this.fov = source.fov;
  9633. this.zoom = source.zoom;
  9634. this.near = source.near;
  9635. this.far = source.far;
  9636. this.focus = source.focus;
  9637. this.aspect = source.aspect;
  9638. this.view = source.view === null ? null : Object.assign({}, source.view);
  9639. this.filmGauge = source.filmGauge;
  9640. this.filmOffset = source.filmOffset;
  9641. return this;
  9642. },
  9643. /**
  9644. * Sets the FOV by focal length in respect to the current .filmGauge.
  9645. *
  9646. * The default film gauge is 35, so that the focal length can be specified for
  9647. * a 35mm (full frame) camera.
  9648. *
  9649. * Values for focal length and film gauge must have the same unit.
  9650. */
  9651. setFocalLength: function (focalLength) {
  9652. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  9653. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9654. this.fov = _Math.RAD2DEG * 2 * Math.atan(vExtentSlope);
  9655. this.updateProjectionMatrix();
  9656. },
  9657. /**
  9658. * Calculates the focal length from the current .fov and .filmGauge.
  9659. */
  9660. getFocalLength: function () {
  9661. var vExtentSlope = Math.tan(_Math.DEG2RAD * 0.5 * this.fov);
  9662. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9663. },
  9664. getEffectiveFOV: function () {
  9665. return _Math.RAD2DEG * 2 * Math.atan(Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom);
  9666. },
  9667. getFilmWidth: function () {
  9668. // film not completely covered in portrait format (aspect < 1)
  9669. return this.filmGauge * Math.min(this.aspect, 1);
  9670. },
  9671. getFilmHeight: function () {
  9672. // film not completely covered in landscape format (aspect > 1)
  9673. return this.filmGauge / Math.max(this.aspect, 1);
  9674. },
  9675. /**
  9676. * Sets an offset in a larger frustum. This is useful for multi-window or
  9677. * multi-monitor/multi-machine setups.
  9678. *
  9679. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9680. * the monitors are in grid like this
  9681. *
  9682. * +---+---+---+
  9683. * | A | B | C |
  9684. * +---+---+---+
  9685. * | D | E | F |
  9686. * +---+---+---+
  9687. *
  9688. * then for each monitor you would call it like this
  9689. *
  9690. * var w = 1920;
  9691. * var h = 1080;
  9692. * var fullWidth = w * 3;
  9693. * var fullHeight = h * 2;
  9694. *
  9695. * --A--
  9696. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9697. * --B--
  9698. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9699. * --C--
  9700. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9701. * --D--
  9702. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9703. * --E--
  9704. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9705. * --F--
  9706. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9707. *
  9708. * Note there is no reason monitors have to be the same size or in a grid.
  9709. */
  9710. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  9711. this.aspect = fullWidth / fullHeight;
  9712. if (this.view === null) {
  9713. this.view = {
  9714. enabled: true,
  9715. fullWidth: 1,
  9716. fullHeight: 1,
  9717. offsetX: 0,
  9718. offsetY: 0,
  9719. width: 1,
  9720. height: 1
  9721. };
  9722. }
  9723. this.view.enabled = true;
  9724. this.view.fullWidth = fullWidth;
  9725. this.view.fullHeight = fullHeight;
  9726. this.view.offsetX = x;
  9727. this.view.offsetY = y;
  9728. this.view.width = width;
  9729. this.view.height = height;
  9730. this.updateProjectionMatrix();
  9731. },
  9732. clearViewOffset: function () {
  9733. if (this.view !== null) {
  9734. this.view.enabled = false;
  9735. }
  9736. this.updateProjectionMatrix();
  9737. },
  9738. updateProjectionMatrix: function () {
  9739. var near = this.near,
  9740. top = near * Math.tan(_Math.DEG2RAD * 0.5 * this.fov) / this.zoom,
  9741. height = 2 * top,
  9742. width = this.aspect * height,
  9743. left = -0.5 * width,
  9744. view = this.view;
  9745. if (this.view !== null && this.view.enabled) {
  9746. var fullWidth = view.fullWidth,
  9747. fullHeight = view.fullHeight;
  9748. left += view.offsetX * width / fullWidth;
  9749. top -= view.offsetY * height / fullHeight;
  9750. width *= view.width / fullWidth;
  9751. height *= view.height / fullHeight;
  9752. }
  9753. var skew = this.filmOffset;
  9754. if (skew !== 0) left += near * skew / this.getFilmWidth();
  9755. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  9756. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  9757. },
  9758. toJSON: function (meta) {
  9759. var data = Object3D.prototype.toJSON.call(this, meta);
  9760. data.object.fov = this.fov;
  9761. data.object.zoom = this.zoom;
  9762. data.object.near = this.near;
  9763. data.object.far = this.far;
  9764. data.object.focus = this.focus;
  9765. data.object.aspect = this.aspect;
  9766. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9767. data.object.filmGauge = this.filmGauge;
  9768. data.object.filmOffset = this.filmOffset;
  9769. return data;
  9770. }
  9771. });
  9772. /**
  9773. * Camera for rendering cube maps
  9774. * - renders scene into axis-aligned cube
  9775. *
  9776. * @author alteredq / http://alteredqualia.com/
  9777. */
  9778. var fov = 90,
  9779. aspect = 1;
  9780. function CubeCamera(near, far, cubeResolution, options) {
  9781. Object3D.call(this);
  9782. this.type = 'CubeCamera';
  9783. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  9784. cameraPX.up.set(0, -1, 0);
  9785. cameraPX.lookAt(new Vector3(1, 0, 0));
  9786. this.add(cameraPX);
  9787. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  9788. cameraNX.up.set(0, -1, 0);
  9789. cameraNX.lookAt(new Vector3(-1, 0, 0));
  9790. this.add(cameraNX);
  9791. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  9792. cameraPY.up.set(0, 0, 1);
  9793. cameraPY.lookAt(new Vector3(0, 1, 0));
  9794. this.add(cameraPY);
  9795. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  9796. cameraNY.up.set(0, 0, -1);
  9797. cameraNY.lookAt(new Vector3(0, -1, 0));
  9798. this.add(cameraNY);
  9799. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  9800. cameraPZ.up.set(0, -1, 0);
  9801. cameraPZ.lookAt(new Vector3(0, 0, 1));
  9802. this.add(cameraPZ);
  9803. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  9804. cameraNZ.up.set(0, -1, 0);
  9805. cameraNZ.lookAt(new Vector3(0, 0, -1));
  9806. this.add(cameraNZ);
  9807. options = options || {
  9808. format: RGBFormat,
  9809. magFilter: LinearFilter,
  9810. minFilter: LinearFilter
  9811. };
  9812. this.renderTarget = new WebGLRenderTargetCube(cubeResolution, cubeResolution, options);
  9813. this.renderTarget.texture.name = "CubeCamera";
  9814. this.update = function (renderer, scene) {
  9815. if (this.parent === null) this.updateMatrixWorld();
  9816. var currentRenderTarget = renderer.getRenderTarget();
  9817. var renderTarget = this.renderTarget;
  9818. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9819. renderTarget.texture.generateMipmaps = false;
  9820. renderer.setRenderTarget(renderTarget, 0);
  9821. renderer.render(scene, cameraPX);
  9822. renderer.setRenderTarget(renderTarget, 1);
  9823. renderer.render(scene, cameraNX);
  9824. renderer.setRenderTarget(renderTarget, 2);
  9825. renderer.render(scene, cameraPY);
  9826. renderer.setRenderTarget(renderTarget, 3);
  9827. renderer.render(scene, cameraNY);
  9828. renderer.setRenderTarget(renderTarget, 4);
  9829. renderer.render(scene, cameraPZ);
  9830. renderTarget.texture.generateMipmaps = generateMipmaps;
  9831. renderer.setRenderTarget(renderTarget, 5);
  9832. renderer.render(scene, cameraNZ);
  9833. renderer.setRenderTarget(currentRenderTarget);
  9834. };
  9835. this.clear = function (renderer, color, depth, stencil) {
  9836. var currentRenderTarget = renderer.getRenderTarget();
  9837. var renderTarget = this.renderTarget;
  9838. for (var i = 0; i < 6; i++) {
  9839. renderer.setRenderTarget(renderTarget, i);
  9840. renderer.clear(color, depth, stencil);
  9841. }
  9842. renderer.setRenderTarget(currentRenderTarget);
  9843. };
  9844. }
  9845. CubeCamera.prototype = Object.create(Object3D.prototype);
  9846. CubeCamera.prototype.constructor = CubeCamera;
  9847. /**
  9848. * @author alteredq / http://alteredqualia.com
  9849. * @author WestLangley / http://github.com/WestLangley
  9850. */
  9851. function WebGLRenderTargetCube(width, height, options) {
  9852. WebGLRenderTarget.call(this, width, height, options);
  9853. }
  9854. WebGLRenderTargetCube.prototype = Object.create(WebGLRenderTarget.prototype);
  9855. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  9856. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  9857. WebGLRenderTargetCube.prototype.fromEquirectangularTexture = function (renderer, texture) {
  9858. this.texture.type = texture.type;
  9859. this.texture.format = texture.format;
  9860. this.texture.encoding = texture.encoding;
  9861. var scene = new Scene();
  9862. var shader = {
  9863. uniforms: {
  9864. tEquirect: {
  9865. value: null
  9866. }
  9867. },
  9868. 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'),
  9869. 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')
  9870. };
  9871. var material = new ShaderMaterial({
  9872. type: 'CubemapFromEquirect',
  9873. uniforms: cloneUniforms(shader.uniforms),
  9874. vertexShader: shader.vertexShader,
  9875. fragmentShader: shader.fragmentShader,
  9876. side: BackSide,
  9877. blending: NoBlending
  9878. });
  9879. material.uniforms.tEquirect.value = texture;
  9880. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  9881. scene.add(mesh);
  9882. var camera = new CubeCamera(1, 10, 1);
  9883. camera.renderTarget = this;
  9884. camera.renderTarget.texture.name = 'CubeCameraTexture';
  9885. camera.update(renderer, scene);
  9886. mesh.geometry.dispose();
  9887. mesh.material.dispose();
  9888. return this;
  9889. };
  9890. /**
  9891. * @author alteredq / http://alteredqualia.com/
  9892. */
  9893. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  9894. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  9895. this.image = {
  9896. data: data || null,
  9897. width: width || 1,
  9898. height: height || 1
  9899. };
  9900. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  9901. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  9902. this.generateMipmaps = false;
  9903. this.flipY = false;
  9904. this.unpackAlignment = 1;
  9905. this.needsUpdate = true;
  9906. }
  9907. DataTexture.prototype = Object.create(Texture.prototype);
  9908. DataTexture.prototype.constructor = DataTexture;
  9909. DataTexture.prototype.isDataTexture = true;
  9910. /**
  9911. * @author bhouston / http://clara.io
  9912. */
  9913. var _vector1 = new Vector3();
  9914. var _vector2 = new Vector3();
  9915. var _normalMatrix = new Matrix3();
  9916. function Plane(normal, constant) {
  9917. // normal is assumed to be normalized
  9918. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  9919. this.constant = constant !== undefined ? constant : 0;
  9920. }
  9921. Object.assign(Plane.prototype, {
  9922. isPlane: true,
  9923. set: function (normal, constant) {
  9924. this.normal.copy(normal);
  9925. this.constant = constant;
  9926. return this;
  9927. },
  9928. setComponents: function (x, y, z, w) {
  9929. this.normal.set(x, y, z);
  9930. this.constant = w;
  9931. return this;
  9932. },
  9933. setFromNormalAndCoplanarPoint: function (normal, point) {
  9934. this.normal.copy(normal);
  9935. this.constant = -point.dot(this.normal);
  9936. return this;
  9937. },
  9938. setFromCoplanarPoints: function (a, b, c) {
  9939. 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)?
  9940. this.setFromNormalAndCoplanarPoint(normal, a);
  9941. return this;
  9942. },
  9943. clone: function () {
  9944. return new this.constructor().copy(this);
  9945. },
  9946. copy: function (plane) {
  9947. this.normal.copy(plane.normal);
  9948. this.constant = plane.constant;
  9949. return this;
  9950. },
  9951. normalize: function () {
  9952. // Note: will lead to a divide by zero if the plane is invalid.
  9953. var inverseNormalLength = 1.0 / this.normal.length();
  9954. this.normal.multiplyScalar(inverseNormalLength);
  9955. this.constant *= inverseNormalLength;
  9956. return this;
  9957. },
  9958. negate: function () {
  9959. this.constant *= -1;
  9960. this.normal.negate();
  9961. return this;
  9962. },
  9963. distanceToPoint: function (point) {
  9964. return this.normal.dot(point) + this.constant;
  9965. },
  9966. distanceToSphere: function (sphere) {
  9967. return this.distanceToPoint(sphere.center) - sphere.radius;
  9968. },
  9969. projectPoint: function (point, target) {
  9970. if (target === undefined) {
  9971. console.warn('THREE.Plane: .projectPoint() target is now required');
  9972. target = new Vector3();
  9973. }
  9974. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  9975. },
  9976. intersectLine: function (line, target) {
  9977. if (target === undefined) {
  9978. console.warn('THREE.Plane: .intersectLine() target is now required');
  9979. target = new Vector3();
  9980. }
  9981. var direction = line.delta(_vector1);
  9982. var denominator = this.normal.dot(direction);
  9983. if (denominator === 0) {
  9984. // line is coplanar, return origin
  9985. if (this.distanceToPoint(line.start) === 0) {
  9986. return target.copy(line.start);
  9987. } // Unsure if this is the correct method to handle this case.
  9988. return undefined;
  9989. }
  9990. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  9991. if (t < 0 || t > 1) {
  9992. return undefined;
  9993. }
  9994. return target.copy(direction).multiplyScalar(t).add(line.start);
  9995. },
  9996. intersectsLine: function (line) {
  9997. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  9998. var startSign = this.distanceToPoint(line.start);
  9999. var endSign = this.distanceToPoint(line.end);
  10000. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  10001. },
  10002. intersectsBox: function (box) {
  10003. return box.intersectsPlane(this);
  10004. },
  10005. intersectsSphere: function (sphere) {
  10006. return sphere.intersectsPlane(this);
  10007. },
  10008. coplanarPoint: function (target) {
  10009. if (target === undefined) {
  10010. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  10011. target = new Vector3();
  10012. }
  10013. return target.copy(this.normal).multiplyScalar(-this.constant);
  10014. },
  10015. applyMatrix4: function (matrix, optionalNormalMatrix) {
  10016. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  10017. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  10018. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  10019. this.constant = -referencePoint.dot(normal);
  10020. return this;
  10021. },
  10022. translate: function (offset) {
  10023. this.constant -= offset.dot(this.normal);
  10024. return this;
  10025. },
  10026. equals: function (plane) {
  10027. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  10028. }
  10029. });
  10030. /**
  10031. * @author mrdoob / http://mrdoob.com/
  10032. * @author alteredq / http://alteredqualia.com/
  10033. * @author bhouston / http://clara.io
  10034. */
  10035. var _sphere$1 = new Sphere();
  10036. var _vector$5 = new Vector3();
  10037. function Frustum(p0, p1, p2, p3, p4, p5) {
  10038. 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()];
  10039. }
  10040. Object.assign(Frustum.prototype, {
  10041. set: function (p0, p1, p2, p3, p4, p5) {
  10042. var planes = this.planes;
  10043. planes[0].copy(p0);
  10044. planes[1].copy(p1);
  10045. planes[2].copy(p2);
  10046. planes[3].copy(p3);
  10047. planes[4].copy(p4);
  10048. planes[5].copy(p5);
  10049. return this;
  10050. },
  10051. clone: function () {
  10052. return new this.constructor().copy(this);
  10053. },
  10054. copy: function (frustum) {
  10055. var planes = this.planes;
  10056. for (var i = 0; i < 6; i++) {
  10057. planes[i].copy(frustum.planes[i]);
  10058. }
  10059. return this;
  10060. },
  10061. setFromMatrix: function (m) {
  10062. var planes = this.planes;
  10063. var me = m.elements;
  10064. var me0 = me[0],
  10065. me1 = me[1],
  10066. me2 = me[2],
  10067. me3 = me[3];
  10068. var me4 = me[4],
  10069. me5 = me[5],
  10070. me6 = me[6],
  10071. me7 = me[7];
  10072. var me8 = me[8],
  10073. me9 = me[9],
  10074. me10 = me[10],
  10075. me11 = me[11];
  10076. var me12 = me[12],
  10077. me13 = me[13],
  10078. me14 = me[14],
  10079. me15 = me[15];
  10080. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  10081. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  10082. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  10083. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  10084. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  10085. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  10086. return this;
  10087. },
  10088. intersectsObject: function (object) {
  10089. var geometry = object.geometry;
  10090. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  10091. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  10092. return this.intersectsSphere(_sphere$1);
  10093. },
  10094. intersectsSprite: function (sprite) {
  10095. _sphere$1.center.set(0, 0, 0);
  10096. _sphere$1.radius = 0.7071067811865476;
  10097. _sphere$1.applyMatrix4(sprite.matrixWorld);
  10098. return this.intersectsSphere(_sphere$1);
  10099. },
  10100. intersectsSphere: function (sphere) {
  10101. var planes = this.planes;
  10102. var center = sphere.center;
  10103. var negRadius = -sphere.radius;
  10104. for (var i = 0; i < 6; i++) {
  10105. var distance = planes[i].distanceToPoint(center);
  10106. if (distance < negRadius) {
  10107. return false;
  10108. }
  10109. }
  10110. return true;
  10111. },
  10112. intersectsBox: function (box) {
  10113. var planes = this.planes;
  10114. for (var i = 0; i < 6; i++) {
  10115. var plane = planes[i]; // corner at max distance
  10116. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10117. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10118. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10119. if (plane.distanceToPoint(_vector$5) < 0) {
  10120. return false;
  10121. }
  10122. }
  10123. return true;
  10124. },
  10125. containsPoint: function (point) {
  10126. var planes = this.planes;
  10127. for (var i = 0; i < 6; i++) {
  10128. if (planes[i].distanceToPoint(point) < 0) {
  10129. return false;
  10130. }
  10131. }
  10132. return true;
  10133. }
  10134. });
  10135. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  10136. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  10137. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  10138. 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";
  10139. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  10140. var begin_vertex = "vec3 transformed = vec3( position );";
  10141. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  10142. 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";
  10143. 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";
  10144. 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";
  10145. 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";
  10146. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  10147. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  10148. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  10149. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10150. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  10151. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  10152. 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}";
  10153. 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";
  10154. 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";
  10155. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  10156. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  10157. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  10158. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  10159. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  10160. 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}";
  10161. 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";
  10162. 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";
  10163. 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";
  10164. 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";
  10165. 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";
  10166. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  10167. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  10168. 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";
  10169. 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";
  10170. 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";
  10171. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  10172. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  10173. 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";
  10174. 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";
  10175. 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";
  10176. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  10177. 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)";
  10178. 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";
  10179. 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}";
  10180. 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";
  10181. 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";
  10182. 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";
  10183. 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";
  10184. 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";
  10185. 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";
  10186. 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";
  10187. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  10188. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  10189. 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";
  10190. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  10191. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  10192. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  10193. 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";
  10194. 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";
  10195. 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";
  10196. 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;";
  10197. 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";
  10198. 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";
  10199. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  10200. 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";
  10201. var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  10202. 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}";
  10203. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  10204. 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;";
  10205. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  10206. 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";
  10207. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  10208. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  10209. 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";
  10210. 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";
  10211. 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";
  10212. 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}";
  10213. 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";
  10214. 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";
  10215. 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";
  10216. 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";
  10217. 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";
  10218. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  10219. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  10220. 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}";
  10221. var uv_pars_fragment = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif";
  10222. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  10223. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  10224. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  10225. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  10226. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  10227. 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";
  10228. 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}";
  10229. 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}";
  10230. 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}";
  10231. 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}";
  10232. 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}";
  10233. 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}";
  10234. 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}";
  10235. 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}";
  10236. 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}";
  10237. 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}";
  10238. 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}";
  10239. 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}";
  10240. 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}";
  10241. 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}";
  10242. 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}";
  10243. 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}";
  10244. 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}";
  10245. 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}";
  10246. 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}";
  10247. 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}";
  10248. 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}";
  10249. 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}";
  10250. 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}";
  10251. 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}";
  10252. 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}";
  10253. 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}";
  10254. 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}";
  10255. 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}";
  10256. 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}";
  10257. 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}";
  10258. var ShaderChunk = {
  10259. alphamap_fragment: alphamap_fragment,
  10260. alphamap_pars_fragment: alphamap_pars_fragment,
  10261. alphatest_fragment: alphatest_fragment,
  10262. aomap_fragment: aomap_fragment,
  10263. aomap_pars_fragment: aomap_pars_fragment,
  10264. begin_vertex: begin_vertex,
  10265. beginnormal_vertex: beginnormal_vertex,
  10266. bsdfs: bsdfs,
  10267. bumpmap_pars_fragment: bumpmap_pars_fragment,
  10268. clipping_planes_fragment: clipping_planes_fragment,
  10269. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  10270. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  10271. clipping_planes_vertex: clipping_planes_vertex,
  10272. color_fragment: color_fragment,
  10273. color_pars_fragment: color_pars_fragment,
  10274. color_pars_vertex: color_pars_vertex,
  10275. color_vertex: color_vertex,
  10276. common: common,
  10277. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  10278. defaultnormal_vertex: defaultnormal_vertex,
  10279. displacementmap_pars_vertex: displacementmap_pars_vertex,
  10280. displacementmap_vertex: displacementmap_vertex,
  10281. emissivemap_fragment: emissivemap_fragment,
  10282. emissivemap_pars_fragment: emissivemap_pars_fragment,
  10283. encodings_fragment: encodings_fragment,
  10284. encodings_pars_fragment: encodings_pars_fragment,
  10285. envmap_fragment: envmap_fragment,
  10286. envmap_common_pars_fragment: envmap_common_pars_fragment,
  10287. envmap_pars_fragment: envmap_pars_fragment,
  10288. envmap_pars_vertex: envmap_pars_vertex,
  10289. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  10290. envmap_vertex: envmap_vertex,
  10291. fog_vertex: fog_vertex,
  10292. fog_pars_vertex: fog_pars_vertex,
  10293. fog_fragment: fog_fragment,
  10294. fog_pars_fragment: fog_pars_fragment,
  10295. gradientmap_pars_fragment: gradientmap_pars_fragment,
  10296. lightmap_fragment: lightmap_fragment,
  10297. lightmap_pars_fragment: lightmap_pars_fragment,
  10298. lights_lambert_vertex: lights_lambert_vertex,
  10299. lights_pars_begin: lights_pars_begin,
  10300. lights_phong_fragment: lights_phong_fragment,
  10301. lights_phong_pars_fragment: lights_phong_pars_fragment,
  10302. lights_physical_fragment: lights_physical_fragment,
  10303. lights_physical_pars_fragment: lights_physical_pars_fragment,
  10304. lights_fragment_begin: lights_fragment_begin,
  10305. lights_fragment_maps: lights_fragment_maps,
  10306. lights_fragment_end: lights_fragment_end,
  10307. logdepthbuf_fragment: logdepthbuf_fragment,
  10308. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  10309. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  10310. logdepthbuf_vertex: logdepthbuf_vertex,
  10311. map_fragment: map_fragment,
  10312. map_pars_fragment: map_pars_fragment,
  10313. map_particle_fragment: map_particle_fragment,
  10314. map_particle_pars_fragment: map_particle_pars_fragment,
  10315. metalnessmap_fragment: metalnessmap_fragment,
  10316. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  10317. morphnormal_vertex: morphnormal_vertex,
  10318. morphtarget_pars_vertex: morphtarget_pars_vertex,
  10319. morphtarget_vertex: morphtarget_vertex,
  10320. normal_fragment_begin: normal_fragment_begin,
  10321. normal_fragment_maps: normal_fragment_maps,
  10322. normalmap_pars_fragment: normalmap_pars_fragment,
  10323. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  10324. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  10325. clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,
  10326. packing: packing,
  10327. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  10328. project_vertex: project_vertex,
  10329. dithering_fragment: dithering_fragment,
  10330. dithering_pars_fragment: dithering_pars_fragment,
  10331. roughnessmap_fragment: roughnessmap_fragment,
  10332. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  10333. shadowmap_pars_fragment: shadowmap_pars_fragment,
  10334. shadowmap_pars_vertex: shadowmap_pars_vertex,
  10335. shadowmap_vertex: shadowmap_vertex,
  10336. shadowmask_pars_fragment: shadowmask_pars_fragment,
  10337. skinbase_vertex: skinbase_vertex,
  10338. skinning_pars_vertex: skinning_pars_vertex,
  10339. skinning_vertex: skinning_vertex,
  10340. skinnormal_vertex: skinnormal_vertex,
  10341. specularmap_fragment: specularmap_fragment,
  10342. specularmap_pars_fragment: specularmap_pars_fragment,
  10343. tonemapping_fragment: tonemapping_fragment,
  10344. tonemapping_pars_fragment: tonemapping_pars_fragment,
  10345. uv_pars_fragment: uv_pars_fragment,
  10346. uv_pars_vertex: uv_pars_vertex,
  10347. uv_vertex: uv_vertex,
  10348. uv2_pars_fragment: uv2_pars_fragment,
  10349. uv2_pars_vertex: uv2_pars_vertex,
  10350. uv2_vertex: uv2_vertex,
  10351. worldpos_vertex: worldpos_vertex,
  10352. background_frag: background_frag,
  10353. background_vert: background_vert,
  10354. cube_frag: cube_frag,
  10355. cube_vert: cube_vert,
  10356. depth_frag: depth_frag,
  10357. depth_vert: depth_vert,
  10358. distanceRGBA_frag: distanceRGBA_frag,
  10359. distanceRGBA_vert: distanceRGBA_vert,
  10360. equirect_frag: equirect_frag,
  10361. equirect_vert: equirect_vert,
  10362. linedashed_frag: linedashed_frag,
  10363. linedashed_vert: linedashed_vert,
  10364. meshbasic_frag: meshbasic_frag,
  10365. meshbasic_vert: meshbasic_vert,
  10366. meshlambert_frag: meshlambert_frag,
  10367. meshlambert_vert: meshlambert_vert,
  10368. meshmatcap_frag: meshmatcap_frag,
  10369. meshmatcap_vert: meshmatcap_vert,
  10370. meshphong_frag: meshphong_frag,
  10371. meshphong_vert: meshphong_vert,
  10372. meshphysical_frag: meshphysical_frag,
  10373. meshphysical_vert: meshphysical_vert,
  10374. normal_frag: normal_frag,
  10375. normal_vert: normal_vert,
  10376. points_frag: points_frag,
  10377. points_vert: points_vert,
  10378. shadow_frag: shadow_frag,
  10379. shadow_vert: shadow_vert,
  10380. sprite_frag: sprite_frag,
  10381. sprite_vert: sprite_vert
  10382. };
  10383. /**
  10384. * Uniforms library for shared webgl shaders
  10385. */
  10386. exports.ShaderChunk = ShaderChunk;
  10387. var UniformsLib = {
  10388. common: {
  10389. diffuse: {
  10390. value: new Color(0xeeeeee)
  10391. },
  10392. opacity: {
  10393. value: 1.0
  10394. },
  10395. map: {
  10396. value: null
  10397. },
  10398. uvTransform: {
  10399. value: new Matrix3()
  10400. },
  10401. alphaMap: {
  10402. value: null
  10403. }
  10404. },
  10405. specularmap: {
  10406. specularMap: {
  10407. value: null
  10408. }
  10409. },
  10410. envmap: {
  10411. envMap: {
  10412. value: null
  10413. },
  10414. flipEnvMap: {
  10415. value: -1
  10416. },
  10417. reflectivity: {
  10418. value: 1.0
  10419. },
  10420. refractionRatio: {
  10421. value: 0.98
  10422. },
  10423. maxMipLevel: {
  10424. value: 0
  10425. }
  10426. },
  10427. aomap: {
  10428. aoMap: {
  10429. value: null
  10430. },
  10431. aoMapIntensity: {
  10432. value: 1
  10433. }
  10434. },
  10435. lightmap: {
  10436. lightMap: {
  10437. value: null
  10438. },
  10439. lightMapIntensity: {
  10440. value: 1
  10441. }
  10442. },
  10443. emissivemap: {
  10444. emissiveMap: {
  10445. value: null
  10446. }
  10447. },
  10448. bumpmap: {
  10449. bumpMap: {
  10450. value: null
  10451. },
  10452. bumpScale: {
  10453. value: 1
  10454. }
  10455. },
  10456. normalmap: {
  10457. normalMap: {
  10458. value: null
  10459. },
  10460. normalScale: {
  10461. value: new Vector2(1, 1)
  10462. }
  10463. },
  10464. displacementmap: {
  10465. displacementMap: {
  10466. value: null
  10467. },
  10468. displacementScale: {
  10469. value: 1
  10470. },
  10471. displacementBias: {
  10472. value: 0
  10473. }
  10474. },
  10475. roughnessmap: {
  10476. roughnessMap: {
  10477. value: null
  10478. }
  10479. },
  10480. metalnessmap: {
  10481. metalnessMap: {
  10482. value: null
  10483. }
  10484. },
  10485. gradientmap: {
  10486. gradientMap: {
  10487. value: null
  10488. }
  10489. },
  10490. fog: {
  10491. fogDensity: {
  10492. value: 0.00025
  10493. },
  10494. fogNear: {
  10495. value: 1
  10496. },
  10497. fogFar: {
  10498. value: 2000
  10499. },
  10500. fogColor: {
  10501. value: new Color(0xffffff)
  10502. }
  10503. },
  10504. lights: {
  10505. ambientLightColor: {
  10506. value: []
  10507. },
  10508. lightProbe: {
  10509. value: []
  10510. },
  10511. directionalLights: {
  10512. value: [],
  10513. properties: {
  10514. direction: {},
  10515. color: {},
  10516. shadow: {},
  10517. shadowBias: {},
  10518. shadowRadius: {},
  10519. shadowMapSize: {}
  10520. }
  10521. },
  10522. directionalShadowMap: {
  10523. value: []
  10524. },
  10525. directionalShadowMatrix: {
  10526. value: []
  10527. },
  10528. spotLights: {
  10529. value: [],
  10530. properties: {
  10531. color: {},
  10532. position: {},
  10533. direction: {},
  10534. distance: {},
  10535. coneCos: {},
  10536. penumbraCos: {},
  10537. decay: {},
  10538. shadow: {},
  10539. shadowBias: {},
  10540. shadowRadius: {},
  10541. shadowMapSize: {}
  10542. }
  10543. },
  10544. spotShadowMap: {
  10545. value: []
  10546. },
  10547. spotShadowMatrix: {
  10548. value: []
  10549. },
  10550. pointLights: {
  10551. value: [],
  10552. properties: {
  10553. color: {},
  10554. position: {},
  10555. decay: {},
  10556. distance: {},
  10557. shadow: {},
  10558. shadowBias: {},
  10559. shadowRadius: {},
  10560. shadowMapSize: {},
  10561. shadowCameraNear: {},
  10562. shadowCameraFar: {}
  10563. }
  10564. },
  10565. pointShadowMap: {
  10566. value: []
  10567. },
  10568. pointShadowMatrix: {
  10569. value: []
  10570. },
  10571. hemisphereLights: {
  10572. value: [],
  10573. properties: {
  10574. direction: {},
  10575. skyColor: {},
  10576. groundColor: {}
  10577. }
  10578. },
  10579. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  10580. rectAreaLights: {
  10581. value: [],
  10582. properties: {
  10583. color: {},
  10584. position: {},
  10585. width: {},
  10586. height: {}
  10587. }
  10588. }
  10589. },
  10590. points: {
  10591. diffuse: {
  10592. value: new Color(0xeeeeee)
  10593. },
  10594. opacity: {
  10595. value: 1.0
  10596. },
  10597. size: {
  10598. value: 1.0
  10599. },
  10600. scale: {
  10601. value: 1.0
  10602. },
  10603. map: {
  10604. value: null
  10605. },
  10606. uvTransform: {
  10607. value: new Matrix3()
  10608. }
  10609. },
  10610. sprite: {
  10611. diffuse: {
  10612. value: new Color(0xeeeeee)
  10613. },
  10614. opacity: {
  10615. value: 1.0
  10616. },
  10617. center: {
  10618. value: new Vector2(0.5, 0.5)
  10619. },
  10620. rotation: {
  10621. value: 0.0
  10622. },
  10623. map: {
  10624. value: null
  10625. },
  10626. uvTransform: {
  10627. value: new Matrix3()
  10628. }
  10629. }
  10630. };
  10631. /**
  10632. * @author alteredq / http://alteredqualia.com/
  10633. * @author mrdoob / http://mrdoob.com/
  10634. * @author mikael emtinger / http://gomo.se/
  10635. */
  10636. exports.UniformsLib = UniformsLib;
  10637. var ShaderLib = {
  10638. basic: {
  10639. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  10640. vertexShader: ShaderChunk.meshbasic_vert,
  10641. fragmentShader: ShaderChunk.meshbasic_frag
  10642. },
  10643. lambert: {
  10644. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  10645. emissive: {
  10646. value: new Color(0x000000)
  10647. }
  10648. }]),
  10649. vertexShader: ShaderChunk.meshlambert_vert,
  10650. fragmentShader: ShaderChunk.meshlambert_frag
  10651. },
  10652. phong: {
  10653. 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, {
  10654. emissive: {
  10655. value: new Color(0x000000)
  10656. },
  10657. specular: {
  10658. value: new Color(0x111111)
  10659. },
  10660. shininess: {
  10661. value: 30
  10662. }
  10663. }]),
  10664. vertexShader: ShaderChunk.meshphong_vert,
  10665. fragmentShader: ShaderChunk.meshphong_frag
  10666. },
  10667. standard: {
  10668. 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, {
  10669. emissive: {
  10670. value: new Color(0x000000)
  10671. },
  10672. roughness: {
  10673. value: 0.5
  10674. },
  10675. metalness: {
  10676. value: 0.5
  10677. },
  10678. envMapIntensity: {
  10679. value: 1
  10680. } // temporary
  10681. }]),
  10682. vertexShader: ShaderChunk.meshphysical_vert,
  10683. fragmentShader: ShaderChunk.meshphysical_frag
  10684. },
  10685. matcap: {
  10686. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  10687. matcap: {
  10688. value: null
  10689. }
  10690. }]),
  10691. vertexShader: ShaderChunk.meshmatcap_vert,
  10692. fragmentShader: ShaderChunk.meshmatcap_frag
  10693. },
  10694. points: {
  10695. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  10696. vertexShader: ShaderChunk.points_vert,
  10697. fragmentShader: ShaderChunk.points_frag
  10698. },
  10699. dashed: {
  10700. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  10701. scale: {
  10702. value: 1
  10703. },
  10704. dashSize: {
  10705. value: 1
  10706. },
  10707. totalSize: {
  10708. value: 2
  10709. }
  10710. }]),
  10711. vertexShader: ShaderChunk.linedashed_vert,
  10712. fragmentShader: ShaderChunk.linedashed_frag
  10713. },
  10714. depth: {
  10715. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  10716. vertexShader: ShaderChunk.depth_vert,
  10717. fragmentShader: ShaderChunk.depth_frag
  10718. },
  10719. normal: {
  10720. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  10721. opacity: {
  10722. value: 1.0
  10723. }
  10724. }]),
  10725. vertexShader: ShaderChunk.normal_vert,
  10726. fragmentShader: ShaderChunk.normal_frag
  10727. },
  10728. sprite: {
  10729. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  10730. vertexShader: ShaderChunk.sprite_vert,
  10731. fragmentShader: ShaderChunk.sprite_frag
  10732. },
  10733. background: {
  10734. uniforms: {
  10735. uvTransform: {
  10736. value: new Matrix3()
  10737. },
  10738. t2D: {
  10739. value: null
  10740. }
  10741. },
  10742. vertexShader: ShaderChunk.background_vert,
  10743. fragmentShader: ShaderChunk.background_frag
  10744. },
  10745. /* -------------------------------------------------------------------------
  10746. // Cube map shader
  10747. ------------------------------------------------------------------------- */
  10748. cube: {
  10749. uniforms: {
  10750. tCube: {
  10751. value: null
  10752. },
  10753. tFlip: {
  10754. value: -1
  10755. },
  10756. opacity: {
  10757. value: 1.0
  10758. }
  10759. },
  10760. vertexShader: ShaderChunk.cube_vert,
  10761. fragmentShader: ShaderChunk.cube_frag
  10762. },
  10763. equirect: {
  10764. uniforms: {
  10765. tEquirect: {
  10766. value: null
  10767. }
  10768. },
  10769. vertexShader: ShaderChunk.equirect_vert,
  10770. fragmentShader: ShaderChunk.equirect_frag
  10771. },
  10772. distanceRGBA: {
  10773. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  10774. referencePosition: {
  10775. value: new Vector3()
  10776. },
  10777. nearDistance: {
  10778. value: 1
  10779. },
  10780. farDistance: {
  10781. value: 1000
  10782. }
  10783. }]),
  10784. vertexShader: ShaderChunk.distanceRGBA_vert,
  10785. fragmentShader: ShaderChunk.distanceRGBA_frag
  10786. },
  10787. shadow: {
  10788. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  10789. color: {
  10790. value: new Color(0x00000)
  10791. },
  10792. opacity: {
  10793. value: 1.0
  10794. }
  10795. }]),
  10796. vertexShader: ShaderChunk.shadow_vert,
  10797. fragmentShader: ShaderChunk.shadow_frag
  10798. }
  10799. };
  10800. exports.ShaderLib = ShaderLib;
  10801. ShaderLib.physical = {
  10802. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  10803. transparency: {
  10804. value: 0
  10805. },
  10806. clearcoat: {
  10807. value: 0
  10808. },
  10809. clearcoatRoughness: {
  10810. value: 0
  10811. },
  10812. sheen: {
  10813. value: new Color(0x000000)
  10814. },
  10815. clearcoatNormalScale: {
  10816. value: new Vector2(1, 1)
  10817. },
  10818. clearcoatNormalMap: {
  10819. value: null
  10820. }
  10821. }]),
  10822. vertexShader: ShaderChunk.meshphysical_vert,
  10823. fragmentShader: ShaderChunk.meshphysical_frag
  10824. };
  10825. /**
  10826. * @author mrdoob / http://mrdoob.com/
  10827. */
  10828. function WebGLAnimation() {
  10829. var context = null;
  10830. var isAnimating = false;
  10831. var animationLoop = null;
  10832. function onAnimationFrame(time, frame) {
  10833. if (isAnimating === false) return;
  10834. animationLoop(time, frame);
  10835. context.requestAnimationFrame(onAnimationFrame);
  10836. }
  10837. return {
  10838. start: function () {
  10839. if (isAnimating === true) return;
  10840. if (animationLoop === null) return;
  10841. context.requestAnimationFrame(onAnimationFrame);
  10842. isAnimating = true;
  10843. },
  10844. stop: function () {
  10845. isAnimating = false;
  10846. },
  10847. setAnimationLoop: function (callback) {
  10848. animationLoop = callback;
  10849. },
  10850. setContext: function (value) {
  10851. context = value;
  10852. }
  10853. };
  10854. }
  10855. /**
  10856. * @author mrdoob / http://mrdoob.com/
  10857. */
  10858. function WebGLAttributes(gl) {
  10859. var buffers = new WeakMap();
  10860. function createBuffer(attribute, bufferType) {
  10861. var array = attribute.array;
  10862. var usage = attribute.dynamic ? 35048 : 35044;
  10863. var buffer = gl.createBuffer();
  10864. gl.bindBuffer(bufferType, buffer);
  10865. gl.bufferData(bufferType, array, usage);
  10866. attribute.onUploadCallback();
  10867. var type = 5126;
  10868. if (array instanceof Float32Array) {
  10869. type = 5126;
  10870. } else if (array instanceof Float64Array) {
  10871. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  10872. } else if (array instanceof Uint16Array) {
  10873. type = 5123;
  10874. } else if (array instanceof Int16Array) {
  10875. type = 5122;
  10876. } else if (array instanceof Uint32Array) {
  10877. type = 5125;
  10878. } else if (array instanceof Int32Array) {
  10879. type = 5124;
  10880. } else if (array instanceof Int8Array) {
  10881. type = 5120;
  10882. } else if (array instanceof Uint8Array) {
  10883. type = 5121;
  10884. }
  10885. return {
  10886. buffer: buffer,
  10887. type: type,
  10888. bytesPerElement: array.BYTES_PER_ELEMENT,
  10889. version: attribute.version
  10890. };
  10891. }
  10892. function updateBuffer(buffer, attribute, bufferType) {
  10893. var array = attribute.array;
  10894. var updateRange = attribute.updateRange;
  10895. gl.bindBuffer(bufferType, buffer);
  10896. if (attribute.dynamic === false) {
  10897. gl.bufferData(bufferType, array, 35044);
  10898. } else if (updateRange.count === -1) {
  10899. // Not using update ranges
  10900. gl.bufferSubData(bufferType, 0, array);
  10901. } else if (updateRange.count === 0) {
  10902. 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.');
  10903. } else {
  10904. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  10905. updateRange.count = -1; // reset range
  10906. }
  10907. } //
  10908. function get(attribute) {
  10909. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10910. return buffers.get(attribute);
  10911. }
  10912. function remove(attribute) {
  10913. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10914. var data = buffers.get(attribute);
  10915. if (data) {
  10916. gl.deleteBuffer(data.buffer);
  10917. buffers.delete(attribute);
  10918. }
  10919. }
  10920. function update(attribute, bufferType) {
  10921. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  10922. var data = buffers.get(attribute);
  10923. if (data === undefined) {
  10924. buffers.set(attribute, createBuffer(attribute, bufferType));
  10925. } else if (data.version < attribute.version) {
  10926. updateBuffer(data.buffer, attribute, bufferType);
  10927. data.version = attribute.version;
  10928. }
  10929. }
  10930. return {
  10931. get: get,
  10932. remove: remove,
  10933. update: update
  10934. };
  10935. }
  10936. /**
  10937. * @author mrdoob / http://mrdoob.com/
  10938. * @author Mugen87 / https://github.com/Mugen87
  10939. */
  10940. // PlaneGeometry
  10941. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  10942. Geometry.call(this);
  10943. this.type = 'PlaneGeometry';
  10944. this.parameters = {
  10945. width: width,
  10946. height: height,
  10947. widthSegments: widthSegments,
  10948. heightSegments: heightSegments
  10949. };
  10950. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  10951. this.mergeVertices();
  10952. }
  10953. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  10954. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  10955. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  10956. BufferGeometry.call(this);
  10957. this.type = 'PlaneBufferGeometry';
  10958. this.parameters = {
  10959. width: width,
  10960. height: height,
  10961. widthSegments: widthSegments,
  10962. heightSegments: heightSegments
  10963. };
  10964. width = width || 1;
  10965. height = height || 1;
  10966. var width_half = width / 2;
  10967. var height_half = height / 2;
  10968. var gridX = Math.floor(widthSegments) || 1;
  10969. var gridY = Math.floor(heightSegments) || 1;
  10970. var gridX1 = gridX + 1;
  10971. var gridY1 = gridY + 1;
  10972. var segment_width = width / gridX;
  10973. var segment_height = height / gridY;
  10974. var ix, iy; // buffers
  10975. var indices = [];
  10976. var vertices = [];
  10977. var normals = [];
  10978. var uvs = []; // generate vertices, normals and uvs
  10979. for (iy = 0; iy < gridY1; iy++) {
  10980. var y = iy * segment_height - height_half;
  10981. for (ix = 0; ix < gridX1; ix++) {
  10982. var x = ix * segment_width - width_half;
  10983. vertices.push(x, -y, 0);
  10984. normals.push(0, 0, 1);
  10985. uvs.push(ix / gridX);
  10986. uvs.push(1 - iy / gridY);
  10987. }
  10988. } // indices
  10989. for (iy = 0; iy < gridY; iy++) {
  10990. for (ix = 0; ix < gridX; ix++) {
  10991. var a = ix + gridX1 * iy;
  10992. var b = ix + gridX1 * (iy + 1);
  10993. var c = ix + 1 + gridX1 * (iy + 1);
  10994. var d = ix + 1 + gridX1 * iy; // faces
  10995. indices.push(a, b, d);
  10996. indices.push(b, c, d);
  10997. }
  10998. } // build geometry
  10999. this.setIndex(indices);
  11000. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  11001. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  11002. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  11003. }
  11004. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  11005. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11006. /**
  11007. * @author mrdoob / http://mrdoob.com/
  11008. */
  11009. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  11010. var clearColor = new Color(0x000000);
  11011. var clearAlpha = 0;
  11012. var planeMesh;
  11013. var boxMesh; // Store the current background texture and its `version`
  11014. // so we can recompile the material accordingly.
  11015. var currentBackground = null;
  11016. var currentBackgroundVersion = 0;
  11017. function render(renderList, scene, camera, forceClear) {
  11018. var background = scene.background; // Ignore background in AR
  11019. // TODO: Reconsider this.
  11020. var vr = renderer.vr;
  11021. var session = vr.getSession && vr.getSession();
  11022. if (session && session.environmentBlendMode === 'additive') {
  11023. background = null;
  11024. }
  11025. if (background === null) {
  11026. setClear(clearColor, clearAlpha);
  11027. currentBackground = null;
  11028. currentBackgroundVersion = 0;
  11029. } else if (background && background.isColor) {
  11030. setClear(background, 1);
  11031. forceClear = true;
  11032. currentBackground = null;
  11033. currentBackgroundVersion = 0;
  11034. }
  11035. if (renderer.autoClear || forceClear) {
  11036. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  11037. }
  11038. if (background && (background.isCubeTexture || background.isWebGLRenderTargetCube)) {
  11039. if (boxMesh === undefined) {
  11040. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  11041. type: 'BackgroundCubeMaterial',
  11042. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  11043. vertexShader: ShaderLib.cube.vertexShader,
  11044. fragmentShader: ShaderLib.cube.fragmentShader,
  11045. side: BackSide,
  11046. depthTest: false,
  11047. depthWrite: false,
  11048. fog: false
  11049. }));
  11050. boxMesh.geometry.removeAttribute('normal');
  11051. boxMesh.geometry.removeAttribute('uv');
  11052. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  11053. this.matrixWorld.copyPosition(camera.matrixWorld);
  11054. }; // enable code injection for non-built-in material
  11055. Object.defineProperty(boxMesh.material, 'map', {
  11056. get: function () {
  11057. return this.uniforms.tCube.value;
  11058. }
  11059. });
  11060. objects.update(boxMesh);
  11061. }
  11062. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  11063. boxMesh.material.uniforms.tCube.value = texture;
  11064. boxMesh.material.uniforms.tFlip.value = background.isWebGLRenderTargetCube ? 1 : -1;
  11065. if (currentBackground !== background || currentBackgroundVersion !== texture.version) {
  11066. boxMesh.material.needsUpdate = true;
  11067. currentBackground = background;
  11068. currentBackgroundVersion = texture.version;
  11069. } // push to the pre-sorted opaque render list
  11070. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  11071. } else if (background && background.isTexture) {
  11072. if (planeMesh === undefined) {
  11073. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  11074. type: 'BackgroundMaterial',
  11075. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  11076. vertexShader: ShaderLib.background.vertexShader,
  11077. fragmentShader: ShaderLib.background.fragmentShader,
  11078. side: FrontSide,
  11079. depthTest: false,
  11080. depthWrite: false,
  11081. fog: false
  11082. }));
  11083. planeMesh.geometry.removeAttribute('normal'); // enable code injection for non-built-in material
  11084. Object.defineProperty(planeMesh.material, 'map', {
  11085. get: function () {
  11086. return this.uniforms.t2D.value;
  11087. }
  11088. });
  11089. objects.update(planeMesh);
  11090. }
  11091. planeMesh.material.uniforms.t2D.value = background;
  11092. if (background.matrixAutoUpdate === true) {
  11093. background.updateMatrix();
  11094. }
  11095. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  11096. if (currentBackground !== background || currentBackgroundVersion !== background.version) {
  11097. planeMesh.material.needsUpdate = true;
  11098. currentBackground = background;
  11099. currentBackgroundVersion = background.version;
  11100. } // push to the pre-sorted opaque render list
  11101. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  11102. }
  11103. }
  11104. function setClear(color, alpha) {
  11105. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  11106. }
  11107. return {
  11108. getClearColor: function () {
  11109. return clearColor;
  11110. },
  11111. setClearColor: function (color, alpha) {
  11112. clearColor.set(color);
  11113. clearAlpha = alpha !== undefined ? alpha : 1;
  11114. setClear(clearColor, clearAlpha);
  11115. },
  11116. getClearAlpha: function () {
  11117. return clearAlpha;
  11118. },
  11119. setClearAlpha: function (alpha) {
  11120. clearAlpha = alpha;
  11121. setClear(clearColor, clearAlpha);
  11122. },
  11123. render: render
  11124. };
  11125. }
  11126. /**
  11127. * @author mrdoob / http://mrdoob.com/
  11128. */
  11129. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  11130. var mode;
  11131. function setMode(value) {
  11132. mode = value;
  11133. }
  11134. function render(start, count) {
  11135. gl.drawArrays(mode, start, count);
  11136. info.update(count, mode);
  11137. }
  11138. function renderInstances(geometry, start, count, primcount) {
  11139. if (primcount === 0) return;
  11140. var extension, methodName;
  11141. if (capabilities.isWebGL2) {
  11142. extension = gl;
  11143. methodName = 'drawArraysInstanced';
  11144. } else {
  11145. extension = extensions.get('ANGLE_instanced_arrays');
  11146. methodName = 'drawArraysInstancedANGLE';
  11147. if (extension === null) {
  11148. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11149. return;
  11150. }
  11151. }
  11152. extension[methodName](mode, start, count, primcount);
  11153. info.update(count, mode, primcount);
  11154. } //
  11155. this.setMode = setMode;
  11156. this.render = render;
  11157. this.renderInstances = renderInstances;
  11158. }
  11159. /**
  11160. * @author mrdoob / http://mrdoob.com/
  11161. */
  11162. function WebGLCapabilities(gl, extensions, parameters) {
  11163. var maxAnisotropy;
  11164. function getMaxAnisotropy() {
  11165. if (maxAnisotropy !== undefined) return maxAnisotropy;
  11166. var extension = extensions.get('EXT_texture_filter_anisotropic');
  11167. if (extension !== null) {
  11168. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  11169. } else {
  11170. maxAnisotropy = 0;
  11171. }
  11172. return maxAnisotropy;
  11173. }
  11174. function getMaxPrecision(precision) {
  11175. if (precision === 'highp') {
  11176. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  11177. return 'highp';
  11178. }
  11179. precision = 'mediump';
  11180. }
  11181. if (precision === 'mediump') {
  11182. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  11183. return 'mediump';
  11184. }
  11185. }
  11186. return 'lowp';
  11187. }
  11188. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  11189. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  11190. var maxPrecision = getMaxPrecision(precision);
  11191. if (maxPrecision !== precision) {
  11192. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  11193. precision = maxPrecision;
  11194. }
  11195. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  11196. var maxTextures = gl.getParameter(34930);
  11197. var maxVertexTextures = gl.getParameter(35660);
  11198. var maxTextureSize = gl.getParameter(3379);
  11199. var maxCubemapSize = gl.getParameter(34076);
  11200. var maxAttributes = gl.getParameter(34921);
  11201. var maxVertexUniforms = gl.getParameter(36347);
  11202. var maxVaryings = gl.getParameter(36348);
  11203. var maxFragmentUniforms = gl.getParameter(36349);
  11204. var vertexTextures = maxVertexTextures > 0;
  11205. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  11206. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  11207. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  11208. return {
  11209. isWebGL2: isWebGL2,
  11210. getMaxAnisotropy: getMaxAnisotropy,
  11211. getMaxPrecision: getMaxPrecision,
  11212. precision: precision,
  11213. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11214. maxTextures: maxTextures,
  11215. maxVertexTextures: maxVertexTextures,
  11216. maxTextureSize: maxTextureSize,
  11217. maxCubemapSize: maxCubemapSize,
  11218. maxAttributes: maxAttributes,
  11219. maxVertexUniforms: maxVertexUniforms,
  11220. maxVaryings: maxVaryings,
  11221. maxFragmentUniforms: maxFragmentUniforms,
  11222. vertexTextures: vertexTextures,
  11223. floatFragmentTextures: floatFragmentTextures,
  11224. floatVertexTextures: floatVertexTextures,
  11225. maxSamples: maxSamples
  11226. };
  11227. }
  11228. /**
  11229. * @author tschw
  11230. */
  11231. function WebGLClipping() {
  11232. var scope = this,
  11233. globalState = null,
  11234. numGlobalPlanes = 0,
  11235. localClippingEnabled = false,
  11236. renderingShadows = false,
  11237. plane = new Plane(),
  11238. viewNormalMatrix = new Matrix3(),
  11239. uniform = {
  11240. value: null,
  11241. needsUpdate: false
  11242. };
  11243. this.uniform = uniform;
  11244. this.numPlanes = 0;
  11245. this.numIntersection = 0;
  11246. this.init = function (planes, enableLocalClipping, camera) {
  11247. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  11248. // run another frame in order to reset the state:
  11249. numGlobalPlanes !== 0 || localClippingEnabled;
  11250. localClippingEnabled = enableLocalClipping;
  11251. globalState = projectPlanes(planes, camera, 0);
  11252. numGlobalPlanes = planes.length;
  11253. return enabled;
  11254. };
  11255. this.beginShadows = function () {
  11256. renderingShadows = true;
  11257. projectPlanes(null);
  11258. };
  11259. this.endShadows = function () {
  11260. renderingShadows = false;
  11261. resetGlobalState();
  11262. };
  11263. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  11264. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  11265. // there's no local clipping
  11266. if (renderingShadows) {
  11267. // there's no global clipping
  11268. projectPlanes(null);
  11269. } else {
  11270. resetGlobalState();
  11271. }
  11272. } else {
  11273. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  11274. lGlobal = nGlobal * 4,
  11275. dstArray = cache.clippingState || null;
  11276. uniform.value = dstArray; // ensure unique state
  11277. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  11278. for (var i = 0; i !== lGlobal; ++i) {
  11279. dstArray[i] = globalState[i];
  11280. }
  11281. cache.clippingState = dstArray;
  11282. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  11283. this.numPlanes += nGlobal;
  11284. }
  11285. };
  11286. function resetGlobalState() {
  11287. if (uniform.value !== globalState) {
  11288. uniform.value = globalState;
  11289. uniform.needsUpdate = numGlobalPlanes > 0;
  11290. }
  11291. scope.numPlanes = numGlobalPlanes;
  11292. scope.numIntersection = 0;
  11293. }
  11294. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  11295. var nPlanes = planes !== null ? planes.length : 0,
  11296. dstArray = null;
  11297. if (nPlanes !== 0) {
  11298. dstArray = uniform.value;
  11299. if (skipTransform !== true || dstArray === null) {
  11300. var flatSize = dstOffset + nPlanes * 4,
  11301. viewMatrix = camera.matrixWorldInverse;
  11302. viewNormalMatrix.getNormalMatrix(viewMatrix);
  11303. if (dstArray === null || dstArray.length < flatSize) {
  11304. dstArray = new Float32Array(flatSize);
  11305. }
  11306. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  11307. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  11308. plane.normal.toArray(dstArray, i4);
  11309. dstArray[i4 + 3] = plane.constant;
  11310. }
  11311. }
  11312. uniform.value = dstArray;
  11313. uniform.needsUpdate = true;
  11314. }
  11315. scope.numPlanes = nPlanes;
  11316. return dstArray;
  11317. }
  11318. }
  11319. /**
  11320. * @author mrdoob / http://mrdoob.com/
  11321. */
  11322. function WebGLExtensions(gl) {
  11323. var extensions = {};
  11324. return {
  11325. get: function (name) {
  11326. if (extensions[name] !== undefined) {
  11327. return extensions[name];
  11328. }
  11329. var extension;
  11330. switch (name) {
  11331. case 'WEBGL_depth_texture':
  11332. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  11333. break;
  11334. case 'EXT_texture_filter_anisotropic':
  11335. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  11336. break;
  11337. case 'WEBGL_compressed_texture_s3tc':
  11338. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11339. break;
  11340. case 'WEBGL_compressed_texture_pvrtc':
  11341. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11342. break;
  11343. default:
  11344. extension = gl.getExtension(name);
  11345. }
  11346. if (extension === null) {
  11347. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  11348. }
  11349. extensions[name] = extension;
  11350. return extension;
  11351. }
  11352. };
  11353. }
  11354. /**
  11355. * @author mrdoob / http://mrdoob.com/
  11356. */
  11357. function WebGLGeometries(gl, attributes, info) {
  11358. var geometries = new WeakMap();
  11359. var wireframeAttributes = new WeakMap();
  11360. function onGeometryDispose(event) {
  11361. var geometry = event.target;
  11362. var buffergeometry = geometries.get(geometry);
  11363. if (buffergeometry.index !== null) {
  11364. attributes.remove(buffergeometry.index);
  11365. }
  11366. for (var name in buffergeometry.attributes) {
  11367. attributes.remove(buffergeometry.attributes[name]);
  11368. }
  11369. geometry.removeEventListener('dispose', onGeometryDispose);
  11370. geometries.delete(geometry);
  11371. var attribute = wireframeAttributes.get(buffergeometry);
  11372. if (attribute) {
  11373. attributes.remove(attribute);
  11374. wireframeAttributes.delete(buffergeometry);
  11375. } //
  11376. info.memory.geometries--;
  11377. }
  11378. function get(object, geometry) {
  11379. var buffergeometry = geometries.get(geometry);
  11380. if (buffergeometry) return buffergeometry;
  11381. geometry.addEventListener('dispose', onGeometryDispose);
  11382. if (geometry.isBufferGeometry) {
  11383. buffergeometry = geometry;
  11384. } else if (geometry.isGeometry) {
  11385. if (geometry._bufferGeometry === undefined) {
  11386. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  11387. }
  11388. buffergeometry = geometry._bufferGeometry;
  11389. }
  11390. geometries.set(geometry, buffergeometry);
  11391. info.memory.geometries++;
  11392. return buffergeometry;
  11393. }
  11394. function update(geometry) {
  11395. var index = geometry.index;
  11396. var geometryAttributes = geometry.attributes;
  11397. if (index !== null) {
  11398. attributes.update(index, 34963);
  11399. }
  11400. for (var name in geometryAttributes) {
  11401. attributes.update(geometryAttributes[name], 34962);
  11402. } // morph targets
  11403. var morphAttributes = geometry.morphAttributes;
  11404. for (var name in morphAttributes) {
  11405. var array = morphAttributes[name];
  11406. for (var i = 0, l = array.length; i < l; i++) {
  11407. attributes.update(array[i], 34962);
  11408. }
  11409. }
  11410. }
  11411. function updateWireframeAttribute(geometry) {
  11412. var indices = [];
  11413. var geometryIndex = geometry.index;
  11414. var geometryPosition = geometry.attributes.position;
  11415. var version = 0;
  11416. if (geometryIndex !== null) {
  11417. var array = geometryIndex.array;
  11418. version = geometryIndex.version;
  11419. for (var i = 0, l = array.length; i < l; i += 3) {
  11420. var a = array[i + 0];
  11421. var b = array[i + 1];
  11422. var c = array[i + 2];
  11423. indices.push(a, b, b, c, c, a);
  11424. }
  11425. } else {
  11426. var array = geometryPosition.array;
  11427. version = geometryPosition.version;
  11428. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  11429. var a = i + 0;
  11430. var b = i + 1;
  11431. var c = i + 2;
  11432. indices.push(a, b, b, c, c, a);
  11433. }
  11434. }
  11435. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  11436. attribute.version = version;
  11437. attributes.update(attribute, 34963); //
  11438. var previousAttribute = wireframeAttributes.get(geometry);
  11439. if (previousAttribute) attributes.remove(previousAttribute); //
  11440. wireframeAttributes.set(geometry, attribute);
  11441. }
  11442. function getWireframeAttribute(geometry) {
  11443. var currentAttribute = wireframeAttributes.get(geometry);
  11444. if (currentAttribute) {
  11445. var geometryIndex = geometry.index;
  11446. if (geometryIndex !== null) {
  11447. // if the attribute is obsolete, create a new one
  11448. if (currentAttribute.version < geometryIndex.version) {
  11449. updateWireframeAttribute(geometry);
  11450. }
  11451. }
  11452. } else {
  11453. updateWireframeAttribute(geometry);
  11454. }
  11455. return wireframeAttributes.get(geometry);
  11456. }
  11457. return {
  11458. get: get,
  11459. update: update,
  11460. getWireframeAttribute: getWireframeAttribute
  11461. };
  11462. }
  11463. /**
  11464. * @author mrdoob / http://mrdoob.com/
  11465. */
  11466. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  11467. var mode;
  11468. function setMode(value) {
  11469. mode = value;
  11470. }
  11471. var type, bytesPerElement;
  11472. function setIndex(value) {
  11473. type = value.type;
  11474. bytesPerElement = value.bytesPerElement;
  11475. }
  11476. function render(start, count) {
  11477. gl.drawElements(mode, count, type, start * bytesPerElement);
  11478. info.update(count, mode);
  11479. }
  11480. function renderInstances(geometry, start, count, primcount) {
  11481. if (primcount === 0) return;
  11482. var extension, methodName;
  11483. if (capabilities.isWebGL2) {
  11484. extension = gl;
  11485. methodName = 'drawElementsInstanced';
  11486. } else {
  11487. extension = extensions.get('ANGLE_instanced_arrays');
  11488. methodName = 'drawElementsInstancedANGLE';
  11489. if (extension === null) {
  11490. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  11491. return;
  11492. }
  11493. }
  11494. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  11495. info.update(count, mode, primcount);
  11496. } //
  11497. this.setMode = setMode;
  11498. this.setIndex = setIndex;
  11499. this.render = render;
  11500. this.renderInstances = renderInstances;
  11501. }
  11502. /**
  11503. * @author Mugen87 / https://github.com/Mugen87
  11504. */
  11505. function WebGLInfo(gl) {
  11506. var memory = {
  11507. geometries: 0,
  11508. textures: 0
  11509. };
  11510. var render = {
  11511. frame: 0,
  11512. calls: 0,
  11513. triangles: 0,
  11514. points: 0,
  11515. lines: 0
  11516. };
  11517. function update(count, mode, instanceCount) {
  11518. instanceCount = instanceCount || 1;
  11519. render.calls++;
  11520. switch (mode) {
  11521. case 4:
  11522. render.triangles += instanceCount * (count / 3);
  11523. break;
  11524. case 5:
  11525. case 6:
  11526. render.triangles += instanceCount * (count - 2);
  11527. break;
  11528. case 1:
  11529. render.lines += instanceCount * (count / 2);
  11530. break;
  11531. case 3:
  11532. render.lines += instanceCount * (count - 1);
  11533. break;
  11534. case 2:
  11535. render.lines += instanceCount * count;
  11536. break;
  11537. case 0:
  11538. render.points += instanceCount * count;
  11539. break;
  11540. default:
  11541. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  11542. break;
  11543. }
  11544. }
  11545. function reset() {
  11546. render.frame++;
  11547. render.calls = 0;
  11548. render.triangles = 0;
  11549. render.points = 0;
  11550. render.lines = 0;
  11551. }
  11552. return {
  11553. memory: memory,
  11554. render: render,
  11555. programs: null,
  11556. autoReset: true,
  11557. reset: reset,
  11558. update: update
  11559. };
  11560. }
  11561. /**
  11562. * @author mrdoob / http://mrdoob.com/
  11563. */
  11564. function absNumericalSort(a, b) {
  11565. return Math.abs(b[1]) - Math.abs(a[1]);
  11566. }
  11567. function WebGLMorphtargets(gl) {
  11568. var influencesList = {};
  11569. var morphInfluences = new Float32Array(8);
  11570. function update(object, geometry, material, program) {
  11571. var objectInfluences = object.morphTargetInfluences;
  11572. var length = objectInfluences.length;
  11573. var influences = influencesList[geometry.id];
  11574. if (influences === undefined) {
  11575. // initialise list
  11576. influences = [];
  11577. for (var i = 0; i < length; i++) {
  11578. influences[i] = [i, 0];
  11579. }
  11580. influencesList[geometry.id] = influences;
  11581. }
  11582. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  11583. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  11584. for (var i = 0; i < length; i++) {
  11585. var influence = influences[i];
  11586. if (influence[1] !== 0) {
  11587. if (morphTargets) geometry.removeAttribute('morphTarget' + i);
  11588. if (morphNormals) geometry.removeAttribute('morphNormal' + i);
  11589. }
  11590. } // Collect influences
  11591. for (var i = 0; i < length; i++) {
  11592. var influence = influences[i];
  11593. influence[0] = i;
  11594. influence[1] = objectInfluences[i];
  11595. }
  11596. influences.sort(absNumericalSort); // Add morphAttributes
  11597. for (var i = 0; i < 8; i++) {
  11598. var influence = influences[i];
  11599. if (influence) {
  11600. var index = influence[0];
  11601. var value = influence[1];
  11602. if (value) {
  11603. if (morphTargets) geometry.addAttribute('morphTarget' + i, morphTargets[index]);
  11604. if (morphNormals) geometry.addAttribute('morphNormal' + i, morphNormals[index]);
  11605. morphInfluences[i] = value;
  11606. continue;
  11607. }
  11608. }
  11609. morphInfluences[i] = 0;
  11610. }
  11611. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  11612. }
  11613. return {
  11614. update: update
  11615. };
  11616. }
  11617. /**
  11618. * @author mrdoob / http://mrdoob.com/
  11619. */
  11620. function WebGLObjects(gl, geometries, attributes, info) {
  11621. var updateList = {};
  11622. function update(object) {
  11623. var frame = info.render.frame;
  11624. var geometry = object.geometry;
  11625. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  11626. if (updateList[buffergeometry.id] !== frame) {
  11627. if (geometry.isGeometry) {
  11628. buffergeometry.updateFromObject(object);
  11629. }
  11630. geometries.update(buffergeometry);
  11631. updateList[buffergeometry.id] = frame;
  11632. }
  11633. if (object.isInstancedMesh) {
  11634. attributes.update(object.instanceMatrix, 34962);
  11635. }
  11636. return buffergeometry;
  11637. }
  11638. function dispose() {
  11639. updateList = {};
  11640. }
  11641. return {
  11642. update: update,
  11643. dispose: dispose
  11644. };
  11645. }
  11646. /**
  11647. * @author mrdoob / http://mrdoob.com/
  11648. */
  11649. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  11650. images = images !== undefined ? images : [];
  11651. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  11652. format = format !== undefined ? format : RGBFormat;
  11653. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  11654. this.flipY = false;
  11655. }
  11656. CubeTexture.prototype = Object.create(Texture.prototype);
  11657. CubeTexture.prototype.constructor = CubeTexture;
  11658. CubeTexture.prototype.isCubeTexture = true;
  11659. Object.defineProperty(CubeTexture.prototype, 'images', {
  11660. get: function () {
  11661. return this.image;
  11662. },
  11663. set: function (value) {
  11664. this.image = value;
  11665. }
  11666. });
  11667. /**
  11668. * @author Takahiro https://github.com/takahirox
  11669. */
  11670. function DataTexture2DArray(data, width, height, depth) {
  11671. Texture.call(this, null);
  11672. this.image = {
  11673. data: data || null,
  11674. width: width || 1,
  11675. height: height || 1,
  11676. depth: depth || 1
  11677. };
  11678. this.magFilter = NearestFilter;
  11679. this.minFilter = NearestFilter;
  11680. this.wrapR = ClampToEdgeWrapping;
  11681. this.generateMipmaps = false;
  11682. this.flipY = false;
  11683. this.needsUpdate = true;
  11684. }
  11685. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  11686. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  11687. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  11688. /**
  11689. * @author Artur Trzesiok
  11690. */
  11691. function DataTexture3D(data, width, height, depth) {
  11692. // We're going to add .setXXX() methods for setting properties later.
  11693. // Users can still set in DataTexture3D directly.
  11694. //
  11695. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  11696. // texture.anisotropy = 16;
  11697. //
  11698. // See #14839
  11699. Texture.call(this, null);
  11700. this.image = {
  11701. data: data || null,
  11702. width: width || 1,
  11703. height: height || 1,
  11704. depth: depth || 1
  11705. };
  11706. this.magFilter = NearestFilter;
  11707. this.minFilter = NearestFilter;
  11708. this.wrapR = ClampToEdgeWrapping;
  11709. this.generateMipmaps = false;
  11710. this.flipY = false;
  11711. this.needsUpdate = true;
  11712. }
  11713. DataTexture3D.prototype = Object.create(Texture.prototype);
  11714. DataTexture3D.prototype.constructor = DataTexture3D;
  11715. DataTexture3D.prototype.isDataTexture3D = true;
  11716. /**
  11717. * @author tschw
  11718. * @author Mugen87 / https://github.com/Mugen87
  11719. * @author mrdoob / http://mrdoob.com/
  11720. *
  11721. * Uniforms of a program.
  11722. * Those form a tree structure with a special top-level container for the root,
  11723. * which you get by calling 'new WebGLUniforms( gl, program )'.
  11724. *
  11725. *
  11726. * Properties of inner nodes including the top-level container:
  11727. *
  11728. * .seq - array of nested uniforms
  11729. * .map - nested uniforms by name
  11730. *
  11731. *
  11732. * Methods of all nodes except the top-level container:
  11733. *
  11734. * .setValue( gl, value, [textures] )
  11735. *
  11736. * uploads a uniform value(s)
  11737. * the 'textures' parameter is needed for sampler uniforms
  11738. *
  11739. *
  11740. * Static methods of the top-level container (textures factorizations):
  11741. *
  11742. * .upload( gl, seq, values, textures )
  11743. *
  11744. * sets uniforms in 'seq' to 'values[id].value'
  11745. *
  11746. * .seqWithValue( seq, values ) : filteredSeq
  11747. *
  11748. * filters 'seq' entries with corresponding entry in values
  11749. *
  11750. *
  11751. * Methods of the top-level container (textures factorizations):
  11752. *
  11753. * .setValue( gl, name, value, textures )
  11754. *
  11755. * sets uniform with name 'name' to 'value'
  11756. *
  11757. * .setOptional( gl, obj, prop )
  11758. *
  11759. * like .set for an optional property of the object
  11760. *
  11761. */
  11762. var emptyTexture = new Texture();
  11763. var emptyTexture2dArray = new DataTexture2DArray();
  11764. var emptyTexture3d = new DataTexture3D();
  11765. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  11766. // Array Caches (provide typed arrays for temporary by size)
  11767. var arrayCacheF32 = [];
  11768. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  11769. var mat4array = new Float32Array(16);
  11770. var mat3array = new Float32Array(9);
  11771. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  11772. function flatten(array, nBlocks, blockSize) {
  11773. var firstElem = array[0];
  11774. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  11775. // see http://jacksondunstan.com/articles/983
  11776. var n = nBlocks * blockSize,
  11777. r = arrayCacheF32[n];
  11778. if (r === undefined) {
  11779. r = new Float32Array(n);
  11780. arrayCacheF32[n] = r;
  11781. }
  11782. if (nBlocks !== 0) {
  11783. firstElem.toArray(r, 0);
  11784. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  11785. offset += blockSize;
  11786. array[i].toArray(r, offset);
  11787. }
  11788. }
  11789. return r;
  11790. }
  11791. function arraysEqual(a, b) {
  11792. if (a.length !== b.length) return false;
  11793. for (var i = 0, l = a.length; i < l; i++) {
  11794. if (a[i] !== b[i]) return false;
  11795. }
  11796. return true;
  11797. }
  11798. function copyArray(a, b) {
  11799. for (var i = 0, l = b.length; i < l; i++) {
  11800. a[i] = b[i];
  11801. }
  11802. } // Texture unit allocation
  11803. function allocTexUnits(textures, n) {
  11804. var r = arrayCacheI32[n];
  11805. if (r === undefined) {
  11806. r = new Int32Array(n);
  11807. arrayCacheI32[n] = r;
  11808. }
  11809. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  11810. return r;
  11811. } // --- Setters ---
  11812. // Note: Defining these methods externally, because they come in a bunch
  11813. // and this way their names minify.
  11814. // Single scalar
  11815. function setValueV1f(gl, v) {
  11816. var cache = this.cache;
  11817. if (cache[0] === v) return;
  11818. gl.uniform1f(this.addr, v);
  11819. cache[0] = v;
  11820. } // Single float vector (from flat array or THREE.VectorN)
  11821. function setValueV2f(gl, v) {
  11822. var cache = this.cache;
  11823. if (v.x !== undefined) {
  11824. if (cache[0] !== v.x || cache[1] !== v.y) {
  11825. gl.uniform2f(this.addr, v.x, v.y);
  11826. cache[0] = v.x;
  11827. cache[1] = v.y;
  11828. }
  11829. } else {
  11830. if (arraysEqual(cache, v)) return;
  11831. gl.uniform2fv(this.addr, v);
  11832. copyArray(cache, v);
  11833. }
  11834. }
  11835. function setValueV3f(gl, v) {
  11836. var cache = this.cache;
  11837. if (v.x !== undefined) {
  11838. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  11839. gl.uniform3f(this.addr, v.x, v.y, v.z);
  11840. cache[0] = v.x;
  11841. cache[1] = v.y;
  11842. cache[2] = v.z;
  11843. }
  11844. } else if (v.r !== undefined) {
  11845. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  11846. gl.uniform3f(this.addr, v.r, v.g, v.b);
  11847. cache[0] = v.r;
  11848. cache[1] = v.g;
  11849. cache[2] = v.b;
  11850. }
  11851. } else {
  11852. if (arraysEqual(cache, v)) return;
  11853. gl.uniform3fv(this.addr, v);
  11854. copyArray(cache, v);
  11855. }
  11856. }
  11857. function setValueV4f(gl, v) {
  11858. var cache = this.cache;
  11859. if (v.x !== undefined) {
  11860. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  11861. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  11862. cache[0] = v.x;
  11863. cache[1] = v.y;
  11864. cache[2] = v.z;
  11865. cache[3] = v.w;
  11866. }
  11867. } else {
  11868. if (arraysEqual(cache, v)) return;
  11869. gl.uniform4fv(this.addr, v);
  11870. copyArray(cache, v);
  11871. }
  11872. } // Single matrix (from flat array or MatrixN)
  11873. function setValueM2(gl, v) {
  11874. var cache = this.cache;
  11875. var elements = v.elements;
  11876. if (elements === undefined) {
  11877. if (arraysEqual(cache, v)) return;
  11878. gl.uniformMatrix2fv(this.addr, false, v);
  11879. copyArray(cache, v);
  11880. } else {
  11881. if (arraysEqual(cache, elements)) return;
  11882. mat2array.set(elements);
  11883. gl.uniformMatrix2fv(this.addr, false, mat2array);
  11884. copyArray(cache, elements);
  11885. }
  11886. }
  11887. function setValueM3(gl, v) {
  11888. var cache = this.cache;
  11889. var elements = v.elements;
  11890. if (elements === undefined) {
  11891. if (arraysEqual(cache, v)) return;
  11892. gl.uniformMatrix3fv(this.addr, false, v);
  11893. copyArray(cache, v);
  11894. } else {
  11895. if (arraysEqual(cache, elements)) return;
  11896. mat3array.set(elements);
  11897. gl.uniformMatrix3fv(this.addr, false, mat3array);
  11898. copyArray(cache, elements);
  11899. }
  11900. }
  11901. function setValueM4(gl, v) {
  11902. var cache = this.cache;
  11903. var elements = v.elements;
  11904. if (elements === undefined) {
  11905. if (arraysEqual(cache, v)) return;
  11906. gl.uniformMatrix4fv(this.addr, false, v);
  11907. copyArray(cache, v);
  11908. } else {
  11909. if (arraysEqual(cache, elements)) return;
  11910. mat4array.set(elements);
  11911. gl.uniformMatrix4fv(this.addr, false, mat4array);
  11912. copyArray(cache, elements);
  11913. }
  11914. } // Single texture (2D / Cube)
  11915. function setValueT1(gl, v, textures) {
  11916. var cache = this.cache;
  11917. var unit = textures.allocateTextureUnit();
  11918. if (cache[0] !== unit) {
  11919. gl.uniform1i(this.addr, unit);
  11920. cache[0] = unit;
  11921. }
  11922. textures.safeSetTexture2D(v || emptyTexture, unit);
  11923. }
  11924. function setValueT2DArray1(gl, v, textures) {
  11925. var cache = this.cache;
  11926. var unit = textures.allocateTextureUnit();
  11927. if (cache[0] !== unit) {
  11928. gl.uniform1i(this.addr, unit);
  11929. cache[0] = unit;
  11930. }
  11931. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  11932. }
  11933. function setValueT3D1(gl, v, textures) {
  11934. var cache = this.cache;
  11935. var unit = textures.allocateTextureUnit();
  11936. if (cache[0] !== unit) {
  11937. gl.uniform1i(this.addr, unit);
  11938. cache[0] = unit;
  11939. }
  11940. textures.setTexture3D(v || emptyTexture3d, unit);
  11941. }
  11942. function setValueT6(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.safeSetTextureCube(v || emptyCubeTexture, unit);
  11950. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11951. function setValueV1i(gl, v) {
  11952. var cache = this.cache;
  11953. if (cache[0] === v) return;
  11954. gl.uniform1i(this.addr, v);
  11955. cache[0] = v;
  11956. }
  11957. function setValueV2i(gl, v) {
  11958. var cache = this.cache;
  11959. if (arraysEqual(cache, v)) return;
  11960. gl.uniform2iv(this.addr, v);
  11961. copyArray(cache, v);
  11962. }
  11963. function setValueV3i(gl, v) {
  11964. var cache = this.cache;
  11965. if (arraysEqual(cache, v)) return;
  11966. gl.uniform3iv(this.addr, v);
  11967. copyArray(cache, v);
  11968. }
  11969. function setValueV4i(gl, v) {
  11970. var cache = this.cache;
  11971. if (arraysEqual(cache, v)) return;
  11972. gl.uniform4iv(this.addr, v);
  11973. copyArray(cache, v);
  11974. } // Helper to pick the right setter for the singular case
  11975. function getSingularSetter(type) {
  11976. switch (type) {
  11977. case 0x1406:
  11978. return setValueV1f;
  11979. // FLOAT
  11980. case 0x8b50:
  11981. return setValueV2f;
  11982. // _VEC2
  11983. case 0x8b51:
  11984. return setValueV3f;
  11985. // _VEC3
  11986. case 0x8b52:
  11987. return setValueV4f;
  11988. // _VEC4
  11989. case 0x8b5a:
  11990. return setValueM2;
  11991. // _MAT2
  11992. case 0x8b5b:
  11993. return setValueM3;
  11994. // _MAT3
  11995. case 0x8b5c:
  11996. return setValueM4;
  11997. // _MAT4
  11998. case 0x8b5e:
  11999. case 0x8d66:
  12000. return setValueT1;
  12001. // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  12002. case 0x8b5f:
  12003. return setValueT3D1;
  12004. // SAMPLER_3D
  12005. case 0x8b60:
  12006. return setValueT6;
  12007. // SAMPLER_CUBE
  12008. case 0x8DC1:
  12009. return setValueT2DArray1;
  12010. // SAMPLER_2D_ARRAY
  12011. case 0x1404:
  12012. case 0x8b56:
  12013. return setValueV1i;
  12014. // INT, BOOL
  12015. case 0x8b53:
  12016. case 0x8b57:
  12017. return setValueV2i;
  12018. // _VEC2
  12019. case 0x8b54:
  12020. case 0x8b58:
  12021. return setValueV3i;
  12022. // _VEC3
  12023. case 0x8b55:
  12024. case 0x8b59:
  12025. return setValueV4i;
  12026. // _VEC4
  12027. }
  12028. } // Array of scalars
  12029. function setValueV1fArray(gl, v) {
  12030. gl.uniform1fv(this.addr, v);
  12031. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  12032. function setValueV1iArray(gl, v) {
  12033. gl.uniform1iv(this.addr, v);
  12034. }
  12035. function setValueV2iArray(gl, v) {
  12036. gl.uniform2iv(this.addr, v);
  12037. }
  12038. function setValueV3iArray(gl, v) {
  12039. gl.uniform3iv(this.addr, v);
  12040. }
  12041. function setValueV4iArray(gl, v) {
  12042. gl.uniform4iv(this.addr, v);
  12043. } // Array of vectors (flat or from THREE classes)
  12044. function setValueV2fArray(gl, v) {
  12045. var data = flatten(v, this.size, 2);
  12046. gl.uniform2fv(this.addr, data);
  12047. }
  12048. function setValueV3fArray(gl, v) {
  12049. var data = flatten(v, this.size, 3);
  12050. gl.uniform3fv(this.addr, data);
  12051. }
  12052. function setValueV4fArray(gl, v) {
  12053. var data = flatten(v, this.size, 4);
  12054. gl.uniform4fv(this.addr, data);
  12055. } // Array of matrices (flat or from THREE clases)
  12056. function setValueM2Array(gl, v) {
  12057. var data = flatten(v, this.size, 4);
  12058. gl.uniformMatrix2fv(this.addr, false, data);
  12059. }
  12060. function setValueM3Array(gl, v) {
  12061. var data = flatten(v, this.size, 9);
  12062. gl.uniformMatrix3fv(this.addr, false, data);
  12063. }
  12064. function setValueM4Array(gl, v) {
  12065. var data = flatten(v, this.size, 16);
  12066. gl.uniformMatrix4fv(this.addr, false, data);
  12067. } // Array of textures (2D / Cube)
  12068. function setValueT1Array(gl, v, textures) {
  12069. var n = v.length;
  12070. var units = allocTexUnits(textures, n);
  12071. gl.uniform1iv(this.addr, units);
  12072. for (var i = 0; i !== n; ++i) {
  12073. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  12074. }
  12075. }
  12076. function setValueT6Array(gl, v, textures) {
  12077. var n = v.length;
  12078. var units = allocTexUnits(textures, n);
  12079. gl.uniform1iv(this.addr, units);
  12080. for (var i = 0; i !== n; ++i) {
  12081. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  12082. }
  12083. } // Helper to pick the right setter for a pure (bottom-level) array
  12084. function getPureArraySetter(type) {
  12085. switch (type) {
  12086. case 0x1406:
  12087. return setValueV1fArray;
  12088. // FLOAT
  12089. case 0x8b50:
  12090. return setValueV2fArray;
  12091. // _VEC2
  12092. case 0x8b51:
  12093. return setValueV3fArray;
  12094. // _VEC3
  12095. case 0x8b52:
  12096. return setValueV4fArray;
  12097. // _VEC4
  12098. case 0x8b5a:
  12099. return setValueM2Array;
  12100. // _MAT2
  12101. case 0x8b5b:
  12102. return setValueM3Array;
  12103. // _MAT3
  12104. case 0x8b5c:
  12105. return setValueM4Array;
  12106. // _MAT4
  12107. case 0x8b5e:
  12108. return setValueT1Array;
  12109. // SAMPLER_2D
  12110. case 0x8b60:
  12111. return setValueT6Array;
  12112. // SAMPLER_CUBE
  12113. case 0x1404:
  12114. case 0x8b56:
  12115. return setValueV1iArray;
  12116. // INT, BOOL
  12117. case 0x8b53:
  12118. case 0x8b57:
  12119. return setValueV2iArray;
  12120. // _VEC2
  12121. case 0x8b54:
  12122. case 0x8b58:
  12123. return setValueV3iArray;
  12124. // _VEC3
  12125. case 0x8b55:
  12126. case 0x8b59:
  12127. return setValueV4iArray;
  12128. // _VEC4
  12129. }
  12130. } // --- Uniform Classes ---
  12131. function SingleUniform(id, activeInfo, addr) {
  12132. this.id = id;
  12133. this.addr = addr;
  12134. this.cache = [];
  12135. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12136. }
  12137. function PureArrayUniform(id, activeInfo, addr) {
  12138. this.id = id;
  12139. this.addr = addr;
  12140. this.cache = [];
  12141. this.size = activeInfo.size;
  12142. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  12143. }
  12144. PureArrayUniform.prototype.updateCache = function (data) {
  12145. var cache = this.cache;
  12146. if (data instanceof Float32Array && cache.length !== data.length) {
  12147. this.cache = new Float32Array(data.length);
  12148. }
  12149. copyArray(cache, data);
  12150. };
  12151. function StructuredUniform(id) {
  12152. this.id = id;
  12153. this.seq = [];
  12154. this.map = {};
  12155. }
  12156. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  12157. var seq = this.seq;
  12158. for (var i = 0, n = seq.length; i !== n; ++i) {
  12159. var u = seq[i];
  12160. u.setValue(gl, value[u.id], textures);
  12161. }
  12162. }; // --- Top-level ---
  12163. // Parser - builds up the property tree from the path strings
  12164. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  12165. // - the identifier (member name or array index)
  12166. // - followed by an optional right bracket (found when array index)
  12167. // - followed by an optional left bracket or dot (type of subscript)
  12168. //
  12169. // Note: These portions can be read in a non-overlapping fashion and
  12170. // allow straightforward parsing of the hierarchy that WebGL encodes
  12171. // in the uniform names.
  12172. function addUniform(container, uniformObject) {
  12173. container.seq.push(uniformObject);
  12174. container.map[uniformObject.id] = uniformObject;
  12175. }
  12176. function parseUniform(activeInfo, addr, container) {
  12177. var path = activeInfo.name,
  12178. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  12179. RePathPart.lastIndex = 0;
  12180. while (true) {
  12181. var match = RePathPart.exec(path),
  12182. matchEnd = RePathPart.lastIndex,
  12183. id = match[1],
  12184. idIsIndex = match[2] === ']',
  12185. subscript = match[3];
  12186. if (idIsIndex) id = id | 0; // convert to integer
  12187. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  12188. // bare name or "pure" bottom-level array "[0]" suffix
  12189. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  12190. break;
  12191. } else {
  12192. // step into inner node / create it in case it doesn't exist
  12193. var map = container.map,
  12194. next = map[id];
  12195. if (next === undefined) {
  12196. next = new StructuredUniform(id);
  12197. addUniform(container, next);
  12198. }
  12199. container = next;
  12200. }
  12201. }
  12202. } // Root Container
  12203. function WebGLUniforms(gl, program) {
  12204. this.seq = [];
  12205. this.map = {};
  12206. var n = gl.getProgramParameter(program, 35718);
  12207. for (var i = 0; i < n; ++i) {
  12208. var info = gl.getActiveUniform(program, i),
  12209. addr = gl.getUniformLocation(program, info.name);
  12210. parseUniform(info, addr, this);
  12211. }
  12212. }
  12213. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  12214. var u = this.map[name];
  12215. if (u !== undefined) u.setValue(gl, value, textures);
  12216. };
  12217. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  12218. var v = object[name];
  12219. if (v !== undefined) this.setValue(gl, name, v);
  12220. }; // Static interface
  12221. WebGLUniforms.upload = function (gl, seq, values, textures) {
  12222. for (var i = 0, n = seq.length; i !== n; ++i) {
  12223. var u = seq[i],
  12224. v = values[u.id];
  12225. if (v.needsUpdate !== false) {
  12226. // note: always updating when .needsUpdate is undefined
  12227. u.setValue(gl, v.value, textures);
  12228. }
  12229. }
  12230. };
  12231. WebGLUniforms.seqWithValue = function (seq, values) {
  12232. var r = [];
  12233. for (var i = 0, n = seq.length; i !== n; ++i) {
  12234. var u = seq[i];
  12235. if (u.id in values) r.push(u);
  12236. }
  12237. return r;
  12238. };
  12239. /**
  12240. * @author mrdoob / http://mrdoob.com/
  12241. */
  12242. function WebGLShader(gl, type, string) {
  12243. var shader = gl.createShader(type);
  12244. gl.shaderSource(shader, string);
  12245. gl.compileShader(shader);
  12246. return shader;
  12247. }
  12248. /**
  12249. * @author mrdoob / http://mrdoob.com/
  12250. */
  12251. var programIdCount = 0;
  12252. function addLineNumbers(string) {
  12253. var lines = string.split('\n');
  12254. for (var i = 0; i < lines.length; i++) {
  12255. lines[i] = i + 1 + ': ' + lines[i];
  12256. }
  12257. return lines.join('\n');
  12258. }
  12259. function getEncodingComponents(encoding) {
  12260. switch (encoding) {
  12261. case LinearEncoding:
  12262. return ['Linear', '( value )'];
  12263. case sRGBEncoding:
  12264. return ['sRGB', '( value )'];
  12265. case RGBEEncoding:
  12266. return ['RGBE', '( value )'];
  12267. case RGBM7Encoding:
  12268. return ['RGBM', '( value, 7.0 )'];
  12269. case RGBM16Encoding:
  12270. return ['RGBM', '( value, 16.0 )'];
  12271. case RGBDEncoding:
  12272. return ['RGBD', '( value, 256.0 )'];
  12273. case GammaEncoding:
  12274. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  12275. case LogLuvEncoding:
  12276. return ['LogLuv', '( value )'];
  12277. default:
  12278. throw new Error('unsupported encoding: ' + encoding);
  12279. }
  12280. }
  12281. function getShaderErrors(gl, shader, type) {
  12282. var status = gl.getShaderParameter(shader, 35713);
  12283. var log = gl.getShaderInfoLog(shader).trim();
  12284. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  12285. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  12286. var source = gl.getShaderSource(shader);
  12287. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  12288. }
  12289. function getTexelDecodingFunction(functionName, encoding) {
  12290. var components = getEncodingComponents(encoding);
  12291. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  12292. }
  12293. function getTexelEncodingFunction(functionName, encoding) {
  12294. var components = getEncodingComponents(encoding);
  12295. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  12296. }
  12297. function getToneMappingFunction(functionName, toneMapping) {
  12298. var toneMappingName;
  12299. switch (toneMapping) {
  12300. case LinearToneMapping:
  12301. toneMappingName = 'Linear';
  12302. break;
  12303. case ReinhardToneMapping:
  12304. toneMappingName = 'Reinhard';
  12305. break;
  12306. case Uncharted2ToneMapping:
  12307. toneMappingName = 'Uncharted2';
  12308. break;
  12309. case CineonToneMapping:
  12310. toneMappingName = 'OptimizedCineon';
  12311. break;
  12312. case ACESFilmicToneMapping:
  12313. toneMappingName = 'ACESFilmic';
  12314. break;
  12315. default:
  12316. throw new Error('unsupported toneMapping: ' + toneMapping);
  12317. }
  12318. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  12319. }
  12320. function generateExtensions(extensions, parameters, rendererExtensions) {
  12321. extensions = extensions || {};
  12322. 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' : ''];
  12323. return chunks.filter(filterEmptyLine).join('\n');
  12324. }
  12325. function generateDefines(defines) {
  12326. var chunks = [];
  12327. for (var name in defines) {
  12328. var value = defines[name];
  12329. if (value === false) continue;
  12330. chunks.push('#define ' + name + ' ' + value);
  12331. }
  12332. return chunks.join('\n');
  12333. }
  12334. function fetchAttributeLocations(gl, program) {
  12335. var attributes = {};
  12336. var n = gl.getProgramParameter(program, 35721);
  12337. for (var i = 0; i < n; i++) {
  12338. var info = gl.getActiveAttrib(program, i);
  12339. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  12340. attributes[name] = gl.getAttribLocation(program, name);
  12341. }
  12342. return attributes;
  12343. }
  12344. function filterEmptyLine(string) {
  12345. return string !== '';
  12346. }
  12347. function replaceLightNums(string, parameters) {
  12348. 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);
  12349. }
  12350. function replaceClippingPlaneNums(string, parameters) {
  12351. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  12352. } // Resolve Includes
  12353. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  12354. function resolveIncludes(string) {
  12355. return string.replace(includePattern, includeReplacer);
  12356. }
  12357. function includeReplacer(match, include) {
  12358. var string = ShaderChunk[include];
  12359. if (string === undefined) {
  12360. throw new Error('Can not resolve #include <' + include + '>');
  12361. }
  12362. return resolveIncludes(string);
  12363. } // Unroll Loops
  12364. var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  12365. function unrollLoops(string) {
  12366. return string.replace(loopPattern, loopReplacer);
  12367. }
  12368. function loopReplacer(match, start, end, snippet) {
  12369. var string = '';
  12370. for (var i = parseInt(start); i < parseInt(end); i++) {
  12371. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  12372. }
  12373. return string;
  12374. } //
  12375. function generatePrecision(parameters) {
  12376. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  12377. if (parameters.precision === "highp") {
  12378. precisionstring += "\n#define HIGH_PRECISION";
  12379. } else if (parameters.precision === "mediump") {
  12380. precisionstring += "\n#define MEDIUM_PRECISION";
  12381. } else if (parameters.precision === "lowp") {
  12382. precisionstring += "\n#define LOW_PRECISION";
  12383. }
  12384. return precisionstring;
  12385. }
  12386. function generateShadowMapTypeDefine(parameters) {
  12387. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  12388. if (parameters.shadowMapType === PCFShadowMap) {
  12389. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  12390. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  12391. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  12392. } else if (parameters.shadowMapType === VSMShadowMap) {
  12393. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  12394. }
  12395. return shadowMapTypeDefine;
  12396. }
  12397. function generateEnvMapTypeDefine(parameters, material) {
  12398. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12399. if (parameters.envMap) {
  12400. switch (material.envMap.mapping) {
  12401. case CubeReflectionMapping:
  12402. case CubeRefractionMapping:
  12403. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12404. break;
  12405. case CubeUVReflectionMapping:
  12406. case CubeUVRefractionMapping:
  12407. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  12408. break;
  12409. case EquirectangularReflectionMapping:
  12410. case EquirectangularRefractionMapping:
  12411. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  12412. break;
  12413. case SphericalReflectionMapping:
  12414. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  12415. break;
  12416. }
  12417. }
  12418. return envMapTypeDefine;
  12419. }
  12420. function generateEnvMapModeDefine(parameters, material) {
  12421. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  12422. if (parameters.envMap) {
  12423. switch (material.envMap.mapping) {
  12424. case CubeRefractionMapping:
  12425. case EquirectangularRefractionMapping:
  12426. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  12427. break;
  12428. }
  12429. }
  12430. return envMapModeDefine;
  12431. }
  12432. function generateEnvMapBlendingDefine(parameters, material) {
  12433. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12434. if (parameters.envMap) {
  12435. switch (material.combine) {
  12436. case MultiplyOperation:
  12437. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12438. break;
  12439. case MixOperation:
  12440. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  12441. break;
  12442. case AddOperation:
  12443. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  12444. break;
  12445. }
  12446. }
  12447. return envMapBlendingDefine;
  12448. }
  12449. function WebGLProgram(renderer, extensions, code, material, shader, parameters) {
  12450. var gl = renderer.getContext();
  12451. var defines = material.defines;
  12452. var vertexShader = shader.vertexShader;
  12453. var fragmentShader = shader.fragmentShader;
  12454. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  12455. var envMapTypeDefine = generateEnvMapTypeDefine(parameters, material);
  12456. var envMapModeDefine = generateEnvMapModeDefine(parameters, material);
  12457. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters, material);
  12458. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  12459. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(material.extensions, parameters, extensions);
  12460. var customDefines = generateDefines(defines);
  12461. var program = gl.createProgram();
  12462. var prefixVertex, prefixFragment;
  12463. var renderTarget = renderer.getRenderTarget();
  12464. var numMultiviewViews = renderTarget && renderTarget.isWebGLMultiviewRenderTarget ? renderTarget.numViews : 0;
  12465. if (material.isRawShaderMaterial) {
  12466. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  12467. if (prefixVertex.length > 0) {
  12468. prefixVertex += '\n';
  12469. }
  12470. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  12471. if (prefixFragment.length > 0) {
  12472. prefixFragment += '\n';
  12473. }
  12474. } else {
  12475. 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');
  12476. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + shader.name, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  12477. '#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
  12478. 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
  12479. 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');
  12480. }
  12481. vertexShader = resolveIncludes(vertexShader);
  12482. vertexShader = replaceLightNums(vertexShader, parameters);
  12483. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  12484. fragmentShader = resolveIncludes(fragmentShader);
  12485. fragmentShader = replaceLightNums(fragmentShader, parameters);
  12486. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  12487. vertexShader = unrollLoops(vertexShader);
  12488. fragmentShader = unrollLoops(fragmentShader);
  12489. if (parameters.isWebGL2 && !material.isRawShaderMaterial) {
  12490. var isGLSL3ShaderMaterial = false;
  12491. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  12492. if (material.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  12493. isGLSL3ShaderMaterial = true;
  12494. vertexShader = vertexShader.replace(versionRegex, '');
  12495. fragmentShader = fragmentShader.replace(versionRegex, '');
  12496. } // GLSL 3.0 conversion
  12497. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  12498. 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
  12499. if (numMultiviewViews > 0) {
  12500. 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'));
  12501. 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'));
  12502. prefixFragment = prefixFragment.replace('#version 300 es\n', ['#version 300 es\n', '#extension GL_OVR_multiview2 : require', '#define VIEW_ID gl_ViewID_OVR'].join('\n'));
  12503. prefixFragment = prefixFragment.replace('uniform mat4 viewMatrix;', ['uniform mat4 viewMatrices[' + numMultiviewViews + '];', '#define viewMatrix viewMatrices[VIEW_ID]'].join('\n'));
  12504. }
  12505. }
  12506. var vertexGlsl = prefixVertex + vertexShader;
  12507. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  12508. // console.log( '*FRAGMENT*', fragmentGlsl );
  12509. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  12510. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  12511. gl.attachShader(program, glVertexShader);
  12512. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  12513. if (material.index0AttributeName !== undefined) {
  12514. gl.bindAttribLocation(program, 0, material.index0AttributeName);
  12515. } else if (parameters.morphTargets === true) {
  12516. // programs with morphTargets displace position out of attribute 0
  12517. gl.bindAttribLocation(program, 0, 'position');
  12518. }
  12519. gl.linkProgram(program); // check for link errors
  12520. if (renderer.debug.checkShaderErrors) {
  12521. var programLog = gl.getProgramInfoLog(program).trim();
  12522. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  12523. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  12524. var runnable = true;
  12525. var haveDiagnostics = true;
  12526. if (gl.getProgramParameter(program, 35714) === false) {
  12527. runnable = false;
  12528. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  12529. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  12530. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  12531. } else if (programLog !== '') {
  12532. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  12533. } else if (vertexLog === '' || fragmentLog === '') {
  12534. haveDiagnostics = false;
  12535. }
  12536. if (haveDiagnostics) {
  12537. this.diagnostics = {
  12538. runnable: runnable,
  12539. material: material,
  12540. programLog: programLog,
  12541. vertexShader: {
  12542. log: vertexLog,
  12543. prefix: prefixVertex
  12544. },
  12545. fragmentShader: {
  12546. log: fragmentLog,
  12547. prefix: prefixFragment
  12548. }
  12549. };
  12550. }
  12551. } // clean up
  12552. gl.deleteShader(glVertexShader);
  12553. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  12554. var cachedUniforms;
  12555. this.getUniforms = function () {
  12556. if (cachedUniforms === undefined) {
  12557. cachedUniforms = new WebGLUniforms(gl, program);
  12558. }
  12559. return cachedUniforms;
  12560. }; // set up caching for attribute locations
  12561. var cachedAttributes;
  12562. this.getAttributes = function () {
  12563. if (cachedAttributes === undefined) {
  12564. cachedAttributes = fetchAttributeLocations(gl, program);
  12565. }
  12566. return cachedAttributes;
  12567. }; // free resource
  12568. this.destroy = function () {
  12569. gl.deleteProgram(program);
  12570. this.program = undefined;
  12571. }; //
  12572. this.name = shader.name;
  12573. this.id = programIdCount++;
  12574. this.code = code;
  12575. this.usedTimes = 1;
  12576. this.program = program;
  12577. this.vertexShader = glVertexShader;
  12578. this.fragmentShader = glFragmentShader;
  12579. this.numMultiviewViews = numMultiviewViews;
  12580. return this;
  12581. }
  12582. /**
  12583. * @author mrdoob / http://mrdoob.com/
  12584. */
  12585. function WebGLPrograms(renderer, extensions, capabilities) {
  12586. var programs = [];
  12587. var shaderIDs = {
  12588. MeshDepthMaterial: 'depth',
  12589. MeshDistanceMaterial: 'distanceRGBA',
  12590. MeshNormalMaterial: 'normal',
  12591. MeshBasicMaterial: 'basic',
  12592. MeshLambertMaterial: 'lambert',
  12593. MeshPhongMaterial: 'phong',
  12594. MeshToonMaterial: 'phong',
  12595. MeshStandardMaterial: 'physical',
  12596. MeshPhysicalMaterial: 'physical',
  12597. MeshMatcapMaterial: 'matcap',
  12598. LineBasicMaterial: 'basic',
  12599. LineDashedMaterial: 'dashed',
  12600. PointsMaterial: 'points',
  12601. ShadowMaterial: 'shadow',
  12602. SpriteMaterial: 'sprite'
  12603. };
  12604. 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"];
  12605. function allocateBones(object) {
  12606. var skeleton = object.skeleton;
  12607. var bones = skeleton.bones;
  12608. if (capabilities.floatVertexTextures) {
  12609. return 1024;
  12610. } else {
  12611. // default for when object is not specified
  12612. // ( for example when prebuilding shader to be used with multiple objects )
  12613. //
  12614. // - leave some extra space for other uniforms
  12615. // - limit here is ANGLE's 254 max uniform vectors
  12616. // (up to 54 should be safe)
  12617. var nVertexUniforms = capabilities.maxVertexUniforms;
  12618. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  12619. var maxBones = Math.min(nVertexMatrices, bones.length);
  12620. if (maxBones < bones.length) {
  12621. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  12622. return 0;
  12623. }
  12624. return maxBones;
  12625. }
  12626. }
  12627. function getTextureEncodingFromMap(map, gammaOverrideLinear) {
  12628. var encoding;
  12629. if (!map) {
  12630. encoding = LinearEncoding;
  12631. } else if (map.isTexture) {
  12632. encoding = map.encoding;
  12633. } else if (map.isWebGLRenderTarget) {
  12634. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  12635. encoding = map.texture.encoding;
  12636. } // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  12637. if (encoding === LinearEncoding && gammaOverrideLinear) {
  12638. encoding = GammaEncoding;
  12639. }
  12640. return encoding;
  12641. }
  12642. this.getParameters = function (material, lights, shadows, fog, nClipPlanes, nClipIntersection, object) {
  12643. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  12644. // (not to blow over maxLights budget)
  12645. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  12646. var precision = capabilities.precision;
  12647. if (material.precision !== null) {
  12648. precision = capabilities.getMaxPrecision(material.precision);
  12649. if (precision !== material.precision) {
  12650. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  12651. }
  12652. }
  12653. var currentRenderTarget = renderer.getRenderTarget();
  12654. var parameters = {
  12655. isWebGL2: capabilities.isWebGL2,
  12656. shaderID: shaderID,
  12657. precision: precision,
  12658. instancing: object.isInstancedMesh === true,
  12659. supportsVertexTextures: capabilities.vertexTextures,
  12660. outputEncoding: getTextureEncodingFromMap(!currentRenderTarget ? null : currentRenderTarget.texture, renderer.gammaOutput),
  12661. map: !!material.map,
  12662. mapEncoding: getTextureEncodingFromMap(material.map, renderer.gammaInput),
  12663. matcap: !!material.matcap,
  12664. matcapEncoding: getTextureEncodingFromMap(material.matcap, renderer.gammaInput),
  12665. envMap: !!material.envMap,
  12666. envMapMode: material.envMap && material.envMap.mapping,
  12667. envMapEncoding: getTextureEncodingFromMap(material.envMap, renderer.gammaInput),
  12668. envMapCubeUV: !!material.envMap && (material.envMap.mapping === CubeUVReflectionMapping || material.envMap.mapping === CubeUVRefractionMapping),
  12669. lightMap: !!material.lightMap,
  12670. aoMap: !!material.aoMap,
  12671. emissiveMap: !!material.emissiveMap,
  12672. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap, renderer.gammaInput),
  12673. bumpMap: !!material.bumpMap,
  12674. normalMap: !!material.normalMap,
  12675. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  12676. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  12677. clearcoatNormalMap: !!material.clearcoatNormalMap,
  12678. displacementMap: !!material.displacementMap,
  12679. roughnessMap: !!material.roughnessMap,
  12680. metalnessMap: !!material.metalnessMap,
  12681. specularMap: !!material.specularMap,
  12682. alphaMap: !!material.alphaMap,
  12683. gradientMap: !!material.gradientMap,
  12684. sheen: !!material.sheen,
  12685. combine: material.combine,
  12686. vertexTangents: material.normalMap && material.vertexTangents,
  12687. vertexColors: material.vertexColors,
  12688. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap,
  12689. fog: !!fog,
  12690. useFog: material.fog,
  12691. fogExp2: fog && fog.isFogExp2,
  12692. flatShading: material.flatShading,
  12693. sizeAttenuation: material.sizeAttenuation,
  12694. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  12695. skinning: material.skinning && maxBones > 0,
  12696. maxBones: maxBones,
  12697. useVertexTexture: capabilities.floatVertexTextures,
  12698. morphTargets: material.morphTargets,
  12699. morphNormals: material.morphNormals,
  12700. maxMorphTargets: renderer.maxMorphTargets,
  12701. maxMorphNormals: renderer.maxMorphNormals,
  12702. numDirLights: lights.directional.length,
  12703. numPointLights: lights.point.length,
  12704. numSpotLights: lights.spot.length,
  12705. numRectAreaLights: lights.rectArea.length,
  12706. numHemiLights: lights.hemi.length,
  12707. numDirLightShadows: lights.directionalShadowMap.length,
  12708. numPointLightShadows: lights.pointShadowMap.length,
  12709. numSpotLightShadows: lights.spotShadowMap.length,
  12710. numClippingPlanes: nClipPlanes,
  12711. numClipIntersection: nClipIntersection,
  12712. dithering: material.dithering,
  12713. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12714. shadowMapType: renderer.shadowMap.type,
  12715. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12716. physicallyCorrectLights: renderer.physicallyCorrectLights,
  12717. premultipliedAlpha: material.premultipliedAlpha,
  12718. alphaTest: material.alphaTest,
  12719. doubleSided: material.side === DoubleSide,
  12720. flipSided: material.side === BackSide,
  12721. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false
  12722. };
  12723. return parameters;
  12724. };
  12725. this.getProgramCode = function (material, parameters) {
  12726. var array = [];
  12727. if (parameters.shaderID) {
  12728. array.push(parameters.shaderID);
  12729. } else {
  12730. array.push(material.fragmentShader);
  12731. array.push(material.vertexShader);
  12732. }
  12733. if (material.defines !== undefined) {
  12734. for (var name in material.defines) {
  12735. array.push(name);
  12736. array.push(material.defines[name]);
  12737. }
  12738. }
  12739. for (var i = 0; i < parameterNames.length; i++) {
  12740. array.push(parameters[parameterNames[i]]);
  12741. }
  12742. array.push(material.onBeforeCompile.toString());
  12743. array.push(renderer.gammaOutput);
  12744. array.push(renderer.gammaFactor);
  12745. return array.join();
  12746. };
  12747. this.acquireProgram = function (material, shader, parameters, code) {
  12748. var program; // Check if code has been already compiled
  12749. for (var p = 0, pl = programs.length; p < pl; p++) {
  12750. var programInfo = programs[p];
  12751. if (programInfo.code === code) {
  12752. program = programInfo;
  12753. ++program.usedTimes;
  12754. break;
  12755. }
  12756. }
  12757. if (program === undefined) {
  12758. program = new WebGLProgram(renderer, extensions, code, material, shader, parameters);
  12759. programs.push(program);
  12760. }
  12761. return program;
  12762. };
  12763. this.releaseProgram = function (program) {
  12764. if (--program.usedTimes === 0) {
  12765. // Remove from unordered set
  12766. var i = programs.indexOf(program);
  12767. programs[i] = programs[programs.length - 1];
  12768. programs.pop(); // Free WebGL resources
  12769. program.destroy();
  12770. }
  12771. }; // Exposed for resource monitoring & error feedback via renderer.info:
  12772. this.programs = programs;
  12773. }
  12774. /**
  12775. * @author fordacious / fordacious.github.io
  12776. */
  12777. function WebGLProperties() {
  12778. var properties = new WeakMap();
  12779. function get(object) {
  12780. var map = properties.get(object);
  12781. if (map === undefined) {
  12782. map = {};
  12783. properties.set(object, map);
  12784. }
  12785. return map;
  12786. }
  12787. function remove(object) {
  12788. properties.delete(object);
  12789. }
  12790. function update(object, key, value) {
  12791. properties.get(object)[key] = value;
  12792. }
  12793. function dispose() {
  12794. properties = new WeakMap();
  12795. }
  12796. return {
  12797. get: get,
  12798. remove: remove,
  12799. update: update,
  12800. dispose: dispose
  12801. };
  12802. }
  12803. /**
  12804. * @author mrdoob / http://mrdoob.com/
  12805. */
  12806. function painterSortStable(a, b) {
  12807. if (a.groupOrder !== b.groupOrder) {
  12808. return a.groupOrder - b.groupOrder;
  12809. } else if (a.renderOrder !== b.renderOrder) {
  12810. return a.renderOrder - b.renderOrder;
  12811. } else if (a.program !== b.program) {
  12812. return a.program.id - b.program.id;
  12813. } else if (a.material.id !== b.material.id) {
  12814. return a.material.id - b.material.id;
  12815. } else if (a.z !== b.z) {
  12816. return a.z - b.z;
  12817. } else {
  12818. return a.id - b.id;
  12819. }
  12820. }
  12821. function reversePainterSortStable(a, b) {
  12822. if (a.groupOrder !== b.groupOrder) {
  12823. return a.groupOrder - b.groupOrder;
  12824. } else if (a.renderOrder !== b.renderOrder) {
  12825. return a.renderOrder - b.renderOrder;
  12826. } else if (a.z !== b.z) {
  12827. return b.z - a.z;
  12828. } else {
  12829. return a.id - b.id;
  12830. }
  12831. }
  12832. function WebGLRenderList() {
  12833. var renderItems = [];
  12834. var renderItemsIndex = 0;
  12835. var opaque = [];
  12836. var transparent = [];
  12837. var defaultProgram = {
  12838. id: -1
  12839. };
  12840. function init() {
  12841. renderItemsIndex = 0;
  12842. opaque.length = 0;
  12843. transparent.length = 0;
  12844. }
  12845. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12846. var renderItem = renderItems[renderItemsIndex];
  12847. if (renderItem === undefined) {
  12848. renderItem = {
  12849. id: object.id,
  12850. object: object,
  12851. geometry: geometry,
  12852. material: material,
  12853. program: material.program || defaultProgram,
  12854. groupOrder: groupOrder,
  12855. renderOrder: object.renderOrder,
  12856. z: z,
  12857. group: group
  12858. };
  12859. renderItems[renderItemsIndex] = renderItem;
  12860. } else {
  12861. renderItem.id = object.id;
  12862. renderItem.object = object;
  12863. renderItem.geometry = geometry;
  12864. renderItem.material = material;
  12865. renderItem.program = material.program || defaultProgram;
  12866. renderItem.groupOrder = groupOrder;
  12867. renderItem.renderOrder = object.renderOrder;
  12868. renderItem.z = z;
  12869. renderItem.group = group;
  12870. }
  12871. renderItemsIndex++;
  12872. return renderItem;
  12873. }
  12874. function push(object, geometry, material, groupOrder, z, group) {
  12875. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12876. (material.transparent === true ? transparent : opaque).push(renderItem);
  12877. }
  12878. function unshift(object, geometry, material, groupOrder, z, group) {
  12879. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12880. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  12881. }
  12882. function sort() {
  12883. if (opaque.length > 1) opaque.sort(painterSortStable);
  12884. if (transparent.length > 1) transparent.sort(reversePainterSortStable);
  12885. }
  12886. return {
  12887. opaque: opaque,
  12888. transparent: transparent,
  12889. init: init,
  12890. push: push,
  12891. unshift: unshift,
  12892. sort: sort
  12893. };
  12894. }
  12895. function WebGLRenderLists() {
  12896. var lists = new WeakMap();
  12897. function onSceneDispose(event) {
  12898. var scene = event.target;
  12899. scene.removeEventListener('dispose', onSceneDispose);
  12900. lists.delete(scene);
  12901. }
  12902. function get(scene, camera) {
  12903. var cameras = lists.get(scene);
  12904. var list;
  12905. if (cameras === undefined) {
  12906. list = new WebGLRenderList();
  12907. lists.set(scene, new WeakMap());
  12908. lists.get(scene).set(camera, list);
  12909. scene.addEventListener('dispose', onSceneDispose);
  12910. } else {
  12911. list = cameras.get(camera);
  12912. if (list === undefined) {
  12913. list = new WebGLRenderList();
  12914. cameras.set(camera, list);
  12915. }
  12916. }
  12917. return list;
  12918. }
  12919. function dispose() {
  12920. lists = new WeakMap();
  12921. }
  12922. return {
  12923. get: get,
  12924. dispose: dispose
  12925. };
  12926. }
  12927. /**
  12928. * @author mrdoob / http://mrdoob.com/
  12929. */
  12930. function UniformsCache() {
  12931. var lights = {};
  12932. return {
  12933. get: function (light) {
  12934. if (lights[light.id] !== undefined) {
  12935. return lights[light.id];
  12936. }
  12937. var uniforms;
  12938. switch (light.type) {
  12939. case 'DirectionalLight':
  12940. uniforms = {
  12941. direction: new Vector3(),
  12942. color: new Color(),
  12943. shadow: false,
  12944. shadowBias: 0,
  12945. shadowRadius: 1,
  12946. shadowMapSize: new Vector2()
  12947. };
  12948. break;
  12949. case 'SpotLight':
  12950. uniforms = {
  12951. position: new Vector3(),
  12952. direction: new Vector3(),
  12953. color: new Color(),
  12954. distance: 0,
  12955. coneCos: 0,
  12956. penumbraCos: 0,
  12957. decay: 0,
  12958. shadow: false,
  12959. shadowBias: 0,
  12960. shadowRadius: 1,
  12961. shadowMapSize: new Vector2()
  12962. };
  12963. break;
  12964. case 'PointLight':
  12965. uniforms = {
  12966. position: new Vector3(),
  12967. color: new Color(),
  12968. distance: 0,
  12969. decay: 0,
  12970. shadow: false,
  12971. shadowBias: 0,
  12972. shadowRadius: 1,
  12973. shadowMapSize: new Vector2(),
  12974. shadowCameraNear: 1,
  12975. shadowCameraFar: 1000
  12976. };
  12977. break;
  12978. case 'HemisphereLight':
  12979. uniforms = {
  12980. direction: new Vector3(),
  12981. skyColor: new Color(),
  12982. groundColor: new Color()
  12983. };
  12984. break;
  12985. case 'RectAreaLight':
  12986. uniforms = {
  12987. color: new Color(),
  12988. position: new Vector3(),
  12989. halfWidth: new Vector3(),
  12990. halfHeight: new Vector3() // TODO (abelnation): set RectAreaLight shadow uniforms
  12991. };
  12992. break;
  12993. }
  12994. lights[light.id] = uniforms;
  12995. return uniforms;
  12996. }
  12997. };
  12998. }
  12999. var nextVersion = 0;
  13000. function shadowCastingLightsFirst(lightA, lightB) {
  13001. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  13002. }
  13003. function WebGLLights() {
  13004. var cache = new UniformsCache();
  13005. var state = {
  13006. version: 0,
  13007. hash: {
  13008. directionalLength: -1,
  13009. pointLength: -1,
  13010. spotLength: -1,
  13011. rectAreaLength: -1,
  13012. hemiLength: -1,
  13013. numDirectionalShadows: -1,
  13014. numPointShadows: -1,
  13015. numSpotShadows: -1
  13016. },
  13017. ambient: [0, 0, 0],
  13018. probe: [],
  13019. directional: [],
  13020. directionalShadowMap: [],
  13021. directionalShadowMatrix: [],
  13022. spot: [],
  13023. spotShadowMap: [],
  13024. spotShadowMatrix: [],
  13025. rectArea: [],
  13026. point: [],
  13027. pointShadowMap: [],
  13028. pointShadowMatrix: [],
  13029. hemi: [],
  13030. numDirectionalShadows: -1,
  13031. numPointShadows: -1,
  13032. numSpotShadows: -1
  13033. };
  13034. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  13035. var vector3 = new Vector3();
  13036. var matrix4 = new Matrix4();
  13037. var matrix42 = new Matrix4();
  13038. function setup(lights, shadows, camera) {
  13039. var r = 0,
  13040. g = 0,
  13041. b = 0;
  13042. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  13043. var directionalLength = 0;
  13044. var pointLength = 0;
  13045. var spotLength = 0;
  13046. var rectAreaLength = 0;
  13047. var hemiLength = 0;
  13048. var numDirectionalShadows = 0;
  13049. var numPointShadows = 0;
  13050. var numSpotShadows = 0;
  13051. var viewMatrix = camera.matrixWorldInverse;
  13052. lights.sort(shadowCastingLightsFirst);
  13053. for (var i = 0, l = lights.length; i < l; i++) {
  13054. var light = lights[i];
  13055. var color = light.color;
  13056. var intensity = light.intensity;
  13057. var distance = light.distance;
  13058. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  13059. if (light.isAmbientLight) {
  13060. r += color.r * intensity;
  13061. g += color.g * intensity;
  13062. b += color.b * intensity;
  13063. } else if (light.isLightProbe) {
  13064. for (var j = 0; j < 9; j++) {
  13065. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  13066. }
  13067. } else if (light.isDirectionalLight) {
  13068. var uniforms = cache.get(light);
  13069. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13070. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13071. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13072. uniforms.direction.sub(vector3);
  13073. uniforms.direction.transformDirection(viewMatrix);
  13074. uniforms.shadow = light.castShadow;
  13075. if (light.castShadow) {
  13076. var shadow = light.shadow;
  13077. uniforms.shadowBias = shadow.bias;
  13078. uniforms.shadowRadius = shadow.radius;
  13079. uniforms.shadowMapSize = shadow.mapSize;
  13080. state.directionalShadowMap[directionalLength] = shadowMap;
  13081. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  13082. numDirectionalShadows++;
  13083. }
  13084. state.directional[directionalLength] = uniforms;
  13085. directionalLength++;
  13086. } else if (light.isSpotLight) {
  13087. var uniforms = cache.get(light);
  13088. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13089. uniforms.position.applyMatrix4(viewMatrix);
  13090. uniforms.color.copy(color).multiplyScalar(intensity);
  13091. uniforms.distance = distance;
  13092. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13093. vector3.setFromMatrixPosition(light.target.matrixWorld);
  13094. uniforms.direction.sub(vector3);
  13095. uniforms.direction.transformDirection(viewMatrix);
  13096. uniforms.coneCos = Math.cos(light.angle);
  13097. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  13098. uniforms.decay = light.decay;
  13099. uniforms.shadow = light.castShadow;
  13100. if (light.castShadow) {
  13101. var shadow = light.shadow;
  13102. uniforms.shadowBias = shadow.bias;
  13103. uniforms.shadowRadius = shadow.radius;
  13104. uniforms.shadowMapSize = shadow.mapSize;
  13105. state.spotShadowMap[spotLength] = shadowMap;
  13106. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  13107. numSpotShadows++;
  13108. }
  13109. state.spot[spotLength] = uniforms;
  13110. spotLength++;
  13111. } else if (light.isRectAreaLight) {
  13112. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  13113. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  13114. // (b) intensity is the brightness of the light
  13115. uniforms.color.copy(color).multiplyScalar(intensity);
  13116. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13117. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  13118. matrix42.identity();
  13119. matrix4.copy(light.matrixWorld);
  13120. matrix4.premultiply(viewMatrix);
  13121. matrix42.extractRotation(matrix4);
  13122. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  13123. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  13124. uniforms.halfWidth.applyMatrix4(matrix42);
  13125. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  13126. // uniforms.distance = distance;
  13127. state.rectArea[rectAreaLength] = uniforms;
  13128. rectAreaLength++;
  13129. } else if (light.isPointLight) {
  13130. var uniforms = cache.get(light);
  13131. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  13132. uniforms.position.applyMatrix4(viewMatrix);
  13133. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  13134. uniforms.distance = light.distance;
  13135. uniforms.decay = light.decay;
  13136. uniforms.shadow = light.castShadow;
  13137. if (light.castShadow) {
  13138. var shadow = light.shadow;
  13139. uniforms.shadowBias = shadow.bias;
  13140. uniforms.shadowRadius = shadow.radius;
  13141. uniforms.shadowMapSize = shadow.mapSize;
  13142. uniforms.shadowCameraNear = shadow.camera.near;
  13143. uniforms.shadowCameraFar = shadow.camera.far;
  13144. state.pointShadowMap[pointLength] = shadowMap;
  13145. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  13146. numPointShadows++;
  13147. }
  13148. state.point[pointLength] = uniforms;
  13149. pointLength++;
  13150. } else if (light.isHemisphereLight) {
  13151. var uniforms = cache.get(light);
  13152. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  13153. uniforms.direction.transformDirection(viewMatrix);
  13154. uniforms.direction.normalize();
  13155. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  13156. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  13157. state.hemi[hemiLength] = uniforms;
  13158. hemiLength++;
  13159. }
  13160. }
  13161. state.ambient[0] = r;
  13162. state.ambient[1] = g;
  13163. state.ambient[2] = b;
  13164. var hash = state.hash;
  13165. 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) {
  13166. state.directional.length = directionalLength;
  13167. state.spot.length = spotLength;
  13168. state.rectArea.length = rectAreaLength;
  13169. state.point.length = pointLength;
  13170. state.hemi.length = hemiLength;
  13171. state.directionalShadowMap.length = numDirectionalShadows;
  13172. state.pointShadowMap.length = numPointShadows;
  13173. state.spotShadowMap.length = numSpotShadows;
  13174. state.directionalShadowMatrix.length = numDirectionalShadows;
  13175. state.pointShadowMatrix.length = numPointShadows;
  13176. state.spotShadowMatrix.length = numSpotShadows;
  13177. hash.directionalLength = directionalLength;
  13178. hash.pointLength = pointLength;
  13179. hash.spotLength = spotLength;
  13180. hash.rectAreaLength = rectAreaLength;
  13181. hash.hemiLength = hemiLength;
  13182. hash.numDirectionalShadows = numDirectionalShadows;
  13183. hash.numPointShadows = numPointShadows;
  13184. hash.numSpotShadows = numSpotShadows;
  13185. state.version = nextVersion++;
  13186. }
  13187. }
  13188. return {
  13189. setup: setup,
  13190. state: state
  13191. };
  13192. }
  13193. /**
  13194. * @author Mugen87 / https://github.com/Mugen87
  13195. */
  13196. function WebGLRenderState() {
  13197. var lights = new WebGLLights();
  13198. var lightsArray = [];
  13199. var shadowsArray = [];
  13200. function init() {
  13201. lightsArray.length = 0;
  13202. shadowsArray.length = 0;
  13203. }
  13204. function pushLight(light) {
  13205. lightsArray.push(light);
  13206. }
  13207. function pushShadow(shadowLight) {
  13208. shadowsArray.push(shadowLight);
  13209. }
  13210. function setupLights(camera) {
  13211. lights.setup(lightsArray, shadowsArray, camera);
  13212. }
  13213. var state = {
  13214. lightsArray: lightsArray,
  13215. shadowsArray: shadowsArray,
  13216. lights: lights
  13217. };
  13218. return {
  13219. init: init,
  13220. state: state,
  13221. setupLights: setupLights,
  13222. pushLight: pushLight,
  13223. pushShadow: pushShadow
  13224. };
  13225. }
  13226. function WebGLRenderStates() {
  13227. var renderStates = new WeakMap();
  13228. function onSceneDispose(event) {
  13229. var scene = event.target;
  13230. scene.removeEventListener('dispose', onSceneDispose);
  13231. renderStates.delete(scene);
  13232. }
  13233. function get(scene, camera) {
  13234. var renderState;
  13235. if (renderStates.has(scene) === false) {
  13236. renderState = new WebGLRenderState();
  13237. renderStates.set(scene, new WeakMap());
  13238. renderStates.get(scene).set(camera, renderState);
  13239. scene.addEventListener('dispose', onSceneDispose);
  13240. } else {
  13241. if (renderStates.get(scene).has(camera) === false) {
  13242. renderState = new WebGLRenderState();
  13243. renderStates.get(scene).set(camera, renderState);
  13244. } else {
  13245. renderState = renderStates.get(scene).get(camera);
  13246. }
  13247. }
  13248. return renderState;
  13249. }
  13250. function dispose() {
  13251. renderStates = new WeakMap();
  13252. }
  13253. return {
  13254. get: get,
  13255. dispose: dispose
  13256. };
  13257. }
  13258. /**
  13259. * @author mrdoob / http://mrdoob.com/
  13260. * @author alteredq / http://alteredqualia.com/
  13261. * @author bhouston / https://clara.io
  13262. * @author WestLangley / http://github.com/WestLangley
  13263. *
  13264. * parameters = {
  13265. *
  13266. * opacity: <float>,
  13267. *
  13268. * map: new THREE.Texture( <Image> ),
  13269. *
  13270. * alphaMap: new THREE.Texture( <Image> ),
  13271. *
  13272. * displacementMap: new THREE.Texture( <Image> ),
  13273. * displacementScale: <float>,
  13274. * displacementBias: <float>,
  13275. *
  13276. * wireframe: <boolean>,
  13277. * wireframeLinewidth: <float>
  13278. * }
  13279. */
  13280. function MeshDepthMaterial(parameters) {
  13281. Material.call(this);
  13282. this.type = 'MeshDepthMaterial';
  13283. this.depthPacking = BasicDepthPacking;
  13284. this.skinning = false;
  13285. this.morphTargets = false;
  13286. this.map = null;
  13287. this.alphaMap = null;
  13288. this.displacementMap = null;
  13289. this.displacementScale = 1;
  13290. this.displacementBias = 0;
  13291. this.wireframe = false;
  13292. this.wireframeLinewidth = 1;
  13293. this.fog = false;
  13294. this.setValues(parameters);
  13295. }
  13296. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  13297. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  13298. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  13299. MeshDepthMaterial.prototype.copy = function (source) {
  13300. Material.prototype.copy.call(this, source);
  13301. this.depthPacking = source.depthPacking;
  13302. this.skinning = source.skinning;
  13303. this.morphTargets = source.morphTargets;
  13304. this.map = source.map;
  13305. this.alphaMap = source.alphaMap;
  13306. this.displacementMap = source.displacementMap;
  13307. this.displacementScale = source.displacementScale;
  13308. this.displacementBias = source.displacementBias;
  13309. this.wireframe = source.wireframe;
  13310. this.wireframeLinewidth = source.wireframeLinewidth;
  13311. return this;
  13312. };
  13313. /**
  13314. * @author WestLangley / http://github.com/WestLangley
  13315. *
  13316. * parameters = {
  13317. *
  13318. * referencePosition: <float>,
  13319. * nearDistance: <float>,
  13320. * farDistance: <float>,
  13321. *
  13322. * skinning: <bool>,
  13323. * morphTargets: <bool>,
  13324. *
  13325. * map: new THREE.Texture( <Image> ),
  13326. *
  13327. * alphaMap: new THREE.Texture( <Image> ),
  13328. *
  13329. * displacementMap: new THREE.Texture( <Image> ),
  13330. * displacementScale: <float>,
  13331. * displacementBias: <float>
  13332. *
  13333. * }
  13334. */
  13335. function MeshDistanceMaterial(parameters) {
  13336. Material.call(this);
  13337. this.type = 'MeshDistanceMaterial';
  13338. this.referencePosition = new Vector3();
  13339. this.nearDistance = 1;
  13340. this.farDistance = 1000;
  13341. this.skinning = false;
  13342. this.morphTargets = false;
  13343. this.map = null;
  13344. this.alphaMap = null;
  13345. this.displacementMap = null;
  13346. this.displacementScale = 1;
  13347. this.displacementBias = 0;
  13348. this.fog = false;
  13349. this.setValues(parameters);
  13350. }
  13351. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  13352. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  13353. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  13354. MeshDistanceMaterial.prototype.copy = function (source) {
  13355. Material.prototype.copy.call(this, source);
  13356. this.referencePosition.copy(source.referencePosition);
  13357. this.nearDistance = source.nearDistance;
  13358. this.farDistance = source.farDistance;
  13359. this.skinning = source.skinning;
  13360. this.morphTargets = source.morphTargets;
  13361. this.map = source.map;
  13362. this.alphaMap = source.alphaMap;
  13363. this.displacementMap = source.displacementMap;
  13364. this.displacementScale = source.displacementScale;
  13365. this.displacementBias = source.displacementBias;
  13366. return this;
  13367. };
  13368. 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}";
  13369. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13370. /**
  13371. * @author alteredq / http://alteredqualia.com/
  13372. * @author mrdoob / http://mrdoob.com/
  13373. */
  13374. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  13375. var _frustum = new Frustum(),
  13376. _shadowMapSize = new Vector2(),
  13377. _viewportSize = new Vector2(),
  13378. _viewport = new Vector4(),
  13379. _MorphingFlag = 1,
  13380. _SkinningFlag = 2,
  13381. _NumberOfMaterialVariants = (_MorphingFlag | _SkinningFlag) + 1,
  13382. _depthMaterials = new Array(_NumberOfMaterialVariants),
  13383. _distanceMaterials = new Array(_NumberOfMaterialVariants),
  13384. _materialCache = {};
  13385. var shadowSide = {
  13386. 0: BackSide,
  13387. 1: FrontSide,
  13388. 2: DoubleSide
  13389. };
  13390. var shadowMaterialVertical = new ShaderMaterial({
  13391. defines: {
  13392. SAMPLE_RATE: 2.0 / 8.0,
  13393. HALF_SAMPLE_RATE: 1.0 / 8.0
  13394. },
  13395. uniforms: {
  13396. shadow_pass: {
  13397. value: null
  13398. },
  13399. resolution: {
  13400. value: new Vector2()
  13401. },
  13402. radius: {
  13403. value: 4.0
  13404. }
  13405. },
  13406. vertexShader: vsm_vert,
  13407. fragmentShader: vsm_frag
  13408. });
  13409. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  13410. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  13411. var fullScreenTri = new BufferGeometry();
  13412. fullScreenTri.addAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  13413. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); // init
  13414. for (var i = 0; i !== _NumberOfMaterialVariants; ++i) {
  13415. var useMorphing = (i & _MorphingFlag) !== 0;
  13416. var useSkinning = (i & _SkinningFlag) !== 0;
  13417. var depthMaterial = new MeshDepthMaterial({
  13418. depthPacking: RGBADepthPacking,
  13419. morphTargets: useMorphing,
  13420. skinning: useSkinning
  13421. });
  13422. _depthMaterials[i] = depthMaterial;
  13423. var distanceMaterial = new MeshDistanceMaterial({
  13424. morphTargets: useMorphing,
  13425. skinning: useSkinning
  13426. });
  13427. _distanceMaterials[i] = distanceMaterial;
  13428. }
  13429. var scope = this;
  13430. this.enabled = false;
  13431. this.autoUpdate = true;
  13432. this.needsUpdate = false;
  13433. this.type = PCFShadowMap;
  13434. this.render = function (lights, scene, camera) {
  13435. if (scope.enabled === false) return;
  13436. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  13437. if (lights.length === 0) return;
  13438. var currentRenderTarget = _renderer.getRenderTarget();
  13439. var activeCubeFace = _renderer.getActiveCubeFace();
  13440. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13441. var _state = _renderer.state; // Set GL state for depth map.
  13442. _state.setBlending(NoBlending);
  13443. _state.buffers.color.setClear(1, 1, 1, 1);
  13444. _state.buffers.depth.setTest(true);
  13445. _state.setScissorTest(false); // render depth map
  13446. for (var i = 0, il = lights.length; i < il; i++) {
  13447. var light = lights[i];
  13448. var shadow = light.shadow;
  13449. if (shadow === undefined) {
  13450. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  13451. continue;
  13452. }
  13453. _shadowMapSize.copy(shadow.mapSize);
  13454. var shadowFrameExtents = shadow.getFrameExtents();
  13455. _shadowMapSize.multiply(shadowFrameExtents);
  13456. _viewportSize.copy(shadow.mapSize);
  13457. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  13458. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  13459. if (_shadowMapSize.x > maxTextureSize) {
  13460. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  13461. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13462. shadow.mapSize.x = _viewportSize.x;
  13463. }
  13464. if (_shadowMapSize.y > maxTextureSize) {
  13465. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  13466. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13467. shadow.mapSize.y = _viewportSize.y;
  13468. }
  13469. }
  13470. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13471. var pars = {
  13472. minFilter: LinearFilter,
  13473. magFilter: LinearFilter,
  13474. format: RGBAFormat
  13475. };
  13476. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13477. shadow.map.texture.name = light.name + ".shadowMap";
  13478. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13479. shadow.camera.updateProjectionMatrix();
  13480. }
  13481. if (shadow.map === null) {
  13482. var pars = {
  13483. minFilter: NearestFilter,
  13484. magFilter: NearestFilter,
  13485. format: RGBAFormat
  13486. };
  13487. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  13488. shadow.map.texture.name = light.name + ".shadowMap";
  13489. shadow.camera.updateProjectionMatrix();
  13490. }
  13491. _renderer.setRenderTarget(shadow.map);
  13492. _renderer.clear();
  13493. var viewportCount = shadow.getViewportCount();
  13494. for (var vp = 0; vp < viewportCount; vp++) {
  13495. var viewport = shadow.getViewport(vp);
  13496. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  13497. _state.viewport(_viewport);
  13498. shadow.updateMatrices(light, camera, vp);
  13499. _frustum = shadow.getFrustum();
  13500. renderObject(scene, camera, shadow.camera, light, this.type);
  13501. } // do blur pass for VSM
  13502. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  13503. VSMPass(shadow, camera);
  13504. }
  13505. }
  13506. scope.needsUpdate = false;
  13507. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  13508. };
  13509. function VSMPass(shadow, camera) {
  13510. var geometry = _objects.update(fullScreenMesh); // vertical pass
  13511. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13512. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13513. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13514. _renderer.setRenderTarget(shadow.mapPass);
  13515. _renderer.clear();
  13516. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  13517. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13518. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  13519. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  13520. _renderer.setRenderTarget(shadow.map);
  13521. _renderer.clear();
  13522. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  13523. }
  13524. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  13525. var geometry = object.geometry;
  13526. var result = null;
  13527. var materialVariants = _depthMaterials;
  13528. var customMaterial = object.customDepthMaterial;
  13529. if (light.isPointLight) {
  13530. materialVariants = _distanceMaterials;
  13531. customMaterial = object.customDistanceMaterial;
  13532. }
  13533. if (!customMaterial) {
  13534. var useMorphing = false;
  13535. if (material.morphTargets) {
  13536. if (geometry && geometry.isBufferGeometry) {
  13537. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  13538. } else if (geometry && geometry.isGeometry) {
  13539. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  13540. }
  13541. }
  13542. if (object.isSkinnedMesh && material.skinning === false) {
  13543. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  13544. }
  13545. var useSkinning = object.isSkinnedMesh && material.skinning;
  13546. var variantIndex = 0;
  13547. if (useMorphing) variantIndex |= _MorphingFlag;
  13548. if (useSkinning) variantIndex |= _SkinningFlag;
  13549. result = materialVariants[variantIndex];
  13550. } else {
  13551. result = customMaterial;
  13552. }
  13553. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  13554. // in this case we need a unique material instance reflecting the
  13555. // appropriate state
  13556. var keyA = result.uuid,
  13557. keyB = material.uuid;
  13558. var materialsForVariant = _materialCache[keyA];
  13559. if (materialsForVariant === undefined) {
  13560. materialsForVariant = {};
  13561. _materialCache[keyA] = materialsForVariant;
  13562. }
  13563. var cachedMaterial = materialsForVariant[keyB];
  13564. if (cachedMaterial === undefined) {
  13565. cachedMaterial = result.clone();
  13566. materialsForVariant[keyB] = cachedMaterial;
  13567. }
  13568. result = cachedMaterial;
  13569. }
  13570. result.visible = material.visible;
  13571. result.wireframe = material.wireframe;
  13572. if (type === VSMShadowMap) {
  13573. result.side = material.shadowSide != null ? material.shadowSide : material.side;
  13574. } else {
  13575. result.side = material.shadowSide != null ? material.shadowSide : shadowSide[material.side];
  13576. }
  13577. result.clipShadows = material.clipShadows;
  13578. result.clippingPlanes = material.clippingPlanes;
  13579. result.clipIntersection = material.clipIntersection;
  13580. result.wireframeLinewidth = material.wireframeLinewidth;
  13581. result.linewidth = material.linewidth;
  13582. if (light.isPointLight && result.isMeshDistanceMaterial) {
  13583. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  13584. result.nearDistance = shadowCameraNear;
  13585. result.farDistance = shadowCameraFar;
  13586. }
  13587. return result;
  13588. }
  13589. function renderObject(object, camera, shadowCamera, light, type) {
  13590. if (object.visible === false) return;
  13591. var visible = object.layers.test(camera.layers);
  13592. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  13593. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  13594. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  13595. var geometry = _objects.update(object);
  13596. var material = object.material;
  13597. if (Array.isArray(material)) {
  13598. var groups = geometry.groups;
  13599. for (var k = 0, kl = groups.length; k < kl; k++) {
  13600. var group = groups[k];
  13601. var groupMaterial = material[group.materialIndex];
  13602. if (groupMaterial && groupMaterial.visible) {
  13603. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  13604. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  13605. }
  13606. }
  13607. } else if (material.visible) {
  13608. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  13609. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  13610. }
  13611. }
  13612. }
  13613. var children = object.children;
  13614. for (var i = 0, l = children.length; i < l; i++) {
  13615. renderObject(children[i], camera, shadowCamera, light, type);
  13616. }
  13617. }
  13618. }
  13619. /**
  13620. * @author mrdoob / http://mrdoob.com/
  13621. */
  13622. function WebGLState(gl, extensions, utils, capabilities) {
  13623. function ColorBuffer() {
  13624. var locked = false;
  13625. var color = new Vector4();
  13626. var currentColorMask = null;
  13627. var currentColorClear = new Vector4(0, 0, 0, 0);
  13628. return {
  13629. setMask: function (colorMask) {
  13630. if (currentColorMask !== colorMask && !locked) {
  13631. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  13632. currentColorMask = colorMask;
  13633. }
  13634. },
  13635. setLocked: function (lock) {
  13636. locked = lock;
  13637. },
  13638. setClear: function (r, g, b, a, premultipliedAlpha) {
  13639. if (premultipliedAlpha === true) {
  13640. r *= a;
  13641. g *= a;
  13642. b *= a;
  13643. }
  13644. color.set(r, g, b, a);
  13645. if (currentColorClear.equals(color) === false) {
  13646. gl.clearColor(r, g, b, a);
  13647. currentColorClear.copy(color);
  13648. }
  13649. },
  13650. reset: function () {
  13651. locked = false;
  13652. currentColorMask = null;
  13653. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  13654. }
  13655. };
  13656. }
  13657. function DepthBuffer() {
  13658. var locked = false;
  13659. var currentDepthMask = null;
  13660. var currentDepthFunc = null;
  13661. var currentDepthClear = null;
  13662. return {
  13663. setTest: function (depthTest) {
  13664. if (depthTest) {
  13665. enable(2929);
  13666. } else {
  13667. disable(2929);
  13668. }
  13669. },
  13670. setMask: function (depthMask) {
  13671. if (currentDepthMask !== depthMask && !locked) {
  13672. gl.depthMask(depthMask);
  13673. currentDepthMask = depthMask;
  13674. }
  13675. },
  13676. setFunc: function (depthFunc) {
  13677. if (currentDepthFunc !== depthFunc) {
  13678. if (depthFunc) {
  13679. switch (depthFunc) {
  13680. case NeverDepth:
  13681. gl.depthFunc(512);
  13682. break;
  13683. case AlwaysDepth:
  13684. gl.depthFunc(519);
  13685. break;
  13686. case LessDepth:
  13687. gl.depthFunc(513);
  13688. break;
  13689. case LessEqualDepth:
  13690. gl.depthFunc(515);
  13691. break;
  13692. case EqualDepth:
  13693. gl.depthFunc(514);
  13694. break;
  13695. case GreaterEqualDepth:
  13696. gl.depthFunc(518);
  13697. break;
  13698. case GreaterDepth:
  13699. gl.depthFunc(516);
  13700. break;
  13701. case NotEqualDepth:
  13702. gl.depthFunc(517);
  13703. break;
  13704. default:
  13705. gl.depthFunc(515);
  13706. }
  13707. } else {
  13708. gl.depthFunc(515);
  13709. }
  13710. currentDepthFunc = depthFunc;
  13711. }
  13712. },
  13713. setLocked: function (lock) {
  13714. locked = lock;
  13715. },
  13716. setClear: function (depth) {
  13717. if (currentDepthClear !== depth) {
  13718. gl.clearDepth(depth);
  13719. currentDepthClear = depth;
  13720. }
  13721. },
  13722. reset: function () {
  13723. locked = false;
  13724. currentDepthMask = null;
  13725. currentDepthFunc = null;
  13726. currentDepthClear = null;
  13727. }
  13728. };
  13729. }
  13730. function StencilBuffer() {
  13731. var locked = false;
  13732. var currentStencilMask = null;
  13733. var currentStencilFunc = null;
  13734. var currentStencilRef = null;
  13735. var currentStencilFuncMask = null;
  13736. var currentStencilFail = null;
  13737. var currentStencilZFail = null;
  13738. var currentStencilZPass = null;
  13739. var currentStencilClear = null;
  13740. return {
  13741. setTest: function (stencilTest) {
  13742. if (!locked) {
  13743. if (stencilTest) {
  13744. enable(2960);
  13745. } else {
  13746. disable(2960);
  13747. }
  13748. }
  13749. },
  13750. setMask: function (stencilMask) {
  13751. if (currentStencilMask !== stencilMask && !locked) {
  13752. gl.stencilMask(stencilMask);
  13753. currentStencilMask = stencilMask;
  13754. }
  13755. },
  13756. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  13757. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  13758. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  13759. currentStencilFunc = stencilFunc;
  13760. currentStencilRef = stencilRef;
  13761. currentStencilFuncMask = stencilMask;
  13762. }
  13763. },
  13764. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  13765. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13766. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13767. currentStencilFail = stencilFail;
  13768. currentStencilZFail = stencilZFail;
  13769. currentStencilZPass = stencilZPass;
  13770. }
  13771. },
  13772. setLocked: function (lock) {
  13773. locked = lock;
  13774. },
  13775. setClear: function (stencil) {
  13776. if (currentStencilClear !== stencil) {
  13777. gl.clearStencil(stencil);
  13778. currentStencilClear = stencil;
  13779. }
  13780. },
  13781. reset: function () {
  13782. locked = false;
  13783. currentStencilMask = null;
  13784. currentStencilFunc = null;
  13785. currentStencilRef = null;
  13786. currentStencilFuncMask = null;
  13787. currentStencilFail = null;
  13788. currentStencilZFail = null;
  13789. currentStencilZPass = null;
  13790. currentStencilClear = null;
  13791. }
  13792. };
  13793. } //
  13794. var colorBuffer = new ColorBuffer();
  13795. var depthBuffer = new DepthBuffer();
  13796. var stencilBuffer = new StencilBuffer();
  13797. var maxVertexAttributes = gl.getParameter(34921);
  13798. var newAttributes = new Uint8Array(maxVertexAttributes);
  13799. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  13800. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  13801. var enabledCapabilities = {};
  13802. var compressedTextureFormats = null;
  13803. var currentProgram = null;
  13804. var currentBlendingEnabled = null;
  13805. var currentBlending = null;
  13806. var currentBlendEquation = null;
  13807. var currentBlendSrc = null;
  13808. var currentBlendDst = null;
  13809. var currentBlendEquationAlpha = null;
  13810. var currentBlendSrcAlpha = null;
  13811. var currentBlendDstAlpha = null;
  13812. var currentPremultipledAlpha = false;
  13813. var currentFlipSided = null;
  13814. var currentCullFace = null;
  13815. var currentLineWidth = null;
  13816. var currentPolygonOffsetFactor = null;
  13817. var currentPolygonOffsetUnits = null;
  13818. var maxTextures = gl.getParameter(35661);
  13819. var lineWidthAvailable = false;
  13820. var version = 0;
  13821. var glVersion = gl.getParameter(7938);
  13822. if (glVersion.indexOf('WebGL') !== -1) {
  13823. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  13824. lineWidthAvailable = version >= 1.0;
  13825. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13826. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  13827. lineWidthAvailable = version >= 2.0;
  13828. }
  13829. var currentTextureSlot = null;
  13830. var currentBoundTextures = {};
  13831. var currentScissor = new Vector4();
  13832. var currentViewport = new Vector4();
  13833. function createTexture(type, target, count) {
  13834. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13835. var texture = gl.createTexture();
  13836. gl.bindTexture(type, texture);
  13837. gl.texParameteri(type, 10241, 9728);
  13838. gl.texParameteri(type, 10240, 9728);
  13839. for (var i = 0; i < count; i++) {
  13840. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  13841. }
  13842. return texture;
  13843. }
  13844. var emptyTextures = {};
  13845. emptyTextures[3553] = createTexture(3553, 3553, 1);
  13846. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  13847. colorBuffer.setClear(0, 0, 0, 1);
  13848. depthBuffer.setClear(1);
  13849. stencilBuffer.setClear(0);
  13850. enable(2929);
  13851. depthBuffer.setFunc(LessEqualDepth);
  13852. setFlipSided(false);
  13853. setCullFace(CullFaceBack);
  13854. enable(2884);
  13855. setBlending(NoBlending); //
  13856. function initAttributes() {
  13857. for (var i = 0, l = newAttributes.length; i < l; i++) {
  13858. newAttributes[i] = 0;
  13859. }
  13860. }
  13861. function enableAttribute(attribute) {
  13862. enableAttributeAndDivisor(attribute, 0);
  13863. }
  13864. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  13865. newAttributes[attribute] = 1;
  13866. if (enabledAttributes[attribute] === 0) {
  13867. gl.enableVertexAttribArray(attribute);
  13868. enabledAttributes[attribute] = 1;
  13869. }
  13870. if (attributeDivisors[attribute] !== meshPerAttribute) {
  13871. var extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  13872. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  13873. attributeDivisors[attribute] = meshPerAttribute;
  13874. }
  13875. }
  13876. function disableUnusedAttributes() {
  13877. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  13878. if (enabledAttributes[i] !== newAttributes[i]) {
  13879. gl.disableVertexAttribArray(i);
  13880. enabledAttributes[i] = 0;
  13881. }
  13882. }
  13883. }
  13884. function enable(id) {
  13885. if (enabledCapabilities[id] !== true) {
  13886. gl.enable(id);
  13887. enabledCapabilities[id] = true;
  13888. }
  13889. }
  13890. function disable(id) {
  13891. if (enabledCapabilities[id] !== false) {
  13892. gl.disable(id);
  13893. enabledCapabilities[id] = false;
  13894. }
  13895. }
  13896. function getCompressedTextureFormats() {
  13897. if (compressedTextureFormats === null) {
  13898. compressedTextureFormats = [];
  13899. 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')) {
  13900. var formats = gl.getParameter(34467);
  13901. for (var i = 0; i < formats.length; i++) {
  13902. compressedTextureFormats.push(formats[i]);
  13903. }
  13904. }
  13905. }
  13906. return compressedTextureFormats;
  13907. }
  13908. function useProgram(program) {
  13909. if (currentProgram !== program) {
  13910. gl.useProgram(program);
  13911. currentProgram = program;
  13912. return true;
  13913. }
  13914. return false;
  13915. }
  13916. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13917. if (blending === NoBlending) {
  13918. if (currentBlendingEnabled) {
  13919. disable(3042);
  13920. currentBlendingEnabled = false;
  13921. }
  13922. return;
  13923. }
  13924. if (!currentBlendingEnabled) {
  13925. enable(3042);
  13926. currentBlendingEnabled = true;
  13927. }
  13928. if (blending !== CustomBlending) {
  13929. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13930. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13931. gl.blendEquation(32774);
  13932. currentBlendEquation = AddEquation;
  13933. currentBlendEquationAlpha = AddEquation;
  13934. }
  13935. if (premultipliedAlpha) {
  13936. switch (blending) {
  13937. case NormalBlending:
  13938. gl.blendFuncSeparate(1, 771, 1, 771);
  13939. break;
  13940. case AdditiveBlending:
  13941. gl.blendFunc(1, 1);
  13942. break;
  13943. case SubtractiveBlending:
  13944. gl.blendFuncSeparate(0, 0, 769, 771);
  13945. break;
  13946. case MultiplyBlending:
  13947. gl.blendFuncSeparate(0, 768, 0, 770);
  13948. break;
  13949. default:
  13950. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13951. break;
  13952. }
  13953. } else {
  13954. switch (blending) {
  13955. case NormalBlending:
  13956. gl.blendFuncSeparate(770, 771, 1, 771);
  13957. break;
  13958. case AdditiveBlending:
  13959. gl.blendFunc(770, 1);
  13960. break;
  13961. case SubtractiveBlending:
  13962. gl.blendFunc(0, 769);
  13963. break;
  13964. case MultiplyBlending:
  13965. gl.blendFunc(0, 768);
  13966. break;
  13967. default:
  13968. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13969. break;
  13970. }
  13971. }
  13972. currentBlendSrc = null;
  13973. currentBlendDst = null;
  13974. currentBlendSrcAlpha = null;
  13975. currentBlendDstAlpha = null;
  13976. currentBlending = blending;
  13977. currentPremultipledAlpha = premultipliedAlpha;
  13978. }
  13979. return;
  13980. } // custom blending
  13981. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13982. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13983. blendDstAlpha = blendDstAlpha || blendDst;
  13984. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13985. gl.blendEquationSeparate(utils.convert(blendEquation), utils.convert(blendEquationAlpha));
  13986. currentBlendEquation = blendEquation;
  13987. currentBlendEquationAlpha = blendEquationAlpha;
  13988. }
  13989. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13990. gl.blendFuncSeparate(utils.convert(blendSrc), utils.convert(blendDst), utils.convert(blendSrcAlpha), utils.convert(blendDstAlpha));
  13991. currentBlendSrc = blendSrc;
  13992. currentBlendDst = blendDst;
  13993. currentBlendSrcAlpha = blendSrcAlpha;
  13994. currentBlendDstAlpha = blendDstAlpha;
  13995. }
  13996. currentBlending = blending;
  13997. currentPremultipledAlpha = null;
  13998. }
  13999. function setMaterial(material, frontFaceCW) {
  14000. material.side === DoubleSide ? disable(2884) : enable(2884);
  14001. var flipSided = material.side === BackSide;
  14002. if (frontFaceCW) flipSided = !flipSided;
  14003. setFlipSided(flipSided);
  14004. 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);
  14005. depthBuffer.setFunc(material.depthFunc);
  14006. depthBuffer.setTest(material.depthTest);
  14007. depthBuffer.setMask(material.depthWrite);
  14008. colorBuffer.setMask(material.colorWrite);
  14009. var stencilWrite = material.stencilWrite;
  14010. stencilBuffer.setTest(stencilWrite);
  14011. if (stencilWrite) {
  14012. stencilBuffer.setMask(material.stencilWriteMask);
  14013. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  14014. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  14015. }
  14016. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  14017. } //
  14018. function setFlipSided(flipSided) {
  14019. if (currentFlipSided !== flipSided) {
  14020. if (flipSided) {
  14021. gl.frontFace(2304);
  14022. } else {
  14023. gl.frontFace(2305);
  14024. }
  14025. currentFlipSided = flipSided;
  14026. }
  14027. }
  14028. function setCullFace(cullFace) {
  14029. if (cullFace !== CullFaceNone) {
  14030. enable(2884);
  14031. if (cullFace !== currentCullFace) {
  14032. if (cullFace === CullFaceBack) {
  14033. gl.cullFace(1029);
  14034. } else if (cullFace === CullFaceFront) {
  14035. gl.cullFace(1028);
  14036. } else {
  14037. gl.cullFace(1032);
  14038. }
  14039. }
  14040. } else {
  14041. disable(2884);
  14042. }
  14043. currentCullFace = cullFace;
  14044. }
  14045. function setLineWidth(width) {
  14046. if (width !== currentLineWidth) {
  14047. if (lineWidthAvailable) gl.lineWidth(width);
  14048. currentLineWidth = width;
  14049. }
  14050. }
  14051. function setPolygonOffset(polygonOffset, factor, units) {
  14052. if (polygonOffset) {
  14053. enable(32823);
  14054. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  14055. gl.polygonOffset(factor, units);
  14056. currentPolygonOffsetFactor = factor;
  14057. currentPolygonOffsetUnits = units;
  14058. }
  14059. } else {
  14060. disable(32823);
  14061. }
  14062. }
  14063. function setScissorTest(scissorTest) {
  14064. if (scissorTest) {
  14065. enable(3089);
  14066. } else {
  14067. disable(3089);
  14068. }
  14069. } // texture
  14070. function activeTexture(webglSlot) {
  14071. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  14072. if (currentTextureSlot !== webglSlot) {
  14073. gl.activeTexture(webglSlot);
  14074. currentTextureSlot = webglSlot;
  14075. }
  14076. }
  14077. function bindTexture(webglType, webglTexture) {
  14078. if (currentTextureSlot === null) {
  14079. activeTexture();
  14080. }
  14081. var boundTexture = currentBoundTextures[currentTextureSlot];
  14082. if (boundTexture === undefined) {
  14083. boundTexture = {
  14084. type: undefined,
  14085. texture: undefined
  14086. };
  14087. currentBoundTextures[currentTextureSlot] = boundTexture;
  14088. }
  14089. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  14090. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  14091. boundTexture.type = webglType;
  14092. boundTexture.texture = webglTexture;
  14093. }
  14094. }
  14095. function compressedTexImage2D() {
  14096. try {
  14097. gl.compressedTexImage2D.apply(gl, arguments);
  14098. } catch (error) {
  14099. console.error('THREE.WebGLState:', error);
  14100. }
  14101. }
  14102. function texImage2D() {
  14103. try {
  14104. gl.texImage2D.apply(gl, arguments);
  14105. } catch (error) {
  14106. console.error('THREE.WebGLState:', error);
  14107. }
  14108. }
  14109. function texImage3D() {
  14110. try {
  14111. gl.texImage3D.apply(gl, arguments);
  14112. } catch (error) {
  14113. console.error('THREE.WebGLState:', error);
  14114. }
  14115. } //
  14116. function scissor(scissor) {
  14117. if (currentScissor.equals(scissor) === false) {
  14118. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  14119. currentScissor.copy(scissor);
  14120. }
  14121. }
  14122. function viewport(viewport) {
  14123. if (currentViewport.equals(viewport) === false) {
  14124. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  14125. currentViewport.copy(viewport);
  14126. }
  14127. } //
  14128. function reset() {
  14129. for (var i = 0; i < enabledAttributes.length; i++) {
  14130. if (enabledAttributes[i] === 1) {
  14131. gl.disableVertexAttribArray(i);
  14132. enabledAttributes[i] = 0;
  14133. }
  14134. }
  14135. enabledCapabilities = {};
  14136. compressedTextureFormats = null;
  14137. currentTextureSlot = null;
  14138. currentBoundTextures = {};
  14139. currentProgram = null;
  14140. currentBlending = null;
  14141. currentFlipSided = null;
  14142. currentCullFace = null;
  14143. colorBuffer.reset();
  14144. depthBuffer.reset();
  14145. stencilBuffer.reset();
  14146. }
  14147. return {
  14148. buffers: {
  14149. color: colorBuffer,
  14150. depth: depthBuffer,
  14151. stencil: stencilBuffer
  14152. },
  14153. initAttributes: initAttributes,
  14154. enableAttribute: enableAttribute,
  14155. enableAttributeAndDivisor: enableAttributeAndDivisor,
  14156. disableUnusedAttributes: disableUnusedAttributes,
  14157. enable: enable,
  14158. disable: disable,
  14159. getCompressedTextureFormats: getCompressedTextureFormats,
  14160. useProgram: useProgram,
  14161. setBlending: setBlending,
  14162. setMaterial: setMaterial,
  14163. setFlipSided: setFlipSided,
  14164. setCullFace: setCullFace,
  14165. setLineWidth: setLineWidth,
  14166. setPolygonOffset: setPolygonOffset,
  14167. setScissorTest: setScissorTest,
  14168. activeTexture: activeTexture,
  14169. bindTexture: bindTexture,
  14170. compressedTexImage2D: compressedTexImage2D,
  14171. texImage2D: texImage2D,
  14172. texImage3D: texImage3D,
  14173. scissor: scissor,
  14174. viewport: viewport,
  14175. reset: reset
  14176. };
  14177. }
  14178. /**
  14179. * @author mrdoob / http://mrdoob.com/
  14180. */
  14181. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  14182. var _videoTextures = new WeakMap();
  14183. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14184. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14185. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  14186. function createCanvas(width, height) {
  14187. // Use OffscreenCanvas when available. Specially needed in web workers
  14188. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14189. }
  14190. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  14191. var scale = 1; // handle case if texture exceeds max size
  14192. if (image.width > maxSize || image.height > maxSize) {
  14193. scale = maxSize / Math.max(image.width, image.height);
  14194. } // only perform resize if necessary
  14195. if (scale < 1 || needsPowerOfTwo === true) {
  14196. // only perform resize for certain image types
  14197. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  14198. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  14199. var width = floor(scale * image.width);
  14200. var height = floor(scale * image.height);
  14201. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  14202. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  14203. canvas.width = width;
  14204. canvas.height = height;
  14205. var context = canvas.getContext('2d');
  14206. context.drawImage(image, 0, 0, width, height);
  14207. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  14208. return canvas;
  14209. } else {
  14210. if ('data' in image) {
  14211. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  14212. }
  14213. return image;
  14214. }
  14215. }
  14216. return image;
  14217. }
  14218. function isPowerOfTwo(image) {
  14219. return _Math.isPowerOfTwo(image.width) && _Math.isPowerOfTwo(image.height);
  14220. }
  14221. function textureNeedsPowerOfTwo(texture) {
  14222. if (capabilities.isWebGL2) return false;
  14223. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14224. }
  14225. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  14226. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14227. }
  14228. function generateMipmap(target, texture, width, height) {
  14229. _gl.generateMipmap(target);
  14230. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  14231. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  14232. }
  14233. function getInternalFormat(glFormat, glType) {
  14234. if (!capabilities.isWebGL2) return glFormat;
  14235. var internalFormat = glFormat;
  14236. if (glFormat === 6403) {
  14237. if (glType === 5126) internalFormat = 33326;
  14238. if (glType === 5131) internalFormat = 33325;
  14239. if (glType === 5121) internalFormat = 33321;
  14240. }
  14241. if (glFormat === 6407) {
  14242. if (glType === 5126) internalFormat = 34837;
  14243. if (glType === 5131) internalFormat = 34843;
  14244. if (glType === 5121) internalFormat = 32849;
  14245. }
  14246. if (glFormat === 6408) {
  14247. if (glType === 5126) internalFormat = 34836;
  14248. if (glType === 5131) internalFormat = 34842;
  14249. if (glType === 5121) internalFormat = 32856;
  14250. }
  14251. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  14252. extensions.get('EXT_color_buffer_float');
  14253. } else if (internalFormat === 34843 || internalFormat === 34837) {
  14254. console.warn('THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.');
  14255. }
  14256. return internalFormat;
  14257. } // Fallback filters for non-power-of-2 textures
  14258. function filterFallback(f) {
  14259. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  14260. return 9728;
  14261. }
  14262. return 9729;
  14263. } //
  14264. function onTextureDispose(event) {
  14265. var texture = event.target;
  14266. texture.removeEventListener('dispose', onTextureDispose);
  14267. deallocateTexture(texture);
  14268. if (texture.isVideoTexture) {
  14269. _videoTextures.delete(texture);
  14270. }
  14271. info.memory.textures--;
  14272. }
  14273. function onRenderTargetDispose(event) {
  14274. var renderTarget = event.target;
  14275. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  14276. deallocateRenderTarget(renderTarget);
  14277. info.memory.textures--;
  14278. } //
  14279. function deallocateTexture(texture) {
  14280. var textureProperties = properties.get(texture);
  14281. if (textureProperties.__webglInit === undefined) return;
  14282. _gl.deleteTexture(textureProperties.__webglTexture);
  14283. properties.remove(texture);
  14284. }
  14285. function deallocateRenderTarget(renderTarget) {
  14286. var renderTargetProperties = properties.get(renderTarget);
  14287. var textureProperties = properties.get(renderTarget.texture);
  14288. if (!renderTarget) return;
  14289. if (textureProperties.__webglTexture !== undefined) {
  14290. _gl.deleteTexture(textureProperties.__webglTexture);
  14291. }
  14292. if (renderTarget.depthTexture) {
  14293. renderTarget.depthTexture.dispose();
  14294. }
  14295. if (renderTarget.isWebGLRenderTargetCube) {
  14296. for (var i = 0; i < 6; i++) {
  14297. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  14298. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  14299. }
  14300. } else {
  14301. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  14302. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  14303. }
  14304. if (renderTarget.isWebGLMultiviewRenderTarget) {
  14305. _gl.deleteTexture(renderTargetProperties.__webglColorTexture);
  14306. _gl.deleteTexture(renderTargetProperties.__webglDepthStencilTexture);
  14307. info.memory.textures -= 2;
  14308. for (var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i++) {
  14309. _gl.deleteFramebuffer(renderTargetProperties.__webglViewFramebuffers[i]);
  14310. }
  14311. }
  14312. properties.remove(renderTarget.texture);
  14313. properties.remove(renderTarget);
  14314. } //
  14315. var textureUnits = 0;
  14316. function resetTextureUnits() {
  14317. textureUnits = 0;
  14318. }
  14319. function allocateTextureUnit() {
  14320. var textureUnit = textureUnits;
  14321. if (textureUnit >= capabilities.maxTextures) {
  14322. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures);
  14323. }
  14324. textureUnits += 1;
  14325. return textureUnit;
  14326. } //
  14327. function setTexture2D(texture, slot) {
  14328. var textureProperties = properties.get(texture);
  14329. if (texture.isVideoTexture) updateVideoTexture(texture);
  14330. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14331. var image = texture.image;
  14332. if (image === undefined) {
  14333. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  14334. } else if (image.complete === false) {
  14335. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  14336. } else {
  14337. uploadTexture(textureProperties, texture, slot);
  14338. return;
  14339. }
  14340. }
  14341. state.activeTexture(33984 + slot);
  14342. state.bindTexture(3553, textureProperties.__webglTexture);
  14343. }
  14344. function setTexture2DArray(texture, slot) {
  14345. var textureProperties = properties.get(texture);
  14346. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14347. uploadTexture(textureProperties, texture, slot);
  14348. return;
  14349. }
  14350. state.activeTexture(33984 + slot);
  14351. state.bindTexture(35866, textureProperties.__webglTexture);
  14352. }
  14353. function setTexture3D(texture, slot) {
  14354. var textureProperties = properties.get(texture);
  14355. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14356. uploadTexture(textureProperties, texture, slot);
  14357. return;
  14358. }
  14359. state.activeTexture(33984 + slot);
  14360. state.bindTexture(32879, textureProperties.__webglTexture);
  14361. }
  14362. function setTextureCube(texture, slot) {
  14363. if (texture.image.length !== 6) return;
  14364. var textureProperties = properties.get(texture);
  14365. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  14366. initTexture(textureProperties, texture);
  14367. state.activeTexture(33984 + slot);
  14368. state.bindTexture(34067, textureProperties.__webglTexture);
  14369. _gl.pixelStorei(37440, texture.flipY);
  14370. var isCompressed = texture && texture.isCompressedTexture;
  14371. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14372. var cubeImage = [];
  14373. for (var i = 0; i < 6; i++) {
  14374. if (!isCompressed && !isDataTexture) {
  14375. cubeImage[i] = resizeImage(texture.image[i], false, true, capabilities.maxCubemapSize);
  14376. } else {
  14377. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14378. }
  14379. }
  14380. var image = cubeImage[0],
  14381. supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14382. glFormat = utils.convert(texture.format),
  14383. glType = utils.convert(texture.type),
  14384. glInternalFormat = getInternalFormat(glFormat, glType);
  14385. setTextureParameters(34067, texture, supportsMips);
  14386. var mipmaps;
  14387. if (isCompressed) {
  14388. for (var i = 0; i < 6; i++) {
  14389. mipmaps = cubeImage[i].mipmaps;
  14390. for (var j = 0; j < mipmaps.length; j++) {
  14391. var mipmap = mipmaps[j];
  14392. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14393. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14394. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14395. } else {
  14396. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14397. }
  14398. } else {
  14399. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14400. }
  14401. }
  14402. }
  14403. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14404. } else {
  14405. mipmaps = texture.mipmaps;
  14406. for (var i = 0; i < 6; i++) {
  14407. if (isDataTexture) {
  14408. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14409. for (var j = 0; j < mipmaps.length; j++) {
  14410. var mipmap = mipmaps[j];
  14411. var mipmapImage = mipmap.image[i].image;
  14412. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14413. }
  14414. } else {
  14415. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14416. for (var j = 0; j < mipmaps.length; j++) {
  14417. var mipmap = mipmaps[j];
  14418. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14419. }
  14420. }
  14421. }
  14422. textureProperties.__maxMipLevel = mipmaps.length;
  14423. }
  14424. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14425. // We assume images for cube map have the same size.
  14426. generateMipmap(34067, texture, image.width, image.height);
  14427. }
  14428. textureProperties.__version = texture.version;
  14429. if (texture.onUpdate) texture.onUpdate(texture);
  14430. } else {
  14431. state.activeTexture(33984 + slot);
  14432. state.bindTexture(34067, textureProperties.__webglTexture);
  14433. }
  14434. }
  14435. function setTextureCubeDynamic(texture, slot) {
  14436. state.activeTexture(33984 + slot);
  14437. state.bindTexture(34067, properties.get(texture).__webglTexture);
  14438. }
  14439. function setTextureParameters(textureType, texture, supportsMips) {
  14440. var extension;
  14441. if (supportsMips) {
  14442. _gl.texParameteri(textureType, 10242, utils.convert(texture.wrapS));
  14443. _gl.texParameteri(textureType, 10243, utils.convert(texture.wrapT));
  14444. if (textureType === 32879 || textureType === 35866) {
  14445. _gl.texParameteri(textureType, 32882, utils.convert(texture.wrapR));
  14446. }
  14447. _gl.texParameteri(textureType, 10240, utils.convert(texture.magFilter));
  14448. _gl.texParameteri(textureType, 10241, utils.convert(texture.minFilter));
  14449. } else {
  14450. _gl.texParameteri(textureType, 10242, 33071);
  14451. _gl.texParameteri(textureType, 10243, 33071);
  14452. if (textureType === 32879 || textureType === 35866) {
  14453. _gl.texParameteri(textureType, 32882, 33071);
  14454. }
  14455. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  14456. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  14457. }
  14458. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  14459. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  14460. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  14461. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  14462. }
  14463. }
  14464. extension = extensions.get('EXT_texture_filter_anisotropic');
  14465. if (extension) {
  14466. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  14467. if (texture.type === HalfFloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  14468. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  14469. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  14470. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  14471. }
  14472. }
  14473. }
  14474. function initTexture(textureProperties, texture) {
  14475. if (textureProperties.__webglInit === undefined) {
  14476. textureProperties.__webglInit = true;
  14477. texture.addEventListener('dispose', onTextureDispose);
  14478. textureProperties.__webglTexture = _gl.createTexture();
  14479. info.memory.textures++;
  14480. }
  14481. }
  14482. function uploadTexture(textureProperties, texture, slot) {
  14483. var textureType = 3553;
  14484. if (texture.isDataTexture2DArray) textureType = 35866;
  14485. if (texture.isDataTexture3D) textureType = 32879;
  14486. initTexture(textureProperties, texture);
  14487. state.activeTexture(33984 + slot);
  14488. state.bindTexture(textureType, textureProperties.__webglTexture);
  14489. _gl.pixelStorei(37440, texture.flipY);
  14490. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  14491. _gl.pixelStorei(3317, texture.unpackAlignment);
  14492. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  14493. var image = resizeImage(texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize);
  14494. var supportsMips = isPowerOfTwo(image) || capabilities.isWebGL2,
  14495. glFormat = utils.convert(texture.format),
  14496. glType = utils.convert(texture.type),
  14497. glInternalFormat = getInternalFormat(glFormat, glType);
  14498. setTextureParameters(textureType, texture, supportsMips);
  14499. var mipmap,
  14500. mipmaps = texture.mipmaps;
  14501. if (texture.isDepthTexture) {
  14502. // populate depth texture with dummy data
  14503. glInternalFormat = 6402;
  14504. if (texture.type === FloatType) {
  14505. if (!capabilities.isWebGL2) throw new Error('Float Depth Texture only supported in WebGL2.0');
  14506. glInternalFormat = 36012;
  14507. } else if (capabilities.isWebGL2) {
  14508. // WebGL 2.0 requires signed internalformat for glTexImage2D
  14509. glInternalFormat = 33189;
  14510. }
  14511. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  14512. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14513. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14514. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14515. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  14516. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  14517. texture.type = UnsignedShortType;
  14518. glType = utils.convert(texture.type);
  14519. }
  14520. } // Depth stencil textures need the DEPTH_STENCIL internal format
  14521. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14522. if (texture.format === DepthStencilFormat) {
  14523. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14524. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14525. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14526. if (texture.type !== UnsignedInt248Type) {
  14527. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  14528. texture.type = UnsignedInt248Type;
  14529. glType = utils.convert(texture.type);
  14530. }
  14531. }
  14532. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  14533. } else if (texture.isDataTexture) {
  14534. // use manually created mipmaps if available
  14535. // if there are no manual mipmaps
  14536. // set 0 level mipmap and then use GL to generate other mipmap levels
  14537. if (mipmaps.length > 0 && supportsMips) {
  14538. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14539. mipmap = mipmaps[i];
  14540. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14541. }
  14542. texture.generateMipmaps = false;
  14543. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14544. } else {
  14545. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  14546. textureProperties.__maxMipLevel = 0;
  14547. }
  14548. } else if (texture.isCompressedTexture) {
  14549. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14550. mipmap = mipmaps[i];
  14551. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  14552. if (state.getCompressedTextureFormats().indexOf(glFormat) > -1) {
  14553. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14554. } else {
  14555. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14556. }
  14557. } else {
  14558. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14559. }
  14560. }
  14561. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14562. } else if (texture.isDataTexture2DArray) {
  14563. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14564. textureProperties.__maxMipLevel = 0;
  14565. } else if (texture.isDataTexture3D) {
  14566. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14567. textureProperties.__maxMipLevel = 0;
  14568. } else {
  14569. // regular Texture (image, video, canvas)
  14570. // use manually created mipmaps if available
  14571. // if there are no manual mipmaps
  14572. // set 0 level mipmap and then use GL to generate other mipmap levels
  14573. if (mipmaps.length > 0 && supportsMips) {
  14574. for (var i = 0, il = mipmaps.length; i < il; i++) {
  14575. mipmap = mipmaps[i];
  14576. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  14577. }
  14578. texture.generateMipmaps = false;
  14579. textureProperties.__maxMipLevel = mipmaps.length - 1;
  14580. } else {
  14581. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  14582. textureProperties.__maxMipLevel = 0;
  14583. }
  14584. }
  14585. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14586. generateMipmap(3553, texture, image.width, image.height);
  14587. }
  14588. textureProperties.__version = texture.version;
  14589. if (texture.onUpdate) texture.onUpdate(texture);
  14590. } // Render targets
  14591. // Setup storage for target texture and bind it to correct framebuffer
  14592. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  14593. var glFormat = utils.convert(renderTarget.texture.format);
  14594. var glType = utils.convert(renderTarget.texture.type);
  14595. var glInternalFormat = getInternalFormat(glFormat, glType);
  14596. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14597. _gl.bindFramebuffer(36160, framebuffer);
  14598. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  14599. _gl.bindFramebuffer(36160, null);
  14600. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14601. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14602. _gl.bindRenderbuffer(36161, renderbuffer);
  14603. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14604. if (isMultisample) {
  14605. var samples = getRenderTargetSamples(renderTarget);
  14606. _gl.renderbufferStorageMultisample(36161, samples, 33189, renderTarget.width, renderTarget.height);
  14607. } else {
  14608. _gl.renderbufferStorage(36161, 33189, renderTarget.width, renderTarget.height);
  14609. }
  14610. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  14611. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14612. if (isMultisample) {
  14613. var samples = getRenderTargetSamples(renderTarget);
  14614. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  14615. } else {
  14616. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  14617. }
  14618. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  14619. } else {
  14620. var glFormat = utils.convert(renderTarget.texture.format);
  14621. var glType = utils.convert(renderTarget.texture.type);
  14622. var glInternalFormat = getInternalFormat(glFormat, glType);
  14623. if (isMultisample) {
  14624. var samples = getRenderTargetSamples(renderTarget);
  14625. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14626. } else {
  14627. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  14628. }
  14629. }
  14630. _gl.bindRenderbuffer(36161, null);
  14631. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14632. function setupDepthTexture(framebuffer, renderTarget) {
  14633. var isCube = renderTarget && renderTarget.isWebGLRenderTargetCube;
  14634. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14635. _gl.bindFramebuffer(36160, framebuffer);
  14636. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14637. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14638. } // upload an empty depth texture with framebuffer size
  14639. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14640. renderTarget.depthTexture.image.width = renderTarget.width;
  14641. renderTarget.depthTexture.image.height = renderTarget.height;
  14642. renderTarget.depthTexture.needsUpdate = true;
  14643. }
  14644. setTexture2D(renderTarget.depthTexture, 0);
  14645. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14646. if (renderTarget.depthTexture.format === DepthFormat) {
  14647. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  14648. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14649. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  14650. } else {
  14651. throw new Error('Unknown depthTexture format');
  14652. }
  14653. } // Setup GL resources for a non-texture depth buffer
  14654. function setupDepthRenderbuffer(renderTarget) {
  14655. var renderTargetProperties = properties.get(renderTarget);
  14656. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14657. if (renderTarget.depthTexture) {
  14658. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14659. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14660. } else {
  14661. if (isCube) {
  14662. renderTargetProperties.__webglDepthbuffer = [];
  14663. for (var i = 0; i < 6; i++) {
  14664. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  14665. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14666. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget);
  14667. }
  14668. } else {
  14669. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14670. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14671. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget);
  14672. }
  14673. }
  14674. _gl.bindFramebuffer(36160, null);
  14675. } // Set up GL resources for the render target
  14676. function setupRenderTarget(renderTarget) {
  14677. var renderTargetProperties = properties.get(renderTarget);
  14678. var textureProperties = properties.get(renderTarget.texture);
  14679. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14680. textureProperties.__webglTexture = _gl.createTexture();
  14681. info.memory.textures++;
  14682. var isCube = renderTarget.isWebGLRenderTargetCube === true;
  14683. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  14684. var isMultiview = renderTarget.isWebGLMultiviewRenderTarget === true;
  14685. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2; // Setup framebuffer
  14686. if (isCube) {
  14687. renderTargetProperties.__webglFramebuffer = [];
  14688. for (var i = 0; i < 6; i++) {
  14689. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14690. }
  14691. } else {
  14692. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14693. if (isMultisample) {
  14694. if (capabilities.isWebGL2) {
  14695. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14696. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14697. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  14698. var glFormat = utils.convert(renderTarget.texture.format);
  14699. var glType = utils.convert(renderTarget.texture.type);
  14700. var glInternalFormat = getInternalFormat(glFormat, glType);
  14701. var samples = getRenderTargetSamples(renderTarget);
  14702. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14703. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  14704. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  14705. _gl.bindRenderbuffer(36161, null);
  14706. if (renderTarget.depthBuffer) {
  14707. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14708. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14709. }
  14710. _gl.bindFramebuffer(36160, null);
  14711. } else {
  14712. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14713. }
  14714. } else if (isMultiview) {
  14715. var width = renderTarget.width;
  14716. var height = renderTarget.height;
  14717. var numViews = renderTarget.numViews;
  14718. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  14719. var ext = extensions.get('OVR_multiview2');
  14720. info.memory.textures += 2;
  14721. var colorTexture = _gl.createTexture();
  14722. _gl.bindTexture(35866, colorTexture);
  14723. _gl.texParameteri(35866, 10240, 9728);
  14724. _gl.texParameteri(35866, 10241, 9728);
  14725. _gl.texImage3D(35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null);
  14726. ext.framebufferTextureMultiviewOVR(36160, 36064, colorTexture, 0, 0, numViews);
  14727. var depthStencilTexture = _gl.createTexture();
  14728. _gl.bindTexture(35866, depthStencilTexture);
  14729. _gl.texParameteri(35866, 10240, 9728);
  14730. _gl.texParameteri(35866, 10241, 9728);
  14731. _gl.texImage3D(35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null);
  14732. ext.framebufferTextureMultiviewOVR(36160, 33306, depthStencilTexture, 0, 0, numViews);
  14733. var viewFramebuffers = new Array(numViews);
  14734. for (var i = 0; i < numViews; ++i) {
  14735. viewFramebuffers[i] = _gl.createFramebuffer();
  14736. _gl.bindFramebuffer(36160, viewFramebuffers[i]);
  14737. _gl.framebufferTextureLayer(36160, 36064, colorTexture, 0, i);
  14738. }
  14739. renderTargetProperties.__webglColorTexture = colorTexture;
  14740. renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
  14741. renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;
  14742. _gl.bindFramebuffer(36160, null);
  14743. _gl.bindTexture(35866, null);
  14744. }
  14745. } // Setup color buffer
  14746. if (isCube) {
  14747. state.bindTexture(34067, textureProperties.__webglTexture);
  14748. setTextureParameters(34067, renderTarget.texture, supportsMips);
  14749. for (var i = 0; i < 6; i++) {
  14750. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  14751. }
  14752. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14753. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  14754. }
  14755. state.bindTexture(34067, null);
  14756. } else if (!isMultiview) {
  14757. state.bindTexture(3553, textureProperties.__webglTexture);
  14758. setTextureParameters(3553, renderTarget.texture, supportsMips);
  14759. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  14760. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14761. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  14762. }
  14763. state.bindTexture(3553, null);
  14764. } // Setup depth and stencil buffers
  14765. if (renderTarget.depthBuffer) {
  14766. setupDepthRenderbuffer(renderTarget);
  14767. }
  14768. }
  14769. function updateRenderTargetMipmap(renderTarget) {
  14770. var texture = renderTarget.texture;
  14771. var supportsMips = isPowerOfTwo(renderTarget) || capabilities.isWebGL2;
  14772. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14773. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  14774. var webglTexture = properties.get(texture).__webglTexture;
  14775. state.bindTexture(target, webglTexture);
  14776. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  14777. state.bindTexture(target, null);
  14778. }
  14779. }
  14780. function updateMultisampleRenderTarget(renderTarget) {
  14781. if (renderTarget.isWebGLMultisampleRenderTarget) {
  14782. if (capabilities.isWebGL2) {
  14783. var renderTargetProperties = properties.get(renderTarget);
  14784. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  14785. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  14786. var width = renderTarget.width;
  14787. var height = renderTarget.height;
  14788. var mask = 16384;
  14789. if (renderTarget.depthBuffer) mask |= 256;
  14790. if (renderTarget.stencilBuffer) mask |= 1024;
  14791. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  14792. } else {
  14793. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14794. }
  14795. }
  14796. }
  14797. function getRenderTargetSamples(renderTarget) {
  14798. return capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(capabilities.maxSamples, renderTarget.samples) : 0;
  14799. }
  14800. function updateVideoTexture(texture) {
  14801. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14802. if (_videoTextures.get(texture) !== frame) {
  14803. _videoTextures.set(texture, frame);
  14804. texture.update();
  14805. }
  14806. } // backwards compatibility
  14807. var warnedTexture2D = false;
  14808. var warnedTextureCube = false;
  14809. function safeSetTexture2D(texture, slot) {
  14810. if (texture && texture.isWebGLRenderTarget) {
  14811. if (warnedTexture2D === false) {
  14812. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  14813. warnedTexture2D = true;
  14814. }
  14815. texture = texture.texture;
  14816. }
  14817. setTexture2D(texture, slot);
  14818. }
  14819. function safeSetTextureCube(texture, slot) {
  14820. if (texture && texture.isWebGLRenderTargetCube) {
  14821. if (warnedTextureCube === false) {
  14822. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  14823. warnedTextureCube = true;
  14824. }
  14825. texture = texture.texture;
  14826. } // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  14827. // TODO: unify these code paths
  14828. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  14829. // CompressedTexture can have Array in image :/
  14830. // this function alone should take care of cube textures
  14831. setTextureCube(texture, slot);
  14832. } else {
  14833. // assumed: texture property of THREE.WebGLRenderTargetCube
  14834. setTextureCubeDynamic(texture, slot);
  14835. }
  14836. } //
  14837. this.allocateTextureUnit = allocateTextureUnit;
  14838. this.resetTextureUnits = resetTextureUnits;
  14839. this.setTexture2D = setTexture2D;
  14840. this.setTexture2DArray = setTexture2DArray;
  14841. this.setTexture3D = setTexture3D;
  14842. this.setTextureCube = setTextureCube;
  14843. this.setTextureCubeDynamic = setTextureCubeDynamic;
  14844. this.setupRenderTarget = setupRenderTarget;
  14845. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14846. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14847. this.safeSetTexture2D = safeSetTexture2D;
  14848. this.safeSetTextureCube = safeSetTextureCube;
  14849. }
  14850. /**
  14851. * @author thespite / http://www.twitter.com/thespite
  14852. */
  14853. function WebGLUtils(gl, extensions, capabilities) {
  14854. function convert(p) {
  14855. var extension;
  14856. if (p === RepeatWrapping) return 10497;
  14857. if (p === ClampToEdgeWrapping) return 33071;
  14858. if (p === MirroredRepeatWrapping) return 33648;
  14859. if (p === NearestFilter) return 9728;
  14860. if (p === NearestMipmapNearestFilter) return 9984;
  14861. if (p === NearestMipmapLinearFilter) return 9986;
  14862. if (p === LinearFilter) return 9729;
  14863. if (p === LinearMipmapNearestFilter) return 9985;
  14864. if (p === LinearMipmapLinearFilter) return 9987;
  14865. if (p === UnsignedByteType) return 5121;
  14866. if (p === UnsignedShort4444Type) return 32819;
  14867. if (p === UnsignedShort5551Type) return 32820;
  14868. if (p === UnsignedShort565Type) return 33635;
  14869. if (p === ByteType) return 5120;
  14870. if (p === ShortType) return 5122;
  14871. if (p === UnsignedShortType) return 5123;
  14872. if (p === IntType) return 5124;
  14873. if (p === UnsignedIntType) return 5125;
  14874. if (p === FloatType) return 5126;
  14875. if (p === HalfFloatType) {
  14876. if (capabilities.isWebGL2) return 5131;
  14877. extension = extensions.get('OES_texture_half_float');
  14878. if (extension !== null) return extension.HALF_FLOAT_OES;
  14879. }
  14880. if (p === AlphaFormat) return 6406;
  14881. if (p === RGBFormat) return 6407;
  14882. if (p === RGBAFormat) return 6408;
  14883. if (p === LuminanceFormat) return 6409;
  14884. if (p === LuminanceAlphaFormat) return 6410;
  14885. if (p === DepthFormat) return 6402;
  14886. if (p === DepthStencilFormat) return 34041;
  14887. if (p === RedFormat) return 6403;
  14888. if (p === AddEquation) return 32774;
  14889. if (p === SubtractEquation) return 32778;
  14890. if (p === ReverseSubtractEquation) return 32779;
  14891. if (p === ZeroFactor) return 0;
  14892. if (p === OneFactor) return 1;
  14893. if (p === SrcColorFactor) return 768;
  14894. if (p === OneMinusSrcColorFactor) return 769;
  14895. if (p === SrcAlphaFactor) return 770;
  14896. if (p === OneMinusSrcAlphaFactor) return 771;
  14897. if (p === DstAlphaFactor) return 772;
  14898. if (p === OneMinusDstAlphaFactor) return 773;
  14899. if (p === DstColorFactor) return 774;
  14900. if (p === OneMinusDstColorFactor) return 775;
  14901. if (p === SrcAlphaSaturateFactor) return 776;
  14902. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14903. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14904. if (extension !== null) {
  14905. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14906. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14907. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14908. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14909. }
  14910. }
  14911. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14912. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14913. if (extension !== null) {
  14914. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14915. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14916. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14917. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14918. }
  14919. }
  14920. if (p === RGB_ETC1_Format) {
  14921. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14922. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14923. }
  14924. 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) {
  14925. extension = extensions.get('WEBGL_compressed_texture_astc');
  14926. if (extension !== null) {
  14927. return p;
  14928. }
  14929. }
  14930. if (p === MinEquation || p === MaxEquation) {
  14931. if (capabilities.isWebGL2) {
  14932. if (p === MinEquation) return 32775;
  14933. if (p === MaxEquation) return 32776;
  14934. }
  14935. extension = extensions.get('EXT_blend_minmax');
  14936. if (extension !== null) {
  14937. if (p === MinEquation) return extension.MIN_EXT;
  14938. if (p === MaxEquation) return extension.MAX_EXT;
  14939. }
  14940. }
  14941. if (p === UnsignedInt248Type) {
  14942. if (capabilities.isWebGL2) return 34042;
  14943. extension = extensions.get('WEBGL_depth_texture');
  14944. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  14945. }
  14946. return 0;
  14947. }
  14948. return {
  14949. convert: convert
  14950. };
  14951. }
  14952. /**
  14953. * @author fernandojsg / http://fernandojsg.com
  14954. * @author Takahiro https://github.com/takahirox
  14955. */
  14956. function WebGLMultiviewRenderTarget(width, height, numViews, options) {
  14957. WebGLRenderTarget.call(this, width, height, options);
  14958. this.depthBuffer = false;
  14959. this.stencilBuffer = false;
  14960. this.numViews = numViews;
  14961. }
  14962. WebGLMultiviewRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  14963. constructor: WebGLMultiviewRenderTarget,
  14964. isWebGLMultiviewRenderTarget: true,
  14965. copy: function (source) {
  14966. WebGLRenderTarget.prototype.copy.call(this, source);
  14967. this.numViews = source.numViews;
  14968. return this;
  14969. },
  14970. setNumViews: function (numViews) {
  14971. if (this.numViews !== numViews) {
  14972. this.numViews = numViews;
  14973. this.dispose();
  14974. }
  14975. return this;
  14976. }
  14977. });
  14978. /**
  14979. * @author fernandojsg / http://fernandojsg.com
  14980. * @author Takahiro https://github.com/takahirox
  14981. */
  14982. function WebGLMultiview(renderer, gl) {
  14983. var DEFAULT_NUMVIEWS = 2;
  14984. var extensions = renderer.extensions;
  14985. var properties = renderer.properties;
  14986. var renderTarget, currentRenderTarget;
  14987. var mat3, mat4, cameraArray, renderSize;
  14988. var available;
  14989. var maxNumViews = 0; //
  14990. function isAvailable() {
  14991. if (available === undefined) {
  14992. var extension = extensions.get('OVR_multiview2');
  14993. available = extension !== null && gl.getContextAttributes().antialias === false;
  14994. if (available) {
  14995. maxNumViews = gl.getParameter(extension.MAX_VIEWS_OVR);
  14996. renderTarget = new WebGLMultiviewRenderTarget(0, 0, DEFAULT_NUMVIEWS);
  14997. renderSize = new Vector2();
  14998. mat4 = [];
  14999. mat3 = [];
  15000. cameraArray = [];
  15001. for (var i = 0; i < maxNumViews; i++) {
  15002. mat4[i] = new Matrix4();
  15003. mat3[i] = new Matrix3();
  15004. }
  15005. }
  15006. }
  15007. return available;
  15008. }
  15009. function getCameraArray(camera) {
  15010. if (camera.isArrayCamera) return camera.cameras;
  15011. cameraArray[0] = camera;
  15012. return cameraArray;
  15013. }
  15014. function updateCameraProjectionMatricesUniform(camera, uniforms) {
  15015. var cameras = getCameraArray(camera);
  15016. for (var i = 0; i < cameras.length; i++) {
  15017. mat4[i].copy(cameras[i].projectionMatrix);
  15018. }
  15019. uniforms.setValue(gl, 'projectionMatrices', mat4);
  15020. }
  15021. function updateCameraViewMatricesUniform(camera, uniforms) {
  15022. var cameras = getCameraArray(camera);
  15023. for (var i = 0; i < cameras.length; i++) {
  15024. mat4[i].copy(cameras[i].matrixWorldInverse);
  15025. }
  15026. uniforms.setValue(gl, 'viewMatrices', mat4);
  15027. }
  15028. function updateObjectMatricesUniforms(object, camera, uniforms) {
  15029. var cameras = getCameraArray(camera);
  15030. for (var i = 0; i < cameras.length; i++) {
  15031. mat4[i].multiplyMatrices(cameras[i].matrixWorldInverse, object.matrixWorld);
  15032. mat3[i].getNormalMatrix(mat4[i]);
  15033. }
  15034. uniforms.setValue(gl, 'modelViewMatrices', mat4);
  15035. uniforms.setValue(gl, 'normalMatrices', mat3);
  15036. }
  15037. function isMultiviewCompatible(camera) {
  15038. if (camera.isArrayCamera === undefined) return true;
  15039. var cameras = camera.cameras;
  15040. if (cameras.length > maxNumViews) return false;
  15041. for (var i = 1, il = cameras.length; i < il; i++) {
  15042. if (cameras[0].viewport.z !== cameras[i].viewport.z || cameras[0].viewport.w !== cameras[i].viewport.w) return false;
  15043. }
  15044. return true;
  15045. }
  15046. function resizeRenderTarget(camera) {
  15047. if (currentRenderTarget) {
  15048. renderSize.set(currentRenderTarget.width, currentRenderTarget.height);
  15049. } else {
  15050. renderer.getDrawingBufferSize(renderSize);
  15051. }
  15052. if (camera.isArrayCamera) {
  15053. var viewport = camera.cameras[0].viewport;
  15054. renderTarget.setSize(viewport.z, viewport.w);
  15055. renderTarget.setNumViews(camera.cameras.length);
  15056. } else {
  15057. renderTarget.setSize(renderSize.x, renderSize.y);
  15058. renderTarget.setNumViews(DEFAULT_NUMVIEWS);
  15059. }
  15060. }
  15061. function attachCamera(camera) {
  15062. if (isMultiviewCompatible(camera) === false) return;
  15063. currentRenderTarget = renderer.getRenderTarget();
  15064. resizeRenderTarget(camera);
  15065. renderer.setRenderTarget(renderTarget);
  15066. }
  15067. function detachCamera(camera) {
  15068. if (renderTarget !== renderer.getRenderTarget()) return;
  15069. renderer.setRenderTarget(currentRenderTarget);
  15070. flush(camera);
  15071. }
  15072. function flush(camera) {
  15073. var srcRenderTarget = renderTarget;
  15074. var numViews = srcRenderTarget.numViews;
  15075. var srcFramebuffers = properties.get(srcRenderTarget).__webglViewFramebuffers;
  15076. var viewWidth = srcRenderTarget.width;
  15077. var viewHeight = srcRenderTarget.height;
  15078. if (camera.isArrayCamera) {
  15079. for (var i = 0; i < numViews; i++) {
  15080. var viewport = camera.cameras[i].viewport;
  15081. var x1 = viewport.x;
  15082. var y1 = viewport.y;
  15083. var x2 = x1 + viewport.z;
  15084. var y2 = y1 + viewport.w;
  15085. gl.bindFramebuffer(36008, srcFramebuffers[i]);
  15086. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728);
  15087. }
  15088. } else {
  15089. gl.bindFramebuffer(36008, srcFramebuffers[0]);
  15090. gl.blitFramebuffer(0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728);
  15091. }
  15092. }
  15093. this.isAvailable = isAvailable;
  15094. this.attachCamera = attachCamera;
  15095. this.detachCamera = detachCamera;
  15096. this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
  15097. this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
  15098. this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;
  15099. }
  15100. /**
  15101. * @author mrdoob / http://mrdoob.com/
  15102. */
  15103. function Group() {
  15104. Object3D.call(this);
  15105. this.type = 'Group';
  15106. }
  15107. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  15108. constructor: Group,
  15109. isGroup: true
  15110. });
  15111. /**
  15112. * @author mrdoob / http://mrdoob.com/
  15113. */
  15114. function ArrayCamera(array) {
  15115. PerspectiveCamera.call(this);
  15116. this.cameras = array || [];
  15117. }
  15118. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  15119. constructor: ArrayCamera,
  15120. isArrayCamera: true
  15121. });
  15122. /**
  15123. * @author jsantell / https://www.jsantell.com/
  15124. * @author mrdoob / http://mrdoob.com/
  15125. */
  15126. var cameraLPos = new Vector3();
  15127. var cameraRPos = new Vector3();
  15128. /**
  15129. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15130. * the cameras' projection and world matrices have already been set.
  15131. * And that near and far planes are identical for both cameras.
  15132. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15133. */
  15134. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15135. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15136. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15137. var ipd = cameraLPos.distanceTo(cameraRPos);
  15138. var projL = cameraL.projectionMatrix.elements;
  15139. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15140. // most likely identical top and bottom frustum extents.
  15141. // Use the left camera for these values.
  15142. var near = projL[14] / (projL[10] - 1);
  15143. var far = projL[14] / (projL[10] + 1);
  15144. var topFov = (projL[9] + 1) / projL[5];
  15145. var bottomFov = (projL[9] - 1) / projL[5];
  15146. var leftFov = (projL[8] - 1) / projL[0];
  15147. var rightFov = (projR[8] + 1) / projR[0];
  15148. var left = near * leftFov;
  15149. var right = near * rightFov; // Calculate the new camera's position offset from the
  15150. // left camera. xOffset should be roughly half `ipd`.
  15151. var zOffset = ipd / (-leftFov + rightFov);
  15152. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15153. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15154. camera.translateX(xOffset);
  15155. camera.translateZ(zOffset);
  15156. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15157. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  15158. // the values so that the near plane's position does not change in world space,
  15159. // although must now be relative to the new union camera.
  15160. var near2 = near + zOffset;
  15161. var far2 = far + zOffset;
  15162. var left2 = left - xOffset;
  15163. var right2 = right + (ipd - xOffset);
  15164. var top2 = topFov * far / far2 * near2;
  15165. var bottom2 = bottomFov * far / far2 * near2;
  15166. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15167. }
  15168. /**
  15169. * @author mrdoob / http://mrdoob.com/
  15170. */
  15171. function WebVRManager(renderer) {
  15172. var renderWidth, renderHeight;
  15173. var scope = this;
  15174. var device = null;
  15175. var frameData = null;
  15176. var poseTarget = null;
  15177. var controllers = [];
  15178. var standingMatrix = new Matrix4();
  15179. var standingMatrixInverse = new Matrix4();
  15180. var framebufferScaleFactor = 1.0;
  15181. var referenceSpaceType = 'local-floor';
  15182. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  15183. frameData = new window.VRFrameData();
  15184. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  15185. }
  15186. var matrixWorldInverse = new Matrix4();
  15187. var tempQuaternion = new Quaternion();
  15188. var tempPosition = new Vector3();
  15189. var cameraL = new PerspectiveCamera();
  15190. cameraL.viewport = new Vector4();
  15191. cameraL.layers.enable(1);
  15192. var cameraR = new PerspectiveCamera();
  15193. cameraR.viewport = new Vector4();
  15194. cameraR.layers.enable(2);
  15195. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15196. cameraVR.layers.enable(1);
  15197. cameraVR.layers.enable(2); //
  15198. function isPresenting() {
  15199. return device !== null && device.isPresenting === true;
  15200. }
  15201. var currentSize = new Vector2(),
  15202. currentPixelRatio;
  15203. function onVRDisplayPresentChange() {
  15204. if (isPresenting()) {
  15205. var eyeParameters = device.getEyeParameters('left');
  15206. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  15207. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  15208. currentPixelRatio = renderer.getPixelRatio();
  15209. renderer.getSize(currentSize);
  15210. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  15211. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  15212. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  15213. animation.start();
  15214. scope.dispatchEvent({
  15215. type: 'sessionstart'
  15216. });
  15217. } else {
  15218. if (scope.enabled) {
  15219. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  15220. }
  15221. animation.stop();
  15222. scope.dispatchEvent({
  15223. type: 'sessionend'
  15224. });
  15225. }
  15226. } //
  15227. var triggers = [];
  15228. function findGamepad(id) {
  15229. var gamepads = navigator.getGamepads && navigator.getGamepads();
  15230. for (var i = 0, j = 0, l = gamepads.length; i < l; i++) {
  15231. var gamepad = gamepads[i];
  15232. 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'))) {
  15233. if (j === id) return gamepad;
  15234. j++;
  15235. }
  15236. }
  15237. }
  15238. function updateControllers() {
  15239. for (var i = 0; i < controllers.length; i++) {
  15240. var controller = controllers[i];
  15241. var gamepad = findGamepad(i);
  15242. if (gamepad !== undefined && gamepad.pose !== undefined) {
  15243. if (gamepad.pose === null) return; // Pose
  15244. var pose = gamepad.pose;
  15245. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  15246. if (pose.position !== null) controller.position.fromArray(pose.position);
  15247. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  15248. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  15249. controller.matrix.premultiply(standingMatrix);
  15250. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  15251. controller.matrixWorldNeedsUpdate = true;
  15252. controller.visible = true; // Trigger
  15253. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  15254. if (triggers[i] === undefined) triggers[i] = false;
  15255. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  15256. triggers[i] = gamepad.buttons[buttonId].pressed;
  15257. if (triggers[i] === true) {
  15258. controller.dispatchEvent({
  15259. type: 'selectstart'
  15260. });
  15261. } else {
  15262. controller.dispatchEvent({
  15263. type: 'selectend'
  15264. });
  15265. controller.dispatchEvent({
  15266. type: 'select'
  15267. });
  15268. }
  15269. }
  15270. } else {
  15271. controller.visible = false;
  15272. }
  15273. }
  15274. }
  15275. function updateViewportFromBounds(viewport, bounds) {
  15276. if (bounds !== null && bounds.length === 4) {
  15277. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  15278. }
  15279. } //
  15280. this.enabled = false;
  15281. this.getController = function (id) {
  15282. var controller = controllers[id];
  15283. if (controller === undefined) {
  15284. controller = new Group();
  15285. controller.matrixAutoUpdate = false;
  15286. controller.visible = false;
  15287. controllers[id] = controller;
  15288. }
  15289. return controller;
  15290. };
  15291. this.getDevice = function () {
  15292. return device;
  15293. };
  15294. this.setDevice = function (value) {
  15295. if (value !== undefined) device = value;
  15296. animation.setContext(value);
  15297. };
  15298. this.setFramebufferScaleFactor = function (value) {
  15299. framebufferScaleFactor = value;
  15300. };
  15301. this.setReferenceSpaceType = function (value) {
  15302. referenceSpaceType = value;
  15303. };
  15304. this.setPoseTarget = function (object) {
  15305. if (object !== undefined) poseTarget = object;
  15306. };
  15307. this.getCamera = function (camera) {
  15308. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  15309. if (isPresenting() === false) {
  15310. camera.position.set(0, userHeight, 0);
  15311. camera.rotation.set(0, 0, 0);
  15312. return camera;
  15313. }
  15314. device.depthNear = camera.near;
  15315. device.depthFar = camera.far;
  15316. device.getFrameData(frameData); //
  15317. if (referenceSpaceType === 'local-floor') {
  15318. var stageParameters = device.stageParameters;
  15319. if (stageParameters) {
  15320. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  15321. } else {
  15322. standingMatrix.makeTranslation(0, userHeight, 0);
  15323. }
  15324. }
  15325. var pose = frameData.pose;
  15326. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  15327. poseObject.matrix.copy(standingMatrix);
  15328. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  15329. if (pose.orientation !== null) {
  15330. tempQuaternion.fromArray(pose.orientation);
  15331. poseObject.quaternion.multiply(tempQuaternion);
  15332. }
  15333. if (pose.position !== null) {
  15334. tempQuaternion.setFromRotationMatrix(standingMatrix);
  15335. tempPosition.fromArray(pose.position);
  15336. tempPosition.applyQuaternion(tempQuaternion);
  15337. poseObject.position.add(tempPosition);
  15338. }
  15339. poseObject.updateMatrixWorld(); //
  15340. cameraL.near = camera.near;
  15341. cameraR.near = camera.near;
  15342. cameraL.far = camera.far;
  15343. cameraR.far = camera.far;
  15344. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  15345. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  15346. standingMatrixInverse.getInverse(standingMatrix);
  15347. if (referenceSpaceType === 'local-floor') {
  15348. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  15349. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  15350. }
  15351. var parent = poseObject.parent;
  15352. if (parent !== null) {
  15353. matrixWorldInverse.getInverse(parent.matrixWorld);
  15354. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  15355. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  15356. } // envMap and Mirror needs camera.matrixWorld
  15357. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  15358. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  15359. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  15360. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  15361. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  15362. var layers = device.getLayers();
  15363. if (layers.length) {
  15364. var layer = layers[0];
  15365. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  15366. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  15367. }
  15368. updateControllers();
  15369. return cameraVR;
  15370. };
  15371. this.getStandingMatrix = function () {
  15372. return standingMatrix;
  15373. };
  15374. this.isPresenting = isPresenting; // Animation Loop
  15375. var animation = new WebGLAnimation();
  15376. this.setAnimationLoop = function (callback) {
  15377. animation.setAnimationLoop(callback);
  15378. if (isPresenting()) animation.start();
  15379. };
  15380. this.submitFrame = function () {
  15381. if (isPresenting()) device.submitFrame();
  15382. };
  15383. this.dispose = function () {
  15384. if (typeof window !== 'undefined') {
  15385. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  15386. }
  15387. }; // DEPRECATED
  15388. this.setFrameOfReferenceType = function () {
  15389. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  15390. };
  15391. }
  15392. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  15393. /**
  15394. * @author mrdoob / http://mrdoob.com/
  15395. */
  15396. function WebXRManager(renderer, gl) {
  15397. var scope = this;
  15398. var session = null; // var framebufferScaleFactor = 1.0;
  15399. var referenceSpace = null;
  15400. var referenceSpaceType = 'local-floor';
  15401. var pose = null;
  15402. var controllers = [];
  15403. var inputSources = [];
  15404. function isPresenting() {
  15405. return session !== null && referenceSpace !== null;
  15406. } //
  15407. var cameraL = new PerspectiveCamera();
  15408. cameraL.layers.enable(1);
  15409. cameraL.viewport = new Vector4();
  15410. var cameraR = new PerspectiveCamera();
  15411. cameraR.layers.enable(2);
  15412. cameraR.viewport = new Vector4();
  15413. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  15414. cameraVR.layers.enable(1);
  15415. cameraVR.layers.enable(2); //
  15416. this.enabled = false;
  15417. this.getController = function (id) {
  15418. var controller = controllers[id];
  15419. if (controller === undefined) {
  15420. controller = new Group();
  15421. controller.matrixAutoUpdate = false;
  15422. controller.visible = false;
  15423. controllers[id] = controller;
  15424. }
  15425. return controller;
  15426. }; //
  15427. function onSessionEvent(event) {
  15428. for (var i = 0; i < controllers.length; i++) {
  15429. if (inputSources[i] === event.inputSource) {
  15430. controllers[i].dispatchEvent({
  15431. type: event.type
  15432. });
  15433. }
  15434. }
  15435. }
  15436. function onSessionEnd() {
  15437. renderer.setFramebuffer(null);
  15438. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  15439. animation.stop();
  15440. scope.dispatchEvent({
  15441. type: 'sessionend'
  15442. });
  15443. }
  15444. function onRequestReferenceSpace(value) {
  15445. referenceSpace = value;
  15446. animation.setContext(session);
  15447. animation.start();
  15448. scope.dispatchEvent({
  15449. type: 'sessionstart'
  15450. });
  15451. }
  15452. this.setFramebufferScaleFactor = function ()
  15453. /* value */
  15454. {// framebufferScaleFactor = value;
  15455. };
  15456. this.setReferenceSpaceType = function (value) {
  15457. referenceSpaceType = value;
  15458. };
  15459. this.getSession = function () {
  15460. return session;
  15461. };
  15462. this.setSession = function (value) {
  15463. session = value;
  15464. if (session !== null) {
  15465. session.addEventListener('select', onSessionEvent);
  15466. session.addEventListener('selectstart', onSessionEvent);
  15467. session.addEventListener('selectend', onSessionEvent);
  15468. session.addEventListener('end', onSessionEnd); // eslint-disable-next-line no-undef
  15469. session.updateRenderState({
  15470. baseLayer: new XRWebGLLayer(session, gl)
  15471. });
  15472. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  15473. inputSources = session.inputSources;
  15474. session.addEventListener('inputsourceschange', function () {
  15475. inputSources = session.inputSources;
  15476. console.log(inputSources);
  15477. for (var i = 0; i < controllers.length; i++) {
  15478. var controller = controllers[i];
  15479. controller.userData.inputSource = inputSources[i];
  15480. }
  15481. });
  15482. }
  15483. };
  15484. function updateCamera(camera, parent) {
  15485. if (parent === null) {
  15486. camera.matrixWorld.copy(camera.matrix);
  15487. } else {
  15488. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15489. }
  15490. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  15491. }
  15492. this.getCamera = function (camera) {
  15493. if (isPresenting()) {
  15494. var parent = camera.parent;
  15495. var cameras = cameraVR.cameras;
  15496. updateCamera(cameraVR, parent);
  15497. for (var i = 0; i < cameras.length; i++) {
  15498. updateCamera(cameras[i], parent);
  15499. } // update camera and its children
  15500. camera.matrixWorld.copy(cameraVR.matrixWorld);
  15501. var children = camera.children;
  15502. for (var i = 0, l = children.length; i < l; i++) {
  15503. children[i].updateMatrixWorld(true);
  15504. }
  15505. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15506. return cameraVR;
  15507. }
  15508. return camera;
  15509. };
  15510. this.isPresenting = isPresenting; // Animation Loop
  15511. var onAnimationFrameCallback = null;
  15512. function onAnimationFrame(time, frame) {
  15513. pose = frame.getViewerPose(referenceSpace);
  15514. if (pose !== null) {
  15515. var views = pose.views;
  15516. var baseLayer = session.renderState.baseLayer;
  15517. renderer.setFramebuffer(baseLayer.framebuffer);
  15518. for (var i = 0; i < views.length; i++) {
  15519. var view = views[i];
  15520. var viewport = baseLayer.getViewport(view);
  15521. var viewMatrix = view.transform.inverse.matrix;
  15522. var camera = cameraVR.cameras[i];
  15523. camera.matrix.fromArray(viewMatrix).getInverse(camera.matrix);
  15524. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15525. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15526. if (i === 0) {
  15527. cameraVR.matrix.copy(camera.matrix);
  15528. }
  15529. }
  15530. } //
  15531. for (var i = 0; i < controllers.length; i++) {
  15532. var controller = controllers[i];
  15533. var inputSource = inputSources[i];
  15534. if (inputSource) {
  15535. var inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  15536. if (inputPose !== null) {
  15537. controller.matrix.fromArray(inputPose.transform.matrix);
  15538. controller.matrix.decompose(controller.position, controller.rotation, controller.scale);
  15539. controller.visible = true;
  15540. continue;
  15541. }
  15542. }
  15543. controller.visible = false;
  15544. }
  15545. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15546. }
  15547. var animation = new WebGLAnimation();
  15548. animation.setAnimationLoop(onAnimationFrame);
  15549. this.setAnimationLoop = function (callback) {
  15550. onAnimationFrameCallback = callback;
  15551. };
  15552. this.dispose = function () {}; // DEPRECATED
  15553. this.getStandingMatrix = function () {
  15554. console.warn('THREE.WebXRManager: getStandingMatrix() is no longer needed.');
  15555. return new Matrix4();
  15556. };
  15557. this.getDevice = function () {
  15558. console.warn('THREE.WebXRManager: getDevice() has been deprecated.');
  15559. };
  15560. this.setDevice = function () {
  15561. console.warn('THREE.WebXRManager: setDevice() has been deprecated.');
  15562. };
  15563. this.setFrameOfReferenceType = function () {
  15564. console.warn('THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.');
  15565. };
  15566. this.submitFrame = function () {};
  15567. }
  15568. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  15569. /**
  15570. * @author supereggbert / http://www.paulbrunt.co.uk/
  15571. * @author mrdoob / http://mrdoob.com/
  15572. * @author alteredq / http://alteredqualia.com/
  15573. * @author szimek / https://github.com/szimek/
  15574. * @author tschw
  15575. */
  15576. function WebGLRenderer(parameters) {
  15577. parameters = parameters || {};
  15578. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  15579. _context = parameters.context !== undefined ? parameters.context : null,
  15580. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15581. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15582. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15583. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15584. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15585. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15586. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15587. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15588. var currentRenderList = null;
  15589. var currentRenderState = null; // public properties
  15590. this.domElement = _canvas; // Debug configuration container
  15591. this.debug = {
  15592. /**
  15593. * Enables error checking and reporting when shader programs are being compiled
  15594. * @type {boolean}
  15595. */
  15596. checkShaderErrors: true
  15597. }; // clearing
  15598. this.autoClear = true;
  15599. this.autoClearColor = true;
  15600. this.autoClearDepth = true;
  15601. this.autoClearStencil = true; // scene graph
  15602. this.sortObjects = true; // user-defined clipping
  15603. this.clippingPlanes = [];
  15604. this.localClippingEnabled = false; // physically based shading
  15605. this.gammaFactor = 2.0; // for backwards compatibility
  15606. this.gammaInput = false;
  15607. this.gammaOutput = false; // physical lights
  15608. this.physicallyCorrectLights = false; // tone mapping
  15609. this.toneMapping = LinearToneMapping;
  15610. this.toneMappingExposure = 1.0;
  15611. this.toneMappingWhitePoint = 1.0; // morphs
  15612. this.maxMorphTargets = 8;
  15613. this.maxMorphNormals = 4; // internal properties
  15614. var _this = this,
  15615. _isContextLost = false,
  15616. // internal state cache
  15617. _framebuffer = null,
  15618. _currentActiveCubeFace = 0,
  15619. _currentActiveMipmapLevel = 0,
  15620. _currentRenderTarget = null,
  15621. _currentFramebuffer = null,
  15622. _currentMaterialId = -1,
  15623. // geometry and program caching
  15624. _currentGeometryProgram = {
  15625. geometry: null,
  15626. program: null,
  15627. wireframe: false
  15628. },
  15629. _currentCamera = null,
  15630. _currentArrayCamera = null,
  15631. _currentViewport = new Vector4(),
  15632. _currentScissor = new Vector4(),
  15633. _currentScissorTest = null,
  15634. //
  15635. _width = _canvas.width,
  15636. _height = _canvas.height,
  15637. _pixelRatio = 1,
  15638. _viewport = new Vector4(0, 0, _width, _height),
  15639. _scissor = new Vector4(0, 0, _width, _height),
  15640. _scissorTest = false,
  15641. // frustum
  15642. _frustum = new Frustum(),
  15643. // clipping
  15644. _clipping = new WebGLClipping(),
  15645. _clippingEnabled = false,
  15646. _localClippingEnabled = false,
  15647. // camera matrices cache
  15648. _projScreenMatrix = new Matrix4(),
  15649. _vector3 = new Vector3();
  15650. function getTargetPixelRatio() {
  15651. return _currentRenderTarget === null ? _pixelRatio : 1;
  15652. } // initialize
  15653. var _gl;
  15654. try {
  15655. var contextAttributes = {
  15656. alpha: _alpha,
  15657. depth: _depth,
  15658. stencil: _stencil,
  15659. antialias: _antialias,
  15660. premultipliedAlpha: _premultipliedAlpha,
  15661. preserveDrawingBuffer: _preserveDrawingBuffer,
  15662. powerPreference: _powerPreference,
  15663. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  15664. xrCompatible: true
  15665. }; // event listeners must be registered before WebGL context is created, see #12753
  15666. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15667. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15668. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  15669. if (_gl === null) {
  15670. if (_canvas.getContext('webgl') !== null) {
  15671. throw new Error('Error creating WebGL context with your selected attributes.');
  15672. } else {
  15673. throw new Error('Error creating WebGL context.');
  15674. }
  15675. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15676. if (_gl.getShaderPrecisionFormat === undefined) {
  15677. _gl.getShaderPrecisionFormat = function () {
  15678. return {
  15679. 'rangeMin': 1,
  15680. 'rangeMax': 1,
  15681. 'precision': 1
  15682. };
  15683. };
  15684. }
  15685. } catch (error) {
  15686. console.error('THREE.WebGLRenderer: ' + error.message);
  15687. throw error;
  15688. }
  15689. var extensions, capabilities, state, info;
  15690. var properties, textures, attributes, geometries, objects;
  15691. var programCache, renderLists, renderStates;
  15692. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15693. var utils;
  15694. function initGLContext() {
  15695. extensions = new WebGLExtensions(_gl);
  15696. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15697. if (capabilities.isWebGL2 === false) {
  15698. extensions.get('WEBGL_depth_texture');
  15699. extensions.get('OES_texture_float');
  15700. extensions.get('OES_texture_half_float');
  15701. extensions.get('OES_texture_half_float_linear');
  15702. extensions.get('OES_standard_derivatives');
  15703. extensions.get('OES_element_index_uint');
  15704. extensions.get('ANGLE_instanced_arrays');
  15705. }
  15706. extensions.get('OES_texture_float_linear');
  15707. utils = new WebGLUtils(_gl, extensions, capabilities);
  15708. state = new WebGLState(_gl, extensions, utils, capabilities);
  15709. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15710. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15711. info = new WebGLInfo(_gl);
  15712. properties = new WebGLProperties();
  15713. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15714. attributes = new WebGLAttributes(_gl);
  15715. geometries = new WebGLGeometries(_gl, attributes, info);
  15716. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15717. morphtargets = new WebGLMorphtargets(_gl);
  15718. programCache = new WebGLPrograms(_this, extensions, capabilities);
  15719. renderLists = new WebGLRenderLists();
  15720. renderStates = new WebGLRenderStates();
  15721. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  15722. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15723. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15724. info.programs = programCache.programs;
  15725. _this.capabilities = capabilities;
  15726. _this.extensions = extensions;
  15727. _this.properties = properties;
  15728. _this.renderLists = renderLists;
  15729. _this.state = state;
  15730. _this.info = info;
  15731. }
  15732. initGLContext(); // vr
  15733. var vr = typeof navigator !== 'undefined' && 'xr' in navigator && 'supportsSession' in navigator.xr ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  15734. this.vr = vr; // Multiview
  15735. var multiview = new WebGLMultiview(_this, _gl); // shadow map
  15736. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  15737. this.shadowMap = shadowMap; // API
  15738. this.getContext = function () {
  15739. return _gl;
  15740. };
  15741. this.getContextAttributes = function () {
  15742. return _gl.getContextAttributes();
  15743. };
  15744. this.forceContextLoss = function () {
  15745. var extension = extensions.get('WEBGL_lose_context');
  15746. if (extension) extension.loseContext();
  15747. };
  15748. this.forceContextRestore = function () {
  15749. var extension = extensions.get('WEBGL_lose_context');
  15750. if (extension) extension.restoreContext();
  15751. };
  15752. this.getPixelRatio = function () {
  15753. return _pixelRatio;
  15754. };
  15755. this.setPixelRatio = function (value) {
  15756. if (value === undefined) return;
  15757. _pixelRatio = value;
  15758. this.setSize(_width, _height, false);
  15759. };
  15760. this.getSize = function (target) {
  15761. if (target === undefined) {
  15762. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  15763. target = new Vector2();
  15764. }
  15765. return target.set(_width, _height);
  15766. };
  15767. this.setSize = function (width, height, updateStyle) {
  15768. if (vr.isPresenting()) {
  15769. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15770. return;
  15771. }
  15772. _width = width;
  15773. _height = height;
  15774. _canvas.width = Math.floor(width * _pixelRatio);
  15775. _canvas.height = Math.floor(height * _pixelRatio);
  15776. if (updateStyle !== false) {
  15777. _canvas.style.width = width + 'px';
  15778. _canvas.style.height = height + 'px';
  15779. }
  15780. this.setViewport(0, 0, width, height);
  15781. };
  15782. this.getDrawingBufferSize = function (target) {
  15783. if (target === undefined) {
  15784. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  15785. target = new Vector2();
  15786. }
  15787. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15788. };
  15789. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15790. _width = width;
  15791. _height = height;
  15792. _pixelRatio = pixelRatio;
  15793. _canvas.width = Math.floor(width * pixelRatio);
  15794. _canvas.height = Math.floor(height * pixelRatio);
  15795. this.setViewport(0, 0, width, height);
  15796. };
  15797. this.getCurrentViewport = function (target) {
  15798. if (target === undefined) {
  15799. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  15800. target = new Vector4();
  15801. }
  15802. return target.copy(_currentViewport);
  15803. };
  15804. this.getViewport = function (target) {
  15805. return target.copy(_viewport);
  15806. };
  15807. this.setViewport = function (x, y, width, height) {
  15808. if (x.isVector4) {
  15809. _viewport.set(x.x, x.y, x.z, x.w);
  15810. } else {
  15811. _viewport.set(x, y, width, height);
  15812. }
  15813. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15814. };
  15815. this.getScissor = function (target) {
  15816. return target.copy(_scissor);
  15817. };
  15818. this.setScissor = function (x, y, width, height) {
  15819. if (x.isVector4) {
  15820. _scissor.set(x.x, x.y, x.z, x.w);
  15821. } else {
  15822. _scissor.set(x, y, width, height);
  15823. }
  15824. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15825. };
  15826. this.getScissorTest = function () {
  15827. return _scissorTest;
  15828. };
  15829. this.setScissorTest = function (boolean) {
  15830. state.setScissorTest(_scissorTest = boolean);
  15831. }; // Clearing
  15832. this.getClearColor = function () {
  15833. return background.getClearColor();
  15834. };
  15835. this.setClearColor = function () {
  15836. background.setClearColor.apply(background, arguments);
  15837. };
  15838. this.getClearAlpha = function () {
  15839. return background.getClearAlpha();
  15840. };
  15841. this.setClearAlpha = function () {
  15842. background.setClearAlpha.apply(background, arguments);
  15843. };
  15844. this.clear = function (color, depth, stencil) {
  15845. var bits = 0;
  15846. if (color === undefined || color) bits |= 16384;
  15847. if (depth === undefined || depth) bits |= 256;
  15848. if (stencil === undefined || stencil) bits |= 1024;
  15849. _gl.clear(bits);
  15850. };
  15851. this.clearColor = function () {
  15852. this.clear(true, false, false);
  15853. };
  15854. this.clearDepth = function () {
  15855. this.clear(false, true, false);
  15856. };
  15857. this.clearStencil = function () {
  15858. this.clear(false, false, true);
  15859. }; //
  15860. this.dispose = function () {
  15861. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15862. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15863. renderLists.dispose();
  15864. renderStates.dispose();
  15865. properties.dispose();
  15866. objects.dispose();
  15867. vr.dispose();
  15868. animation.stop();
  15869. }; // Events
  15870. function onContextLost(event) {
  15871. event.preventDefault();
  15872. console.log('THREE.WebGLRenderer: Context Lost.');
  15873. _isContextLost = true;
  15874. }
  15875. function onContextRestore()
  15876. /* event */
  15877. {
  15878. console.log('THREE.WebGLRenderer: Context Restored.');
  15879. _isContextLost = false;
  15880. initGLContext();
  15881. }
  15882. function onMaterialDispose(event) {
  15883. var material = event.target;
  15884. material.removeEventListener('dispose', onMaterialDispose);
  15885. deallocateMaterial(material);
  15886. } // Buffer deallocation
  15887. function deallocateMaterial(material) {
  15888. releaseMaterialProgramReference(material);
  15889. properties.remove(material);
  15890. }
  15891. function releaseMaterialProgramReference(material) {
  15892. var programInfo = properties.get(material).program;
  15893. material.program = undefined;
  15894. if (programInfo !== undefined) {
  15895. programCache.releaseProgram(programInfo);
  15896. }
  15897. } // Buffer rendering
  15898. function renderObjectImmediate(object, program) {
  15899. object.render(function (object) {
  15900. _this.renderBufferImmediate(object, program);
  15901. });
  15902. }
  15903. this.renderBufferImmediate = function (object, program) {
  15904. state.initAttributes();
  15905. var buffers = properties.get(object);
  15906. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  15907. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  15908. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  15909. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  15910. var programAttributes = program.getAttributes();
  15911. if (object.hasPositions) {
  15912. _gl.bindBuffer(34962, buffers.position);
  15913. _gl.bufferData(34962, object.positionArray, 35048);
  15914. state.enableAttribute(programAttributes.position);
  15915. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  15916. }
  15917. if (object.hasNormals) {
  15918. _gl.bindBuffer(34962, buffers.normal);
  15919. _gl.bufferData(34962, object.normalArray, 35048);
  15920. state.enableAttribute(programAttributes.normal);
  15921. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  15922. }
  15923. if (object.hasUvs) {
  15924. _gl.bindBuffer(34962, buffers.uv);
  15925. _gl.bufferData(34962, object.uvArray, 35048);
  15926. state.enableAttribute(programAttributes.uv);
  15927. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  15928. }
  15929. if (object.hasColors) {
  15930. _gl.bindBuffer(34962, buffers.color);
  15931. _gl.bufferData(34962, object.colorArray, 35048);
  15932. state.enableAttribute(programAttributes.color);
  15933. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  15934. }
  15935. state.disableUnusedAttributes();
  15936. _gl.drawArrays(4, 0, object.count);
  15937. object.count = 0;
  15938. };
  15939. this.renderBufferDirect = function (camera, fog, geometry, material, object, group) {
  15940. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15941. state.setMaterial(material, frontFaceCW);
  15942. var program = setProgram(camera, fog, material, object);
  15943. var updateBuffers = false;
  15944. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  15945. _currentGeometryProgram.geometry = geometry.id;
  15946. _currentGeometryProgram.program = program.id;
  15947. _currentGeometryProgram.wireframe = material.wireframe === true;
  15948. updateBuffers = true;
  15949. }
  15950. if (object.morphTargetInfluences) {
  15951. morphtargets.update(object, geometry, material, program);
  15952. updateBuffers = true;
  15953. } //
  15954. var index = geometry.index;
  15955. var position = geometry.attributes.position;
  15956. var rangeFactor = 1;
  15957. if (material.wireframe === true) {
  15958. index = geometries.getWireframeAttribute(geometry);
  15959. rangeFactor = 2;
  15960. }
  15961. var attribute;
  15962. var renderer = bufferRenderer;
  15963. if (index !== null) {
  15964. attribute = attributes.get(index);
  15965. renderer = indexedBufferRenderer;
  15966. renderer.setIndex(attribute);
  15967. }
  15968. if (updateBuffers) {
  15969. setupVertexAttributes(object, geometry, material, program);
  15970. if (index !== null) {
  15971. _gl.bindBuffer(34963, attribute.buffer);
  15972. }
  15973. } //
  15974. var dataCount = Infinity;
  15975. if (index !== null) {
  15976. dataCount = index.count;
  15977. } else if (position !== undefined) {
  15978. dataCount = position.count;
  15979. }
  15980. var rangeStart = geometry.drawRange.start * rangeFactor;
  15981. var rangeCount = geometry.drawRange.count * rangeFactor;
  15982. var groupStart = group !== null ? group.start * rangeFactor : 0;
  15983. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15984. var drawStart = Math.max(rangeStart, groupStart);
  15985. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15986. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  15987. if (drawCount === 0) return; //
  15988. if (object.isMesh) {
  15989. if (material.wireframe === true) {
  15990. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15991. renderer.setMode(1);
  15992. } else {
  15993. switch (object.drawMode) {
  15994. case TrianglesDrawMode:
  15995. renderer.setMode(4);
  15996. break;
  15997. case TriangleStripDrawMode:
  15998. renderer.setMode(5);
  15999. break;
  16000. case TriangleFanDrawMode:
  16001. renderer.setMode(6);
  16002. break;
  16003. }
  16004. }
  16005. } else if (object.isLine) {
  16006. var lineWidth = material.linewidth;
  16007. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16008. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16009. if (object.isLineSegments) {
  16010. renderer.setMode(1);
  16011. } else if (object.isLineLoop) {
  16012. renderer.setMode(2);
  16013. } else {
  16014. renderer.setMode(3);
  16015. }
  16016. } else if (object.isPoints) {
  16017. renderer.setMode(0);
  16018. } else if (object.isSprite) {
  16019. renderer.setMode(4);
  16020. }
  16021. if (object.isInstancedMesh) {
  16022. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  16023. } else if (geometry.isInstancedBufferGeometry) {
  16024. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  16025. } else {
  16026. renderer.render(drawStart, drawCount);
  16027. }
  16028. };
  16029. function setupVertexAttributes(object, geometry, material, program) {
  16030. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  16031. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  16032. }
  16033. state.initAttributes();
  16034. var geometryAttributes = geometry.attributes;
  16035. var programAttributes = program.getAttributes();
  16036. var materialDefaultAttributeValues = material.defaultAttributeValues;
  16037. for (var name in programAttributes) {
  16038. var programAttribute = programAttributes[name];
  16039. if (programAttribute >= 0) {
  16040. var geometryAttribute = geometryAttributes[name];
  16041. if (geometryAttribute !== undefined) {
  16042. var normalized = geometryAttribute.normalized;
  16043. var size = geometryAttribute.itemSize;
  16044. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  16045. if (attribute === undefined) continue;
  16046. var buffer = attribute.buffer;
  16047. var type = attribute.type;
  16048. var bytesPerElement = attribute.bytesPerElement;
  16049. if (geometryAttribute.isInterleavedBufferAttribute) {
  16050. var data = geometryAttribute.data;
  16051. var stride = data.stride;
  16052. var offset = geometryAttribute.offset;
  16053. if (data && data.isInstancedInterleavedBuffer) {
  16054. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  16055. if (geometry.maxInstancedCount === undefined) {
  16056. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  16057. }
  16058. } else {
  16059. state.enableAttribute(programAttribute);
  16060. }
  16061. _gl.bindBuffer(34962, buffer);
  16062. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  16063. } else {
  16064. if (geometryAttribute.isInstancedBufferAttribute) {
  16065. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  16066. if (geometry.maxInstancedCount === undefined) {
  16067. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  16068. }
  16069. } else {
  16070. state.enableAttribute(programAttribute);
  16071. }
  16072. _gl.bindBuffer(34962, buffer);
  16073. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  16074. }
  16075. } else if (name === 'instanceMatrix') {
  16076. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  16077. if (attribute === undefined) continue;
  16078. var buffer = attribute.buffer;
  16079. var type = attribute.type;
  16080. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  16081. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  16082. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  16083. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  16084. _gl.bindBuffer(34962, buffer);
  16085. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  16086. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  16087. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  16088. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  16089. } else if (materialDefaultAttributeValues !== undefined) {
  16090. var value = materialDefaultAttributeValues[name];
  16091. if (value !== undefined) {
  16092. switch (value.length) {
  16093. case 2:
  16094. _gl.vertexAttrib2fv(programAttribute, value);
  16095. break;
  16096. case 3:
  16097. _gl.vertexAttrib3fv(programAttribute, value);
  16098. break;
  16099. case 4:
  16100. _gl.vertexAttrib4fv(programAttribute, value);
  16101. break;
  16102. default:
  16103. _gl.vertexAttrib1fv(programAttribute, value);
  16104. }
  16105. }
  16106. }
  16107. }
  16108. }
  16109. state.disableUnusedAttributes();
  16110. } // Compile
  16111. this.compile = function (scene, camera) {
  16112. currentRenderState = renderStates.get(scene, camera);
  16113. currentRenderState.init();
  16114. scene.traverse(function (object) {
  16115. if (object.isLight) {
  16116. currentRenderState.pushLight(object);
  16117. if (object.castShadow) {
  16118. currentRenderState.pushShadow(object);
  16119. }
  16120. }
  16121. });
  16122. currentRenderState.setupLights(camera);
  16123. scene.traverse(function (object) {
  16124. if (object.material) {
  16125. if (Array.isArray(object.material)) {
  16126. for (var i = 0; i < object.material.length; i++) {
  16127. initMaterial(object.material[i], scene.fog, object);
  16128. }
  16129. } else {
  16130. initMaterial(object.material, scene.fog, object);
  16131. }
  16132. }
  16133. });
  16134. }; // Animation Loop
  16135. var onAnimationFrameCallback = null;
  16136. function onAnimationFrame(time) {
  16137. if (vr.isPresenting()) return;
  16138. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16139. }
  16140. var animation = new WebGLAnimation();
  16141. animation.setAnimationLoop(onAnimationFrame);
  16142. if (typeof window !== 'undefined') animation.setContext(window);
  16143. this.setAnimationLoop = function (callback) {
  16144. onAnimationFrameCallback = callback;
  16145. vr.setAnimationLoop(callback);
  16146. animation.start();
  16147. }; // Rendering
  16148. this.render = function (scene, camera) {
  16149. var renderTarget, forceClear;
  16150. if (arguments[2] !== undefined) {
  16151. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  16152. renderTarget = arguments[2];
  16153. }
  16154. if (arguments[3] !== undefined) {
  16155. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  16156. forceClear = arguments[3];
  16157. }
  16158. if (!(camera && camera.isCamera)) {
  16159. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16160. return;
  16161. }
  16162. if (_isContextLost) return; // reset caching for this frame
  16163. _currentGeometryProgram.geometry = null;
  16164. _currentGeometryProgram.program = null;
  16165. _currentGeometryProgram.wireframe = false;
  16166. _currentMaterialId = -1;
  16167. _currentCamera = null; // update scene graph
  16168. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  16169. if (camera.parent === null) camera.updateMatrixWorld();
  16170. if (vr.enabled) {
  16171. camera = vr.getCamera(camera);
  16172. } //
  16173. currentRenderState = renderStates.get(scene, camera);
  16174. currentRenderState.init();
  16175. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  16176. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16177. _frustum.setFromMatrix(_projScreenMatrix);
  16178. _localClippingEnabled = this.localClippingEnabled;
  16179. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16180. currentRenderList = renderLists.get(scene, camera);
  16181. currentRenderList.init();
  16182. projectObject(scene, camera, 0, _this.sortObjects);
  16183. if (_this.sortObjects === true) {
  16184. currentRenderList.sort();
  16185. } //
  16186. if (_clippingEnabled) _clipping.beginShadows();
  16187. var shadowsArray = currentRenderState.state.shadowsArray;
  16188. shadowMap.render(shadowsArray, scene, camera);
  16189. currentRenderState.setupLights(camera);
  16190. if (_clippingEnabled) _clipping.endShadows(); //
  16191. if (this.info.autoReset) this.info.reset();
  16192. if (renderTarget !== undefined) {
  16193. this.setRenderTarget(renderTarget);
  16194. }
  16195. if (vr.enabled && multiview.isAvailable()) {
  16196. multiview.attachCamera(camera);
  16197. } //
  16198. background.render(currentRenderList, scene, camera, forceClear); // render scene
  16199. var opaqueObjects = currentRenderList.opaque;
  16200. var transparentObjects = currentRenderList.transparent;
  16201. if (scene.overrideMaterial) {
  16202. var overrideMaterial = scene.overrideMaterial;
  16203. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  16204. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  16205. } else {
  16206. // opaque pass (front-to-back order)
  16207. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  16208. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  16209. } //
  16210. scene.onAfterRender(_this, scene, camera); //
  16211. if (_currentRenderTarget !== null) {
  16212. // Generate mipmap if we're using any kind of mipmap filtering
  16213. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  16214. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  16215. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  16216. state.buffers.depth.setTest(true);
  16217. state.buffers.depth.setMask(true);
  16218. state.buffers.color.setMask(true);
  16219. state.setPolygonOffset(false);
  16220. if (vr.enabled) {
  16221. if (multiview.isAvailable()) {
  16222. multiview.detachCamera(camera);
  16223. }
  16224. vr.submitFrame();
  16225. } // _gl.finish();
  16226. currentRenderList = null;
  16227. currentRenderState = null;
  16228. };
  16229. function projectObject(object, camera, groupOrder, sortObjects) {
  16230. if (object.visible === false) return;
  16231. var visible = object.layers.test(camera.layers);
  16232. if (visible) {
  16233. if (object.isGroup) {
  16234. groupOrder = object.renderOrder;
  16235. } else if (object.isLOD) {
  16236. if (object.autoUpdate === true) object.update(camera);
  16237. } else if (object.isLight) {
  16238. currentRenderState.pushLight(object);
  16239. if (object.castShadow) {
  16240. currentRenderState.pushShadow(object);
  16241. }
  16242. } else if (object.isSprite) {
  16243. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16244. if (sortObjects) {
  16245. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16246. }
  16247. var geometry = objects.update(object);
  16248. var material = object.material;
  16249. if (material.visible) {
  16250. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16251. }
  16252. }
  16253. } else if (object.isImmediateRenderObject) {
  16254. if (sortObjects) {
  16255. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16256. }
  16257. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  16258. } else if (object.isMesh || object.isLine || object.isPoints) {
  16259. if (object.isSkinnedMesh) {
  16260. // update skeleton only once in a frame
  16261. if (object.skeleton.frame !== info.render.frame) {
  16262. object.skeleton.update();
  16263. object.skeleton.frame = info.render.frame;
  16264. }
  16265. }
  16266. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16267. if (sortObjects) {
  16268. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16269. }
  16270. var geometry = objects.update(object);
  16271. var material = object.material;
  16272. if (Array.isArray(material)) {
  16273. var groups = geometry.groups;
  16274. for (var i = 0, l = groups.length; i < l; i++) {
  16275. var group = groups[i];
  16276. var groupMaterial = material[group.materialIndex];
  16277. if (groupMaterial && groupMaterial.visible) {
  16278. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16279. }
  16280. }
  16281. } else if (material.visible) {
  16282. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16283. }
  16284. }
  16285. }
  16286. }
  16287. var children = object.children;
  16288. for (var i = 0, l = children.length; i < l; i++) {
  16289. projectObject(children[i], camera, groupOrder, sortObjects);
  16290. }
  16291. }
  16292. function renderObjects(renderList, scene, camera, overrideMaterial) {
  16293. for (var i = 0, l = renderList.length; i < l; i++) {
  16294. var renderItem = renderList[i];
  16295. var object = renderItem.object;
  16296. var geometry = renderItem.geometry;
  16297. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  16298. var group = renderItem.group;
  16299. if (camera.isArrayCamera) {
  16300. _currentArrayCamera = camera;
  16301. if (vr.enabled && multiview.isAvailable()) {
  16302. renderObject(object, scene, camera, geometry, material, group);
  16303. } else {
  16304. var cameras = camera.cameras;
  16305. for (var j = 0, jl = cameras.length; j < jl; j++) {
  16306. var camera2 = cameras[j];
  16307. if (object.layers.test(camera2.layers)) {
  16308. state.viewport(_currentViewport.copy(camera2.viewport));
  16309. currentRenderState.setupLights(camera2);
  16310. renderObject(object, scene, camera2, geometry, material, group);
  16311. }
  16312. }
  16313. }
  16314. } else {
  16315. _currentArrayCamera = null;
  16316. renderObject(object, scene, camera, geometry, material, group);
  16317. }
  16318. }
  16319. }
  16320. function renderObject(object, scene, camera, geometry, material, group) {
  16321. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16322. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16323. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16324. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16325. if (object.isImmediateRenderObject) {
  16326. state.setMaterial(material);
  16327. var program = setProgram(camera, scene.fog, material, object);
  16328. _currentGeometryProgram.geometry = null;
  16329. _currentGeometryProgram.program = null;
  16330. _currentGeometryProgram.wireframe = false;
  16331. renderObjectImmediate(object, program);
  16332. } else {
  16333. _this.renderBufferDirect(camera, scene.fog, geometry, material, object, group);
  16334. }
  16335. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16336. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  16337. }
  16338. function initMaterial(material, fog, object) {
  16339. var materialProperties = properties.get(material);
  16340. var lights = currentRenderState.state.lights;
  16341. var shadowsArray = currentRenderState.state.shadowsArray;
  16342. var lightsStateVersion = lights.state.version;
  16343. var parameters = programCache.getParameters(material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object);
  16344. var code = programCache.getProgramCode(material, parameters);
  16345. var program = materialProperties.program;
  16346. var programChange = true;
  16347. if (program === undefined) {
  16348. // new material
  16349. material.addEventListener('dispose', onMaterialDispose);
  16350. } else if (program.code !== code) {
  16351. // changed glsl or parameters
  16352. releaseMaterialProgramReference(material);
  16353. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  16354. materialProperties.lightsStateVersion = lightsStateVersion;
  16355. programChange = false;
  16356. } else if (parameters.shaderID !== undefined) {
  16357. // same glsl and uniform list
  16358. return;
  16359. } else {
  16360. // only rebuild uniform list
  16361. programChange = false;
  16362. }
  16363. if (programChange) {
  16364. if (parameters.shaderID) {
  16365. var shader = ShaderLib[parameters.shaderID];
  16366. materialProperties.shader = {
  16367. name: material.type,
  16368. uniforms: cloneUniforms(shader.uniforms),
  16369. vertexShader: shader.vertexShader,
  16370. fragmentShader: shader.fragmentShader
  16371. };
  16372. } else {
  16373. materialProperties.shader = {
  16374. name: material.type,
  16375. uniforms: material.uniforms,
  16376. vertexShader: material.vertexShader,
  16377. fragmentShader: material.fragmentShader
  16378. };
  16379. }
  16380. material.onBeforeCompile(materialProperties.shader, _this); // Computing code again as onBeforeCompile may have changed the shaders
  16381. code = programCache.getProgramCode(material, parameters);
  16382. program = programCache.acquireProgram(material, materialProperties.shader, parameters, code);
  16383. materialProperties.program = program;
  16384. material.program = program;
  16385. }
  16386. var programAttributes = program.getAttributes();
  16387. if (material.morphTargets) {
  16388. material.numSupportedMorphTargets = 0;
  16389. for (var i = 0; i < _this.maxMorphTargets; i++) {
  16390. if (programAttributes['morphTarget' + i] >= 0) {
  16391. material.numSupportedMorphTargets++;
  16392. }
  16393. }
  16394. }
  16395. if (material.morphNormals) {
  16396. material.numSupportedMorphNormals = 0;
  16397. for (var i = 0; i < _this.maxMorphNormals; i++) {
  16398. if (programAttributes['morphNormal' + i] >= 0) {
  16399. material.numSupportedMorphNormals++;
  16400. }
  16401. }
  16402. }
  16403. var uniforms = materialProperties.shader.uniforms;
  16404. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16405. materialProperties.numClippingPlanes = _clipping.numPlanes;
  16406. materialProperties.numIntersection = _clipping.numIntersection;
  16407. uniforms.clippingPlanes = _clipping.uniform;
  16408. }
  16409. materialProperties.fog = fog; // store the light setup it was created for
  16410. materialProperties.needsLights = materialNeedsLights(material);
  16411. materialProperties.lightsStateVersion = lightsStateVersion;
  16412. if (materialProperties.needsLights) {
  16413. // wire up the material to this renderer's lighting state
  16414. uniforms.ambientLightColor.value = lights.state.ambient;
  16415. uniforms.lightProbe.value = lights.state.probe;
  16416. uniforms.directionalLights.value = lights.state.directional;
  16417. uniforms.spotLights.value = lights.state.spot;
  16418. uniforms.rectAreaLights.value = lights.state.rectArea;
  16419. uniforms.pointLights.value = lights.state.point;
  16420. uniforms.hemisphereLights.value = lights.state.hemi;
  16421. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16422. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16423. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16424. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16425. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16426. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16427. }
  16428. var progUniforms = materialProperties.program.getUniforms(),
  16429. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16430. materialProperties.uniformsList = uniformsList;
  16431. }
  16432. function setProgram(camera, fog, material, object) {
  16433. textures.resetTextureUnits();
  16434. var materialProperties = properties.get(material);
  16435. var lights = currentRenderState.state.lights;
  16436. if (_clippingEnabled) {
  16437. if (_localClippingEnabled || camera !== _currentCamera) {
  16438. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16439. // object instead of the material, once it becomes feasible
  16440. // (#8465, #8379)
  16441. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  16442. }
  16443. }
  16444. if (material.needsUpdate === false) {
  16445. if (materialProperties.program === undefined) {
  16446. material.needsUpdate = true;
  16447. } else if (material.fog && materialProperties.fog !== fog) {
  16448. material.needsUpdate = true;
  16449. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16450. material.needsUpdate = true;
  16451. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  16452. material.needsUpdate = true;
  16453. }
  16454. }
  16455. if (material.needsUpdate) {
  16456. initMaterial(material, fog, object);
  16457. material.needsUpdate = false;
  16458. }
  16459. var refreshProgram = false;
  16460. var refreshMaterial = false;
  16461. var refreshLights = false;
  16462. var program = materialProperties.program,
  16463. p_uniforms = program.getUniforms(),
  16464. m_uniforms = materialProperties.shader.uniforms;
  16465. if (state.useProgram(program.program)) {
  16466. refreshProgram = true;
  16467. refreshMaterial = true;
  16468. refreshLights = true;
  16469. }
  16470. if (material.id !== _currentMaterialId) {
  16471. _currentMaterialId = material.id;
  16472. refreshMaterial = true;
  16473. }
  16474. if (refreshProgram || _currentCamera !== camera) {
  16475. if (program.numMultiviewViews > 0) {
  16476. multiview.updateCameraProjectionMatricesUniform(camera, p_uniforms);
  16477. } else {
  16478. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16479. }
  16480. if (capabilities.logarithmicDepthBuffer) {
  16481. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16482. }
  16483. if (_currentCamera !== camera) {
  16484. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16485. // now, in case this material supports lights - or later, when
  16486. // the next material that does gets activated:
  16487. refreshMaterial = true; // set to true on material change
  16488. refreshLights = true; // remains set until update done
  16489. } // load material specific uniforms
  16490. // (shader material also gets them for the sake of genericity)
  16491. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.envMap) {
  16492. var uCamPos = p_uniforms.map.cameraPosition;
  16493. if (uCamPos !== undefined) {
  16494. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16495. }
  16496. }
  16497. if (material.isMeshPhongMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  16498. if (program.numMultiviewViews > 0) {
  16499. multiview.updateCameraViewMatricesUniform(camera, p_uniforms);
  16500. } else {
  16501. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16502. }
  16503. }
  16504. } // skinning uniforms must be set even if material didn't change
  16505. // auto-setting of texture unit for bone texture must go before other textures
  16506. // not sure why, but otherwise weird things happen
  16507. if (material.skinning) {
  16508. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16509. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16510. var skeleton = object.skeleton;
  16511. if (skeleton) {
  16512. var bones = skeleton.bones;
  16513. if (capabilities.floatVertexTextures) {
  16514. if (skeleton.boneTexture === undefined) {
  16515. // layout (1 matrix = 4 pixels)
  16516. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16517. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16518. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16519. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16520. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16521. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  16522. size = _Math.ceilPowerOfTwo(size);
  16523. size = Math.max(size, 4);
  16524. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16525. boneMatrices.set(skeleton.boneMatrices); // copy current values
  16526. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16527. skeleton.boneMatrices = boneMatrices;
  16528. skeleton.boneTexture = boneTexture;
  16529. skeleton.boneTextureSize = size;
  16530. }
  16531. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16532. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16533. } else {
  16534. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  16535. }
  16536. }
  16537. }
  16538. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16539. materialProperties.receiveShadow = object.receiveShadow;
  16540. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16541. }
  16542. if (refreshMaterial) {
  16543. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16544. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  16545. if (materialProperties.needsLights) {
  16546. // the current material requires lighting info
  16547. // note: all lighting uniforms are always set correctly
  16548. // they simply reference the renderer's state for their
  16549. // values
  16550. //
  16551. // use the current material's .needsUpdate flags to set
  16552. // the GL state when required
  16553. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16554. } // refresh uniforms common to several materials
  16555. if (fog && material.fog) {
  16556. refreshUniformsFog(m_uniforms, fog);
  16557. }
  16558. if (material.isMeshBasicMaterial) {
  16559. refreshUniformsCommon(m_uniforms, material);
  16560. } else if (material.isMeshLambertMaterial) {
  16561. refreshUniformsCommon(m_uniforms, material);
  16562. refreshUniformsLambert(m_uniforms, material);
  16563. } else if (material.isMeshPhongMaterial) {
  16564. refreshUniformsCommon(m_uniforms, material);
  16565. if (material.isMeshToonMaterial) {
  16566. refreshUniformsToon(m_uniforms, material);
  16567. } else {
  16568. refreshUniformsPhong(m_uniforms, material);
  16569. }
  16570. } else if (material.isMeshStandardMaterial) {
  16571. refreshUniformsCommon(m_uniforms, material);
  16572. if (material.isMeshPhysicalMaterial) {
  16573. refreshUniformsPhysical(m_uniforms, material);
  16574. } else {
  16575. refreshUniformsStandard(m_uniforms, material);
  16576. }
  16577. } else if (material.isMeshMatcapMaterial) {
  16578. refreshUniformsCommon(m_uniforms, material);
  16579. refreshUniformsMatcap(m_uniforms, material);
  16580. } else if (material.isMeshDepthMaterial) {
  16581. refreshUniformsCommon(m_uniforms, material);
  16582. refreshUniformsDepth(m_uniforms, material);
  16583. } else if (material.isMeshDistanceMaterial) {
  16584. refreshUniformsCommon(m_uniforms, material);
  16585. refreshUniformsDistance(m_uniforms, material);
  16586. } else if (material.isMeshNormalMaterial) {
  16587. refreshUniformsCommon(m_uniforms, material);
  16588. refreshUniformsNormal(m_uniforms, material);
  16589. } else if (material.isLineBasicMaterial) {
  16590. refreshUniformsLine(m_uniforms, material);
  16591. if (material.isLineDashedMaterial) {
  16592. refreshUniformsDash(m_uniforms, material);
  16593. }
  16594. } else if (material.isPointsMaterial) {
  16595. refreshUniformsPoints(m_uniforms, material);
  16596. } else if (material.isSpriteMaterial) {
  16597. refreshUniformsSprites(m_uniforms, material);
  16598. } else if (material.isShadowMaterial) {
  16599. m_uniforms.color.value.copy(material.color);
  16600. m_uniforms.opacity.value = material.opacity;
  16601. } // RectAreaLight Texture
  16602. // TODO (mrdoob): Find a nicer implementation
  16603. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  16604. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  16605. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16606. }
  16607. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16608. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16609. material.uniformsNeedUpdate = false;
  16610. }
  16611. if (material.isSpriteMaterial) {
  16612. p_uniforms.setValue(_gl, 'center', object.center);
  16613. } // common matrices
  16614. if (program.numMultiviewViews > 0) {
  16615. multiview.updateObjectMatricesUniforms(object, camera, p_uniforms);
  16616. } else {
  16617. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16618. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16619. }
  16620. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16621. return program;
  16622. } // Uniforms (refresh uniforms objects)
  16623. function refreshUniformsCommon(uniforms, material) {
  16624. uniforms.opacity.value = material.opacity;
  16625. if (material.color) {
  16626. uniforms.diffuse.value.copy(material.color);
  16627. }
  16628. if (material.emissive) {
  16629. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  16630. }
  16631. if (material.map) {
  16632. uniforms.map.value = material.map;
  16633. }
  16634. if (material.alphaMap) {
  16635. uniforms.alphaMap.value = material.alphaMap;
  16636. }
  16637. if (material.specularMap) {
  16638. uniforms.specularMap.value = material.specularMap;
  16639. }
  16640. if (material.envMap) {
  16641. uniforms.envMap.value = material.envMap; // don't flip CubeTexture envMaps, flip everything else:
  16642. // WebGLRenderTargetCube will be flipped for backwards compatibility
  16643. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  16644. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  16645. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  16646. uniforms.reflectivity.value = material.reflectivity;
  16647. uniforms.refractionRatio.value = material.refractionRatio;
  16648. uniforms.maxMipLevel.value = properties.get(material.envMap).__maxMipLevel;
  16649. }
  16650. if (material.lightMap) {
  16651. uniforms.lightMap.value = material.lightMap;
  16652. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16653. }
  16654. if (material.aoMap) {
  16655. uniforms.aoMap.value = material.aoMap;
  16656. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16657. } // uv repeat and offset setting priorities
  16658. // 1. color map
  16659. // 2. specular map
  16660. // 3. normal map
  16661. // 4. bump map
  16662. // 5. alpha map
  16663. // 6. emissive map
  16664. var uvScaleMap;
  16665. if (material.map) {
  16666. uvScaleMap = material.map;
  16667. } else if (material.specularMap) {
  16668. uvScaleMap = material.specularMap;
  16669. } else if (material.displacementMap) {
  16670. uvScaleMap = material.displacementMap;
  16671. } else if (material.normalMap) {
  16672. uvScaleMap = material.normalMap;
  16673. } else if (material.bumpMap) {
  16674. uvScaleMap = material.bumpMap;
  16675. } else if (material.roughnessMap) {
  16676. uvScaleMap = material.roughnessMap;
  16677. } else if (material.metalnessMap) {
  16678. uvScaleMap = material.metalnessMap;
  16679. } else if (material.alphaMap) {
  16680. uvScaleMap = material.alphaMap;
  16681. } else if (material.emissiveMap) {
  16682. uvScaleMap = material.emissiveMap;
  16683. }
  16684. if (uvScaleMap !== undefined) {
  16685. // backwards compatibility
  16686. if (uvScaleMap.isWebGLRenderTarget) {
  16687. uvScaleMap = uvScaleMap.texture;
  16688. }
  16689. if (uvScaleMap.matrixAutoUpdate === true) {
  16690. uvScaleMap.updateMatrix();
  16691. }
  16692. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  16693. }
  16694. }
  16695. function refreshUniformsLine(uniforms, material) {
  16696. uniforms.diffuse.value.copy(material.color);
  16697. uniforms.opacity.value = material.opacity;
  16698. }
  16699. function refreshUniformsDash(uniforms, material) {
  16700. uniforms.dashSize.value = material.dashSize;
  16701. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16702. uniforms.scale.value = material.scale;
  16703. }
  16704. function refreshUniformsPoints(uniforms, material) {
  16705. uniforms.diffuse.value.copy(material.color);
  16706. uniforms.opacity.value = material.opacity;
  16707. uniforms.size.value = material.size * _pixelRatio;
  16708. uniforms.scale.value = _height * 0.5;
  16709. uniforms.map.value = material.map;
  16710. if (material.map !== null) {
  16711. if (material.map.matrixAutoUpdate === true) {
  16712. material.map.updateMatrix();
  16713. }
  16714. uniforms.uvTransform.value.copy(material.map.matrix);
  16715. }
  16716. }
  16717. function refreshUniformsSprites(uniforms, material) {
  16718. uniforms.diffuse.value.copy(material.color);
  16719. uniforms.opacity.value = material.opacity;
  16720. uniforms.rotation.value = material.rotation;
  16721. uniforms.map.value = material.map;
  16722. if (material.map !== null) {
  16723. if (material.map.matrixAutoUpdate === true) {
  16724. material.map.updateMatrix();
  16725. }
  16726. uniforms.uvTransform.value.copy(material.map.matrix);
  16727. }
  16728. }
  16729. function refreshUniformsFog(uniforms, fog) {
  16730. uniforms.fogColor.value.copy(fog.color);
  16731. if (fog.isFog) {
  16732. uniforms.fogNear.value = fog.near;
  16733. uniforms.fogFar.value = fog.far;
  16734. } else if (fog.isFogExp2) {
  16735. uniforms.fogDensity.value = fog.density;
  16736. }
  16737. }
  16738. function refreshUniformsLambert(uniforms, material) {
  16739. if (material.emissiveMap) {
  16740. uniforms.emissiveMap.value = material.emissiveMap;
  16741. }
  16742. }
  16743. function refreshUniformsPhong(uniforms, material) {
  16744. uniforms.specular.value.copy(material.specular);
  16745. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  16746. if (material.emissiveMap) {
  16747. uniforms.emissiveMap.value = material.emissiveMap;
  16748. }
  16749. if (material.bumpMap) {
  16750. uniforms.bumpMap.value = material.bumpMap;
  16751. uniforms.bumpScale.value = material.bumpScale;
  16752. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16753. }
  16754. if (material.normalMap) {
  16755. uniforms.normalMap.value = material.normalMap;
  16756. uniforms.normalScale.value.copy(material.normalScale);
  16757. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16758. }
  16759. if (material.displacementMap) {
  16760. uniforms.displacementMap.value = material.displacementMap;
  16761. uniforms.displacementScale.value = material.displacementScale;
  16762. uniforms.displacementBias.value = material.displacementBias;
  16763. }
  16764. }
  16765. function refreshUniformsToon(uniforms, material) {
  16766. refreshUniformsPhong(uniforms, material);
  16767. if (material.gradientMap) {
  16768. uniforms.gradientMap.value = material.gradientMap;
  16769. }
  16770. }
  16771. function refreshUniformsStandard(uniforms, material) {
  16772. uniforms.roughness.value = material.roughness;
  16773. uniforms.metalness.value = material.metalness;
  16774. if (material.roughnessMap) {
  16775. uniforms.roughnessMap.value = material.roughnessMap;
  16776. }
  16777. if (material.metalnessMap) {
  16778. uniforms.metalnessMap.value = material.metalnessMap;
  16779. }
  16780. if (material.emissiveMap) {
  16781. uniforms.emissiveMap.value = material.emissiveMap;
  16782. }
  16783. if (material.bumpMap) {
  16784. uniforms.bumpMap.value = material.bumpMap;
  16785. uniforms.bumpScale.value = material.bumpScale;
  16786. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16787. }
  16788. if (material.normalMap) {
  16789. uniforms.normalMap.value = material.normalMap;
  16790. uniforms.normalScale.value.copy(material.normalScale);
  16791. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16792. }
  16793. if (material.displacementMap) {
  16794. uniforms.displacementMap.value = material.displacementMap;
  16795. uniforms.displacementScale.value = material.displacementScale;
  16796. uniforms.displacementBias.value = material.displacementBias;
  16797. }
  16798. if (material.envMap) {
  16799. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16800. uniforms.envMapIntensity.value = material.envMapIntensity;
  16801. }
  16802. }
  16803. function refreshUniformsPhysical(uniforms, material) {
  16804. refreshUniformsStandard(uniforms, material);
  16805. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  16806. uniforms.clearcoat.value = material.clearcoat;
  16807. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16808. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  16809. if (material.clearcoatNormalMap) {
  16810. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  16811. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16812. if (material.side === BackSide) {
  16813. uniforms.clearcoatNormalScale.value.negate();
  16814. }
  16815. }
  16816. uniforms.transparency.value = material.transparency;
  16817. }
  16818. function refreshUniformsMatcap(uniforms, material) {
  16819. if (material.matcap) {
  16820. uniforms.matcap.value = material.matcap;
  16821. }
  16822. if (material.bumpMap) {
  16823. uniforms.bumpMap.value = material.bumpMap;
  16824. uniforms.bumpScale.value = material.bumpScale;
  16825. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16826. }
  16827. if (material.normalMap) {
  16828. uniforms.normalMap.value = material.normalMap;
  16829. uniforms.normalScale.value.copy(material.normalScale);
  16830. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16831. }
  16832. if (material.displacementMap) {
  16833. uniforms.displacementMap.value = material.displacementMap;
  16834. uniforms.displacementScale.value = material.displacementScale;
  16835. uniforms.displacementBias.value = material.displacementBias;
  16836. }
  16837. }
  16838. function refreshUniformsDepth(uniforms, material) {
  16839. if (material.displacementMap) {
  16840. uniforms.displacementMap.value = material.displacementMap;
  16841. uniforms.displacementScale.value = material.displacementScale;
  16842. uniforms.displacementBias.value = material.displacementBias;
  16843. }
  16844. }
  16845. function refreshUniformsDistance(uniforms, material) {
  16846. if (material.displacementMap) {
  16847. uniforms.displacementMap.value = material.displacementMap;
  16848. uniforms.displacementScale.value = material.displacementScale;
  16849. uniforms.displacementBias.value = material.displacementBias;
  16850. }
  16851. uniforms.referencePosition.value.copy(material.referencePosition);
  16852. uniforms.nearDistance.value = material.nearDistance;
  16853. uniforms.farDistance.value = material.farDistance;
  16854. }
  16855. function refreshUniformsNormal(uniforms, material) {
  16856. if (material.bumpMap) {
  16857. uniforms.bumpMap.value = material.bumpMap;
  16858. uniforms.bumpScale.value = material.bumpScale;
  16859. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  16860. }
  16861. if (material.normalMap) {
  16862. uniforms.normalMap.value = material.normalMap;
  16863. uniforms.normalScale.value.copy(material.normalScale);
  16864. if (material.side === BackSide) uniforms.normalScale.value.negate();
  16865. }
  16866. if (material.displacementMap) {
  16867. uniforms.displacementMap.value = material.displacementMap;
  16868. uniforms.displacementScale.value = material.displacementScale;
  16869. uniforms.displacementBias.value = material.displacementBias;
  16870. }
  16871. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16872. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16873. uniforms.ambientLightColor.needsUpdate = value;
  16874. uniforms.lightProbe.needsUpdate = value;
  16875. uniforms.directionalLights.needsUpdate = value;
  16876. uniforms.pointLights.needsUpdate = value;
  16877. uniforms.spotLights.needsUpdate = value;
  16878. uniforms.rectAreaLights.needsUpdate = value;
  16879. uniforms.hemisphereLights.needsUpdate = value;
  16880. }
  16881. function materialNeedsLights(material) {
  16882. return material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16883. } //
  16884. this.setFramebuffer = function (value) {
  16885. if (_framebuffer !== value) _gl.bindFramebuffer(36160, value);
  16886. _framebuffer = value;
  16887. };
  16888. this.getActiveCubeFace = function () {
  16889. return _currentActiveCubeFace;
  16890. };
  16891. this.getActiveMipmapLevel = function () {
  16892. return _currentActiveMipmapLevel;
  16893. };
  16894. this.getRenderTarget = function () {
  16895. return _currentRenderTarget;
  16896. };
  16897. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  16898. _currentRenderTarget = renderTarget;
  16899. _currentActiveCubeFace = activeCubeFace;
  16900. _currentActiveMipmapLevel = activeMipmapLevel;
  16901. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  16902. textures.setupRenderTarget(renderTarget);
  16903. }
  16904. var framebuffer = _framebuffer;
  16905. var isCube = false;
  16906. if (renderTarget) {
  16907. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16908. if (renderTarget.isWebGLRenderTargetCube) {
  16909. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  16910. isCube = true;
  16911. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  16912. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16913. } else {
  16914. framebuffer = __webglFramebuffer;
  16915. }
  16916. _currentViewport.copy(renderTarget.viewport);
  16917. _currentScissor.copy(renderTarget.scissor);
  16918. _currentScissorTest = renderTarget.scissorTest;
  16919. } else {
  16920. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16921. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16922. _currentScissorTest = _scissorTest;
  16923. }
  16924. if (_currentFramebuffer !== framebuffer) {
  16925. _gl.bindFramebuffer(36160, framebuffer);
  16926. _currentFramebuffer = framebuffer;
  16927. }
  16928. state.viewport(_currentViewport);
  16929. state.scissor(_currentScissor);
  16930. state.setScissorTest(_currentScissorTest);
  16931. if (isCube) {
  16932. var textureProperties = properties.get(renderTarget.texture);
  16933. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  16934. }
  16935. };
  16936. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16937. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16938. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16939. return;
  16940. }
  16941. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16942. if (renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined) {
  16943. framebuffer = framebuffer[activeCubeFaceIndex];
  16944. }
  16945. if (framebuffer) {
  16946. var restore = false;
  16947. if (framebuffer !== _currentFramebuffer) {
  16948. _gl.bindFramebuffer(36160, framebuffer);
  16949. restore = true;
  16950. }
  16951. try {
  16952. var texture = renderTarget.texture;
  16953. var textureFormat = texture.format;
  16954. var textureType = texture.type;
  16955. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  16956. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16957. return;
  16958. }
  16959. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  16960. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16961. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  16962. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16963. return;
  16964. }
  16965. if (_gl.checkFramebufferStatus(36160) === 36053) {
  16966. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16967. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16968. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16969. }
  16970. } else {
  16971. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16972. }
  16973. } finally {
  16974. if (restore) {
  16975. _gl.bindFramebuffer(36160, _currentFramebuffer);
  16976. }
  16977. }
  16978. }
  16979. };
  16980. this.copyFramebufferToTexture = function (position, texture, level) {
  16981. var width = texture.image.width;
  16982. var height = texture.image.height;
  16983. var glFormat = utils.convert(texture.format);
  16984. textures.setTexture2D(texture, 0);
  16985. _gl.copyTexImage2D(3553, level || 0, glFormat, position.x, position.y, width, height, 0);
  16986. };
  16987. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  16988. var width = srcTexture.image.width;
  16989. var height = srcTexture.image.height;
  16990. var glFormat = utils.convert(dstTexture.format);
  16991. var glType = utils.convert(dstTexture.type);
  16992. textures.setTexture2D(dstTexture, 0);
  16993. if (srcTexture.isDataTexture) {
  16994. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16995. } else {
  16996. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  16997. }
  16998. };
  16999. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17000. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17001. detail: this
  17002. })); // eslint-disable-line no-undef
  17003. }
  17004. }
  17005. /**
  17006. * @author mrdoob / http://mrdoob.com/
  17007. * @author alteredq / http://alteredqualia.com/
  17008. */
  17009. function FogExp2(color, density) {
  17010. this.name = '';
  17011. this.color = new Color(color);
  17012. this.density = density !== undefined ? density : 0.00025;
  17013. }
  17014. Object.assign(FogExp2.prototype, {
  17015. isFogExp2: true,
  17016. clone: function () {
  17017. return new FogExp2(this.color, this.density);
  17018. },
  17019. toJSON: function ()
  17020. /* meta */
  17021. {
  17022. return {
  17023. type: 'FogExp2',
  17024. color: this.color.getHex(),
  17025. density: this.density
  17026. };
  17027. }
  17028. });
  17029. /**
  17030. * @author mrdoob / http://mrdoob.com/
  17031. * @author alteredq / http://alteredqualia.com/
  17032. */
  17033. function Fog(color, near, far) {
  17034. this.name = '';
  17035. this.color = new Color(color);
  17036. this.near = near !== undefined ? near : 1;
  17037. this.far = far !== undefined ? far : 1000;
  17038. }
  17039. Object.assign(Fog.prototype, {
  17040. isFog: true,
  17041. clone: function () {
  17042. return new Fog(this.color, this.near, this.far);
  17043. },
  17044. toJSON: function ()
  17045. /* meta */
  17046. {
  17047. return {
  17048. type: 'Fog',
  17049. color: this.color.getHex(),
  17050. near: this.near,
  17051. far: this.far
  17052. };
  17053. }
  17054. });
  17055. /**
  17056. * @author benaadams / https://twitter.com/ben_a_adams
  17057. */
  17058. function InterleavedBuffer(array, stride) {
  17059. this.array = array;
  17060. this.stride = stride;
  17061. this.count = array !== undefined ? array.length / stride : 0;
  17062. this.dynamic = false;
  17063. this.updateRange = {
  17064. offset: 0,
  17065. count: -1
  17066. };
  17067. this.version = 0;
  17068. }
  17069. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  17070. set: function (value) {
  17071. if (value === true) this.version++;
  17072. }
  17073. });
  17074. Object.assign(InterleavedBuffer.prototype, {
  17075. isInterleavedBuffer: true,
  17076. onUploadCallback: function () {},
  17077. setDynamic: function (value) {
  17078. this.dynamic = value;
  17079. return this;
  17080. },
  17081. copy: function (source) {
  17082. this.array = new source.array.constructor(source.array);
  17083. this.count = source.count;
  17084. this.stride = source.stride;
  17085. this.dynamic = source.dynamic;
  17086. return this;
  17087. },
  17088. copyAt: function (index1, attribute, index2) {
  17089. index1 *= this.stride;
  17090. index2 *= attribute.stride;
  17091. for (var i = 0, l = this.stride; i < l; i++) {
  17092. this.array[index1 + i] = attribute.array[index2 + i];
  17093. }
  17094. return this;
  17095. },
  17096. set: function (value, offset) {
  17097. if (offset === undefined) offset = 0;
  17098. this.array.set(value, offset);
  17099. return this;
  17100. },
  17101. clone: function () {
  17102. return new this.constructor().copy(this);
  17103. },
  17104. onUpload: function (callback) {
  17105. this.onUploadCallback = callback;
  17106. return this;
  17107. }
  17108. });
  17109. /**
  17110. * @author benaadams / https://twitter.com/ben_a_adams
  17111. */
  17112. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  17113. this.data = interleavedBuffer;
  17114. this.itemSize = itemSize;
  17115. this.offset = offset;
  17116. this.normalized = normalized === true;
  17117. }
  17118. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  17119. count: {
  17120. get: function () {
  17121. return this.data.count;
  17122. }
  17123. },
  17124. array: {
  17125. get: function () {
  17126. return this.data.array;
  17127. }
  17128. }
  17129. });
  17130. Object.assign(InterleavedBufferAttribute.prototype, {
  17131. isInterleavedBufferAttribute: true,
  17132. setX: function (index, x) {
  17133. this.data.array[index * this.data.stride + this.offset] = x;
  17134. return this;
  17135. },
  17136. setY: function (index, y) {
  17137. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17138. return this;
  17139. },
  17140. setZ: function (index, z) {
  17141. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17142. return this;
  17143. },
  17144. setW: function (index, w) {
  17145. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17146. return this;
  17147. },
  17148. getX: function (index) {
  17149. return this.data.array[index * this.data.stride + this.offset];
  17150. },
  17151. getY: function (index) {
  17152. return this.data.array[index * this.data.stride + this.offset + 1];
  17153. },
  17154. getZ: function (index) {
  17155. return this.data.array[index * this.data.stride + this.offset + 2];
  17156. },
  17157. getW: function (index) {
  17158. return this.data.array[index * this.data.stride + this.offset + 3];
  17159. },
  17160. setXY: function (index, x, y) {
  17161. index = index * this.data.stride + this.offset;
  17162. this.data.array[index + 0] = x;
  17163. this.data.array[index + 1] = y;
  17164. return this;
  17165. },
  17166. setXYZ: function (index, x, y, z) {
  17167. index = index * this.data.stride + this.offset;
  17168. this.data.array[index + 0] = x;
  17169. this.data.array[index + 1] = y;
  17170. this.data.array[index + 2] = z;
  17171. return this;
  17172. },
  17173. setXYZW: function (index, x, y, z, w) {
  17174. index = index * this.data.stride + this.offset;
  17175. this.data.array[index + 0] = x;
  17176. this.data.array[index + 1] = y;
  17177. this.data.array[index + 2] = z;
  17178. this.data.array[index + 3] = w;
  17179. return this;
  17180. }
  17181. });
  17182. /**
  17183. * @author alteredq / http://alteredqualia.com/
  17184. *
  17185. * parameters = {
  17186. * color: <hex>,
  17187. * map: new THREE.Texture( <Image> ),
  17188. * rotation: <float>,
  17189. * sizeAttenuation: <bool>
  17190. * }
  17191. */
  17192. function SpriteMaterial(parameters) {
  17193. Material.call(this);
  17194. this.type = 'SpriteMaterial';
  17195. this.color = new Color(0xffffff);
  17196. this.map = null;
  17197. this.rotation = 0;
  17198. this.sizeAttenuation = true;
  17199. this.transparent = true;
  17200. this.setValues(parameters);
  17201. }
  17202. SpriteMaterial.prototype = Object.create(Material.prototype);
  17203. SpriteMaterial.prototype.constructor = SpriteMaterial;
  17204. SpriteMaterial.prototype.isSpriteMaterial = true;
  17205. SpriteMaterial.prototype.copy = function (source) {
  17206. Material.prototype.copy.call(this, source);
  17207. this.color.copy(source.color);
  17208. this.map = source.map;
  17209. this.rotation = source.rotation;
  17210. this.sizeAttenuation = source.sizeAttenuation;
  17211. return this;
  17212. };
  17213. /**
  17214. * @author mikael emtinger / http://gomo.se/
  17215. * @author alteredq / http://alteredqualia.com/
  17216. */
  17217. var _geometry;
  17218. var _intersectPoint = new Vector3();
  17219. var _worldScale = new Vector3();
  17220. var _mvPosition = new Vector3();
  17221. var _alignedPosition = new Vector2();
  17222. var _rotatedPosition = new Vector2();
  17223. var _viewWorldMatrix = new Matrix4();
  17224. var _vA$1 = new Vector3();
  17225. var _vB$1 = new Vector3();
  17226. var _vC$1 = new Vector3();
  17227. var _uvA$1 = new Vector2();
  17228. var _uvB$1 = new Vector2();
  17229. var _uvC$1 = new Vector2();
  17230. function Sprite(material) {
  17231. Object3D.call(this);
  17232. this.type = 'Sprite';
  17233. if (_geometry === undefined) {
  17234. _geometry = new BufferGeometry();
  17235. 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]);
  17236. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17237. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17238. _geometry.addAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17239. _geometry.addAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17240. }
  17241. this.geometry = _geometry;
  17242. this.material = material !== undefined ? material : new SpriteMaterial();
  17243. this.center = new Vector2(0.5, 0.5);
  17244. }
  17245. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  17246. constructor: Sprite,
  17247. isSprite: true,
  17248. raycast: function (raycaster, intersects) {
  17249. if (raycaster.camera === null) {
  17250. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17251. }
  17252. _worldScale.setFromMatrixScale(this.matrixWorld);
  17253. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17254. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17255. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17256. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17257. _worldScale.multiplyScalar(-_mvPosition.z);
  17258. }
  17259. var rotation = this.material.rotation;
  17260. var sin, cos;
  17261. if (rotation !== 0) {
  17262. cos = Math.cos(rotation);
  17263. sin = Math.sin(rotation);
  17264. }
  17265. var center = this.center;
  17266. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17267. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17268. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17269. _uvA$1.set(0, 0);
  17270. _uvB$1.set(1, 0);
  17271. _uvC$1.set(1, 1); // check first triangle
  17272. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  17273. if (intersect === null) {
  17274. // check second triangle
  17275. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17276. _uvB$1.set(0, 1);
  17277. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  17278. if (intersect === null) {
  17279. return;
  17280. }
  17281. }
  17282. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17283. if (distance < raycaster.near || distance > raycaster.far) return;
  17284. intersects.push({
  17285. distance: distance,
  17286. point: _intersectPoint.clone(),
  17287. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  17288. face: null,
  17289. object: this
  17290. });
  17291. },
  17292. clone: function () {
  17293. return new this.constructor(this.material).copy(this);
  17294. },
  17295. copy: function (source) {
  17296. Object3D.prototype.copy.call(this, source);
  17297. if (source.center !== undefined) this.center.copy(source.center);
  17298. return this;
  17299. }
  17300. });
  17301. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17302. // compute position in camera space
  17303. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17304. if (sin !== undefined) {
  17305. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17306. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17307. } else {
  17308. _rotatedPosition.copy(_alignedPosition);
  17309. }
  17310. vertexPosition.copy(mvPosition);
  17311. vertexPosition.x += _rotatedPosition.x;
  17312. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17313. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17314. }
  17315. /**
  17316. * @author mikael emtinger / http://gomo.se/
  17317. * @author alteredq / http://alteredqualia.com/
  17318. * @author mrdoob / http://mrdoob.com/
  17319. */
  17320. var _v1$4 = new Vector3();
  17321. var _v2$2 = new Vector3();
  17322. function LOD() {
  17323. Object3D.call(this);
  17324. this.type = 'LOD';
  17325. Object.defineProperties(this, {
  17326. levels: {
  17327. enumerable: true,
  17328. value: []
  17329. }
  17330. });
  17331. this.autoUpdate = true;
  17332. }
  17333. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  17334. constructor: LOD,
  17335. isLOD: true,
  17336. copy: function (source) {
  17337. Object3D.prototype.copy.call(this, source, false);
  17338. var levels = source.levels;
  17339. for (var i = 0, l = levels.length; i < l; i++) {
  17340. var level = levels[i];
  17341. this.addLevel(level.object.clone(), level.distance);
  17342. }
  17343. return this;
  17344. },
  17345. addLevel: function (object, distance) {
  17346. if (distance === undefined) distance = 0;
  17347. distance = Math.abs(distance);
  17348. var levels = this.levels;
  17349. for (var l = 0; l < levels.length; l++) {
  17350. if (distance < levels[l].distance) {
  17351. break;
  17352. }
  17353. }
  17354. levels.splice(l, 0, {
  17355. distance: distance,
  17356. object: object
  17357. });
  17358. this.add(object);
  17359. return this;
  17360. },
  17361. getObjectForDistance: function (distance) {
  17362. var levels = this.levels;
  17363. for (var i = 1, l = levels.length; i < l; i++) {
  17364. if (distance < levels[i].distance) {
  17365. break;
  17366. }
  17367. }
  17368. return levels[i - 1].object;
  17369. },
  17370. raycast: function (raycaster, intersects) {
  17371. _v1$4.setFromMatrixPosition(this.matrixWorld);
  17372. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  17373. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17374. },
  17375. update: function (camera) {
  17376. var levels = this.levels;
  17377. if (levels.length > 1) {
  17378. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  17379. _v2$2.setFromMatrixPosition(this.matrixWorld);
  17380. var distance = _v1$4.distanceTo(_v2$2);
  17381. levels[0].object.visible = true;
  17382. for (var i = 1, l = levels.length; i < l; i++) {
  17383. if (distance >= levels[i].distance) {
  17384. levels[i - 1].object.visible = false;
  17385. levels[i].object.visible = true;
  17386. } else {
  17387. break;
  17388. }
  17389. }
  17390. for (; i < l; i++) {
  17391. levels[i].object.visible = false;
  17392. }
  17393. }
  17394. },
  17395. toJSON: function (meta) {
  17396. var data = Object3D.prototype.toJSON.call(this, meta);
  17397. data.object.levels = [];
  17398. var levels = this.levels;
  17399. for (var i = 0, l = levels.length; i < l; i++) {
  17400. var level = levels[i];
  17401. data.object.levels.push({
  17402. object: level.object.uuid,
  17403. distance: level.distance
  17404. });
  17405. }
  17406. return data;
  17407. }
  17408. });
  17409. /**
  17410. * @author mikael emtinger / http://gomo.se/
  17411. * @author alteredq / http://alteredqualia.com/
  17412. * @author ikerr / http://verold.com
  17413. */
  17414. function SkinnedMesh(geometry, material) {
  17415. if (geometry && geometry.isGeometry) {
  17416. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17417. }
  17418. Mesh.call(this, geometry, material);
  17419. this.type = 'SkinnedMesh';
  17420. this.bindMode = 'attached';
  17421. this.bindMatrix = new Matrix4();
  17422. this.bindMatrixInverse = new Matrix4();
  17423. }
  17424. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17425. constructor: SkinnedMesh,
  17426. isSkinnedMesh: true,
  17427. bind: function (skeleton, bindMatrix) {
  17428. this.skeleton = skeleton;
  17429. if (bindMatrix === undefined) {
  17430. this.updateMatrixWorld(true);
  17431. this.skeleton.calculateInverses();
  17432. bindMatrix = this.matrixWorld;
  17433. }
  17434. this.bindMatrix.copy(bindMatrix);
  17435. this.bindMatrixInverse.getInverse(bindMatrix);
  17436. },
  17437. pose: function () {
  17438. this.skeleton.pose();
  17439. },
  17440. normalizeSkinWeights: function () {
  17441. var vector = new Vector4();
  17442. var skinWeight = this.geometry.attributes.skinWeight;
  17443. for (var i = 0, l = skinWeight.count; i < l; i++) {
  17444. vector.x = skinWeight.getX(i);
  17445. vector.y = skinWeight.getY(i);
  17446. vector.z = skinWeight.getZ(i);
  17447. vector.w = skinWeight.getW(i);
  17448. var scale = 1.0 / vector.manhattanLength();
  17449. if (scale !== Infinity) {
  17450. vector.multiplyScalar(scale);
  17451. } else {
  17452. vector.set(1, 0, 0, 0); // do something reasonable
  17453. }
  17454. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17455. }
  17456. },
  17457. updateMatrixWorld: function (force) {
  17458. Mesh.prototype.updateMatrixWorld.call(this, force);
  17459. if (this.bindMode === 'attached') {
  17460. this.bindMatrixInverse.getInverse(this.matrixWorld);
  17461. } else if (this.bindMode === 'detached') {
  17462. this.bindMatrixInverse.getInverse(this.bindMatrix);
  17463. } else {
  17464. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17465. }
  17466. },
  17467. clone: function () {
  17468. return new this.constructor(this.geometry, this.material).copy(this);
  17469. }
  17470. });
  17471. /**
  17472. * @author mikael emtinger / http://gomo.se/
  17473. * @author alteredq / http://alteredqualia.com/
  17474. * @author michael guerrero / http://realitymeltdown.com
  17475. * @author ikerr / http://verold.com
  17476. */
  17477. var _offsetMatrix = new Matrix4();
  17478. var _identityMatrix = new Matrix4();
  17479. function Skeleton(bones, boneInverses) {
  17480. // copy the bone array
  17481. bones = bones || [];
  17482. this.bones = bones.slice(0);
  17483. this.boneMatrices = new Float32Array(this.bones.length * 16);
  17484. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  17485. if (boneInverses === undefined) {
  17486. this.calculateInverses();
  17487. } else {
  17488. if (this.bones.length === boneInverses.length) {
  17489. this.boneInverses = boneInverses.slice(0);
  17490. } else {
  17491. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  17492. this.boneInverses = [];
  17493. for (var i = 0, il = this.bones.length; i < il; i++) {
  17494. this.boneInverses.push(new Matrix4());
  17495. }
  17496. }
  17497. }
  17498. }
  17499. Object.assign(Skeleton.prototype, {
  17500. calculateInverses: function () {
  17501. this.boneInverses = [];
  17502. for (var i = 0, il = this.bones.length; i < il; i++) {
  17503. var inverse = new Matrix4();
  17504. if (this.bones[i]) {
  17505. inverse.getInverse(this.bones[i].matrixWorld);
  17506. }
  17507. this.boneInverses.push(inverse);
  17508. }
  17509. },
  17510. pose: function () {
  17511. var bone, i, il; // recover the bind-time world matrices
  17512. for (i = 0, il = this.bones.length; i < il; i++) {
  17513. bone = this.bones[i];
  17514. if (bone) {
  17515. bone.matrixWorld.getInverse(this.boneInverses[i]);
  17516. }
  17517. } // compute the local matrices, positions, rotations and scales
  17518. for (i = 0, il = this.bones.length; i < il; i++) {
  17519. bone = this.bones[i];
  17520. if (bone) {
  17521. if (bone.parent && bone.parent.isBone) {
  17522. bone.matrix.getInverse(bone.parent.matrixWorld);
  17523. bone.matrix.multiply(bone.matrixWorld);
  17524. } else {
  17525. bone.matrix.copy(bone.matrixWorld);
  17526. }
  17527. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17528. }
  17529. }
  17530. },
  17531. update: function () {
  17532. var bones = this.bones;
  17533. var boneInverses = this.boneInverses;
  17534. var boneMatrices = this.boneMatrices;
  17535. var boneTexture = this.boneTexture; // flatten bone matrices to array
  17536. for (var i = 0, il = bones.length; i < il; i++) {
  17537. // compute the offset between the current and the original transform
  17538. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17539. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17540. _offsetMatrix.toArray(boneMatrices, i * 16);
  17541. }
  17542. if (boneTexture !== undefined) {
  17543. boneTexture.needsUpdate = true;
  17544. }
  17545. },
  17546. clone: function () {
  17547. return new Skeleton(this.bones, this.boneInverses);
  17548. },
  17549. getBoneByName: function (name) {
  17550. for (var i = 0, il = this.bones.length; i < il; i++) {
  17551. var bone = this.bones[i];
  17552. if (bone.name === name) {
  17553. return bone;
  17554. }
  17555. }
  17556. return undefined;
  17557. }
  17558. });
  17559. /**
  17560. * @author mikael emtinger / http://gomo.se/
  17561. * @author alteredq / http://alteredqualia.com/
  17562. * @author ikerr / http://verold.com
  17563. */
  17564. function Bone() {
  17565. Object3D.call(this);
  17566. this.type = 'Bone';
  17567. }
  17568. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  17569. constructor: Bone,
  17570. isBone: true
  17571. });
  17572. /**
  17573. * @author mrdoob / http://mrdoob.com/
  17574. */
  17575. function InstancedMesh(geometry, material, count) {
  17576. Mesh.call(this, geometry, material);
  17577. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  17578. this.count = count;
  17579. }
  17580. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  17581. constructor: InstancedMesh,
  17582. isInstancedMesh: true,
  17583. raycast: function () {},
  17584. setMatrixAt: function (index, matrix) {
  17585. matrix.toArray(this.instanceMatrix.array, index * 16);
  17586. },
  17587. updateMorphTargets: function () {}
  17588. });
  17589. /**
  17590. * @author mrdoob / http://mrdoob.com/
  17591. * @author alteredq / http://alteredqualia.com/
  17592. *
  17593. * parameters = {
  17594. * color: <hex>,
  17595. * opacity: <float>,
  17596. *
  17597. * linewidth: <float>,
  17598. * linecap: "round",
  17599. * linejoin: "round"
  17600. * }
  17601. */
  17602. function LineBasicMaterial(parameters) {
  17603. Material.call(this);
  17604. this.type = 'LineBasicMaterial';
  17605. this.color = new Color(0xffffff);
  17606. this.linewidth = 1;
  17607. this.linecap = 'round';
  17608. this.linejoin = 'round';
  17609. this.setValues(parameters);
  17610. }
  17611. LineBasicMaterial.prototype = Object.create(Material.prototype);
  17612. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  17613. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17614. LineBasicMaterial.prototype.copy = function (source) {
  17615. Material.prototype.copy.call(this, source);
  17616. this.color.copy(source.color);
  17617. this.linewidth = source.linewidth;
  17618. this.linecap = source.linecap;
  17619. this.linejoin = source.linejoin;
  17620. return this;
  17621. };
  17622. /**
  17623. * @author mrdoob / http://mrdoob.com/
  17624. */
  17625. var _start = new Vector3();
  17626. var _end = new Vector3();
  17627. var _inverseMatrix$1 = new Matrix4();
  17628. var _ray$1 = new Ray();
  17629. var _sphere$2 = new Sphere();
  17630. function Line(geometry, material, mode) {
  17631. if (mode === 1) {
  17632. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  17633. }
  17634. Object3D.call(this);
  17635. this.type = 'Line';
  17636. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17637. this.material = material !== undefined ? material : new LineBasicMaterial({
  17638. color: Math.random() * 0xffffff
  17639. });
  17640. }
  17641. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  17642. constructor: Line,
  17643. isLine: true,
  17644. computeLineDistances: function () {
  17645. var geometry = this.geometry;
  17646. if (geometry.isBufferGeometry) {
  17647. // we assume non-indexed geometry
  17648. if (geometry.index === null) {
  17649. var positionAttribute = geometry.attributes.position;
  17650. var lineDistances = [0];
  17651. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  17652. _start.fromBufferAttribute(positionAttribute, i - 1);
  17653. _end.fromBufferAttribute(positionAttribute, i);
  17654. lineDistances[i] = lineDistances[i - 1];
  17655. lineDistances[i] += _start.distanceTo(_end);
  17656. }
  17657. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17658. } else {
  17659. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17660. }
  17661. } else if (geometry.isGeometry) {
  17662. var vertices = geometry.vertices;
  17663. var lineDistances = geometry.lineDistances;
  17664. lineDistances[0] = 0;
  17665. for (var i = 1, l = vertices.length; i < l; i++) {
  17666. lineDistances[i] = lineDistances[i - 1];
  17667. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  17668. }
  17669. }
  17670. return this;
  17671. },
  17672. raycast: function (raycaster, intersects) {
  17673. var precision = raycaster.linePrecision;
  17674. var geometry = this.geometry;
  17675. var matrixWorld = this.matrixWorld; // Checking boundingSphere distance to ray
  17676. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17677. _sphere$2.copy(geometry.boundingSphere);
  17678. _sphere$2.applyMatrix4(matrixWorld);
  17679. _sphere$2.radius += precision;
  17680. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  17681. _inverseMatrix$1.getInverse(matrixWorld);
  17682. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17683. var localPrecision = precision / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17684. var localPrecisionSq = localPrecision * localPrecision;
  17685. var vStart = new Vector3();
  17686. var vEnd = new Vector3();
  17687. var interSegment = new Vector3();
  17688. var interRay = new Vector3();
  17689. var step = this && this.isLineSegments ? 2 : 1;
  17690. if (geometry.isBufferGeometry) {
  17691. var index = geometry.index;
  17692. var attributes = geometry.attributes;
  17693. var positions = attributes.position.array;
  17694. if (index !== null) {
  17695. var indices = index.array;
  17696. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  17697. var a = indices[i];
  17698. var b = indices[i + 1];
  17699. vStart.fromArray(positions, a * 3);
  17700. vEnd.fromArray(positions, b * 3);
  17701. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17702. if (distSq > localPrecisionSq) continue;
  17703. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17704. var distance = raycaster.ray.origin.distanceTo(interRay);
  17705. if (distance < raycaster.near || distance > raycaster.far) continue;
  17706. intersects.push({
  17707. distance: distance,
  17708. // What do we want? intersection point on the ray or on the segment??
  17709. // point: raycaster.ray.at( distance ),
  17710. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17711. index: i,
  17712. face: null,
  17713. faceIndex: null,
  17714. object: this
  17715. });
  17716. }
  17717. } else {
  17718. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  17719. vStart.fromArray(positions, 3 * i);
  17720. vEnd.fromArray(positions, 3 * i + 3);
  17721. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17722. if (distSq > localPrecisionSq) continue;
  17723. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17724. var distance = raycaster.ray.origin.distanceTo(interRay);
  17725. if (distance < raycaster.near || distance > raycaster.far) continue;
  17726. intersects.push({
  17727. distance: distance,
  17728. // What do we want? intersection point on the ray or on the segment??
  17729. // point: raycaster.ray.at( distance ),
  17730. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17731. index: i,
  17732. face: null,
  17733. faceIndex: null,
  17734. object: this
  17735. });
  17736. }
  17737. }
  17738. } else if (geometry.isGeometry) {
  17739. var vertices = geometry.vertices;
  17740. var nbVertices = vertices.length;
  17741. for (var i = 0; i < nbVertices - 1; i += step) {
  17742. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  17743. if (distSq > localPrecisionSq) continue;
  17744. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17745. var distance = raycaster.ray.origin.distanceTo(interRay);
  17746. if (distance < raycaster.near || distance > raycaster.far) continue;
  17747. intersects.push({
  17748. distance: distance,
  17749. // What do we want? intersection point on the ray or on the segment??
  17750. // point: raycaster.ray.at( distance ),
  17751. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17752. index: i,
  17753. face: null,
  17754. faceIndex: null,
  17755. object: this
  17756. });
  17757. }
  17758. }
  17759. },
  17760. clone: function () {
  17761. return new this.constructor(this.geometry, this.material).copy(this);
  17762. }
  17763. });
  17764. /**
  17765. * @author mrdoob / http://mrdoob.com/
  17766. */
  17767. var _start$1 = new Vector3();
  17768. var _end$1 = new Vector3();
  17769. function LineSegments(geometry, material) {
  17770. Line.call(this, geometry, material);
  17771. this.type = 'LineSegments';
  17772. }
  17773. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  17774. constructor: LineSegments,
  17775. isLineSegments: true,
  17776. computeLineDistances: function () {
  17777. var geometry = this.geometry;
  17778. if (geometry.isBufferGeometry) {
  17779. // we assume non-indexed geometry
  17780. if (geometry.index === null) {
  17781. var positionAttribute = geometry.attributes.position;
  17782. var lineDistances = [];
  17783. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  17784. _start$1.fromBufferAttribute(positionAttribute, i);
  17785. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  17786. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17787. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17788. }
  17789. geometry.addAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17790. } else {
  17791. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17792. }
  17793. } else if (geometry.isGeometry) {
  17794. var vertices = geometry.vertices;
  17795. var lineDistances = geometry.lineDistances;
  17796. for (var i = 0, l = vertices.length; i < l; i += 2) {
  17797. _start$1.copy(vertices[i]);
  17798. _end$1.copy(vertices[i + 1]);
  17799. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17800. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  17801. }
  17802. }
  17803. return this;
  17804. }
  17805. });
  17806. /**
  17807. * @author mgreter / http://github.com/mgreter
  17808. */
  17809. function LineLoop(geometry, material) {
  17810. Line.call(this, geometry, material);
  17811. this.type = 'LineLoop';
  17812. }
  17813. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  17814. constructor: LineLoop,
  17815. isLineLoop: true
  17816. });
  17817. /**
  17818. * @author mrdoob / http://mrdoob.com/
  17819. * @author alteredq / http://alteredqualia.com/
  17820. *
  17821. * parameters = {
  17822. * color: <hex>,
  17823. * opacity: <float>,
  17824. * map: new THREE.Texture( <Image> ),
  17825. *
  17826. * size: <float>,
  17827. * sizeAttenuation: <bool>
  17828. *
  17829. * morphTargets: <bool>
  17830. * }
  17831. */
  17832. function PointsMaterial(parameters) {
  17833. Material.call(this);
  17834. this.type = 'PointsMaterial';
  17835. this.color = new Color(0xffffff);
  17836. this.map = null;
  17837. this.size = 1;
  17838. this.sizeAttenuation = true;
  17839. this.morphTargets = false;
  17840. this.setValues(parameters);
  17841. }
  17842. PointsMaterial.prototype = Object.create(Material.prototype);
  17843. PointsMaterial.prototype.constructor = PointsMaterial;
  17844. PointsMaterial.prototype.isPointsMaterial = true;
  17845. PointsMaterial.prototype.copy = function (source) {
  17846. Material.prototype.copy.call(this, source);
  17847. this.color.copy(source.color);
  17848. this.map = source.map;
  17849. this.size = source.size;
  17850. this.sizeAttenuation = source.sizeAttenuation;
  17851. this.morphTargets = source.morphTargets;
  17852. return this;
  17853. };
  17854. /**
  17855. * @author alteredq / http://alteredqualia.com/
  17856. */
  17857. var _inverseMatrix$2 = new Matrix4();
  17858. var _ray$2 = new Ray();
  17859. var _sphere$3 = new Sphere();
  17860. var _position$1 = new Vector3();
  17861. function Points(geometry, material) {
  17862. Object3D.call(this);
  17863. this.type = 'Points';
  17864. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  17865. this.material = material !== undefined ? material : new PointsMaterial({
  17866. color: Math.random() * 0xffffff
  17867. });
  17868. this.updateMorphTargets();
  17869. }
  17870. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  17871. constructor: Points,
  17872. isPoints: true,
  17873. raycast: function (raycaster, intersects) {
  17874. var geometry = this.geometry;
  17875. var matrixWorld = this.matrixWorld;
  17876. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  17877. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17878. _sphere$3.copy(geometry.boundingSphere);
  17879. _sphere$3.applyMatrix4(matrixWorld);
  17880. _sphere$3.radius += threshold;
  17881. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  17882. _inverseMatrix$2.getInverse(matrixWorld);
  17883. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  17884. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17885. var localThresholdSq = localThreshold * localThreshold;
  17886. if (geometry.isBufferGeometry) {
  17887. var index = geometry.index;
  17888. var attributes = geometry.attributes;
  17889. var positions = attributes.position.array;
  17890. if (index !== null) {
  17891. var indices = index.array;
  17892. for (var i = 0, il = indices.length; i < il; i++) {
  17893. var a = indices[i];
  17894. _position$1.fromArray(positions, a * 3);
  17895. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17896. }
  17897. } else {
  17898. for (var i = 0, l = positions.length / 3; i < l; i++) {
  17899. _position$1.fromArray(positions, i * 3);
  17900. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17901. }
  17902. }
  17903. } else {
  17904. var vertices = geometry.vertices;
  17905. for (var i = 0, l = vertices.length; i < l; i++) {
  17906. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17907. }
  17908. }
  17909. },
  17910. updateMorphTargets: function () {
  17911. var geometry = this.geometry;
  17912. var m, ml, name;
  17913. if (geometry.isBufferGeometry) {
  17914. var morphAttributes = geometry.morphAttributes;
  17915. var keys = Object.keys(morphAttributes);
  17916. if (keys.length > 0) {
  17917. var morphAttribute = morphAttributes[keys[0]];
  17918. if (morphAttribute !== undefined) {
  17919. this.morphTargetInfluences = [];
  17920. this.morphTargetDictionary = {};
  17921. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  17922. name = morphAttribute[m].name || String(m);
  17923. this.morphTargetInfluences.push(0);
  17924. this.morphTargetDictionary[name] = m;
  17925. }
  17926. }
  17927. }
  17928. } else {
  17929. var morphTargets = geometry.morphTargets;
  17930. if (morphTargets !== undefined && morphTargets.length > 0) {
  17931. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17932. }
  17933. }
  17934. },
  17935. clone: function () {
  17936. return new this.constructor(this.geometry, this.material).copy(this);
  17937. }
  17938. });
  17939. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17940. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  17941. if (rayPointDistanceSq < localThresholdSq) {
  17942. var intersectPoint = new Vector3();
  17943. _ray$2.closestPointToPoint(point, intersectPoint);
  17944. intersectPoint.applyMatrix4(matrixWorld);
  17945. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17946. if (distance < raycaster.near || distance > raycaster.far) return;
  17947. intersects.push({
  17948. distance: distance,
  17949. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17950. point: intersectPoint,
  17951. index: index,
  17952. face: null,
  17953. object: object
  17954. });
  17955. }
  17956. }
  17957. /**
  17958. * @author mrdoob / http://mrdoob.com/
  17959. */
  17960. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17961. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17962. this.format = format !== undefined ? format : RGBFormat;
  17963. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17964. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17965. this.generateMipmaps = false;
  17966. }
  17967. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  17968. constructor: VideoTexture,
  17969. isVideoTexture: true,
  17970. update: function () {
  17971. var video = this.image;
  17972. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  17973. this.needsUpdate = true;
  17974. }
  17975. }
  17976. });
  17977. /**
  17978. * @author alteredq / http://alteredqualia.com/
  17979. */
  17980. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17981. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17982. this.image = {
  17983. width: width,
  17984. height: height
  17985. };
  17986. this.mipmaps = mipmaps; // no flipping for cube textures
  17987. // (also flipping doesn't work for compressed textures )
  17988. this.flipY = false; // can't generate mipmaps for compressed textures
  17989. // mips must be embedded in DDS files
  17990. this.generateMipmaps = false;
  17991. }
  17992. CompressedTexture.prototype = Object.create(Texture.prototype);
  17993. CompressedTexture.prototype.constructor = CompressedTexture;
  17994. CompressedTexture.prototype.isCompressedTexture = true;
  17995. /**
  17996. * @author mrdoob / http://mrdoob.com/
  17997. */
  17998. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17999. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18000. this.needsUpdate = true;
  18001. }
  18002. CanvasTexture.prototype = Object.create(Texture.prototype);
  18003. CanvasTexture.prototype.constructor = CanvasTexture;
  18004. CanvasTexture.prototype.isCanvasTexture = true;
  18005. /**
  18006. * @author Matt DesLauriers / @mattdesl
  18007. * @author atix / arthursilber.de
  18008. */
  18009. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  18010. format = format !== undefined ? format : DepthFormat;
  18011. if (format !== DepthFormat && format !== DepthStencilFormat) {
  18012. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  18013. }
  18014. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  18015. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  18016. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18017. this.image = {
  18018. width: width,
  18019. height: height
  18020. };
  18021. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18022. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18023. this.flipY = false;
  18024. this.generateMipmaps = false;
  18025. }
  18026. DepthTexture.prototype = Object.create(Texture.prototype);
  18027. DepthTexture.prototype.constructor = DepthTexture;
  18028. DepthTexture.prototype.isDepthTexture = true;
  18029. /**
  18030. * @author mrdoob / http://mrdoob.com/
  18031. * @author Mugen87 / https://github.com/Mugen87
  18032. */
  18033. function WireframeGeometry(geometry) {
  18034. BufferGeometry.call(this);
  18035. this.type = 'WireframeGeometry'; // buffer
  18036. var vertices = []; // helper variables
  18037. var i, j, l, o, ol;
  18038. var edge = [0, 0],
  18039. edges = {},
  18040. e,
  18041. edge1,
  18042. edge2;
  18043. var key,
  18044. keys = ['a', 'b', 'c'];
  18045. var vertex; // different logic for Geometry and BufferGeometry
  18046. if (geometry && geometry.isGeometry) {
  18047. // create a data structure that contains all edges without duplicates
  18048. var faces = geometry.faces;
  18049. for (i = 0, l = faces.length; i < l; i++) {
  18050. var face = faces[i];
  18051. for (j = 0; j < 3; j++) {
  18052. edge1 = face[keys[j]];
  18053. edge2 = face[keys[(j + 1) % 3]];
  18054. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18055. edge[1] = Math.max(edge1, edge2);
  18056. key = edge[0] + ',' + edge[1];
  18057. if (edges[key] === undefined) {
  18058. edges[key] = {
  18059. index1: edge[0],
  18060. index2: edge[1]
  18061. };
  18062. }
  18063. }
  18064. } // generate vertices
  18065. for (key in edges) {
  18066. e = edges[key];
  18067. vertex = geometry.vertices[e.index1];
  18068. vertices.push(vertex.x, vertex.y, vertex.z);
  18069. vertex = geometry.vertices[e.index2];
  18070. vertices.push(vertex.x, vertex.y, vertex.z);
  18071. }
  18072. } else if (geometry && geometry.isBufferGeometry) {
  18073. var position, indices, groups;
  18074. var group, start, count;
  18075. var index1, index2;
  18076. vertex = new Vector3();
  18077. if (geometry.index !== null) {
  18078. // indexed BufferGeometry
  18079. position = geometry.attributes.position;
  18080. indices = geometry.index;
  18081. groups = geometry.groups;
  18082. if (groups.length === 0) {
  18083. groups = [{
  18084. start: 0,
  18085. count: indices.count,
  18086. materialIndex: 0
  18087. }];
  18088. } // create a data structure that contains all eges without duplicates
  18089. for (o = 0, ol = groups.length; o < ol; ++o) {
  18090. group = groups[o];
  18091. start = group.start;
  18092. count = group.count;
  18093. for (i = start, l = start + count; i < l; i += 3) {
  18094. for (j = 0; j < 3; j++) {
  18095. edge1 = indices.getX(i + j);
  18096. edge2 = indices.getX(i + (j + 1) % 3);
  18097. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18098. edge[1] = Math.max(edge1, edge2);
  18099. key = edge[0] + ',' + edge[1];
  18100. if (edges[key] === undefined) {
  18101. edges[key] = {
  18102. index1: edge[0],
  18103. index2: edge[1]
  18104. };
  18105. }
  18106. }
  18107. }
  18108. } // generate vertices
  18109. for (key in edges) {
  18110. e = edges[key];
  18111. vertex.fromBufferAttribute(position, e.index1);
  18112. vertices.push(vertex.x, vertex.y, vertex.z);
  18113. vertex.fromBufferAttribute(position, e.index2);
  18114. vertices.push(vertex.x, vertex.y, vertex.z);
  18115. }
  18116. } else {
  18117. // non-indexed BufferGeometry
  18118. position = geometry.attributes.position;
  18119. for (i = 0, l = position.count / 3; i < l; i++) {
  18120. for (j = 0; j < 3; j++) {
  18121. // three edges per triangle, an edge is represented as (index1, index2)
  18122. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18123. index1 = 3 * i + j;
  18124. vertex.fromBufferAttribute(position, index1);
  18125. vertices.push(vertex.x, vertex.y, vertex.z);
  18126. index2 = 3 * i + (j + 1) % 3;
  18127. vertex.fromBufferAttribute(position, index2);
  18128. vertices.push(vertex.x, vertex.y, vertex.z);
  18129. }
  18130. }
  18131. }
  18132. } // build geometry
  18133. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18134. }
  18135. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  18136. WireframeGeometry.prototype.constructor = WireframeGeometry;
  18137. /**
  18138. * @author zz85 / https://github.com/zz85
  18139. * @author Mugen87 / https://github.com/Mugen87
  18140. *
  18141. * Parametric Surfaces Geometry
  18142. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18143. */
  18144. // ParametricGeometry
  18145. function ParametricGeometry(func, slices, stacks) {
  18146. Geometry.call(this);
  18147. this.type = 'ParametricGeometry';
  18148. this.parameters = {
  18149. func: func,
  18150. slices: slices,
  18151. stacks: stacks
  18152. };
  18153. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  18154. this.mergeVertices();
  18155. }
  18156. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  18157. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  18158. function ParametricBufferGeometry(func, slices, stacks) {
  18159. BufferGeometry.call(this);
  18160. this.type = 'ParametricBufferGeometry';
  18161. this.parameters = {
  18162. func: func,
  18163. slices: slices,
  18164. stacks: stacks
  18165. }; // buffers
  18166. var indices = [];
  18167. var vertices = [];
  18168. var normals = [];
  18169. var uvs = [];
  18170. var EPS = 0.00001;
  18171. var normal = new Vector3();
  18172. var p0 = new Vector3(),
  18173. p1 = new Vector3();
  18174. var pu = new Vector3(),
  18175. pv = new Vector3();
  18176. var i, j;
  18177. if (func.length < 3) {
  18178. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18179. } // generate vertices, normals and uvs
  18180. var sliceCount = slices + 1;
  18181. for (i = 0; i <= stacks; i++) {
  18182. var v = i / stacks;
  18183. for (j = 0; j <= slices; j++) {
  18184. var u = j / slices; // vertex
  18185. func(u, v, p0);
  18186. vertices.push(p0.x, p0.y, p0.z); // normal
  18187. // approximate tangent vectors via finite differences
  18188. if (u - EPS >= 0) {
  18189. func(u - EPS, v, p1);
  18190. pu.subVectors(p0, p1);
  18191. } else {
  18192. func(u + EPS, v, p1);
  18193. pu.subVectors(p1, p0);
  18194. }
  18195. if (v - EPS >= 0) {
  18196. func(u, v - EPS, p1);
  18197. pv.subVectors(p0, p1);
  18198. } else {
  18199. func(u, v + EPS, p1);
  18200. pv.subVectors(p1, p0);
  18201. } // cross product of tangent vectors returns surface normal
  18202. normal.crossVectors(pu, pv).normalize();
  18203. normals.push(normal.x, normal.y, normal.z); // uv
  18204. uvs.push(u, v);
  18205. }
  18206. } // generate indices
  18207. for (i = 0; i < stacks; i++) {
  18208. for (j = 0; j < slices; j++) {
  18209. var a = i * sliceCount + j;
  18210. var b = i * sliceCount + j + 1;
  18211. var c = (i + 1) * sliceCount + j + 1;
  18212. var d = (i + 1) * sliceCount + j; // faces one and two
  18213. indices.push(a, b, d);
  18214. indices.push(b, c, d);
  18215. }
  18216. } // build geometry
  18217. this.setIndex(indices);
  18218. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18219. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18220. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18221. }
  18222. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18223. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  18224. /**
  18225. * @author clockworkgeek / https://github.com/clockworkgeek
  18226. * @author timothypratley / https://github.com/timothypratley
  18227. * @author WestLangley / http://github.com/WestLangley
  18228. * @author Mugen87 / https://github.com/Mugen87
  18229. */
  18230. // PolyhedronGeometry
  18231. function PolyhedronGeometry(vertices, indices, radius, detail) {
  18232. Geometry.call(this);
  18233. this.type = 'PolyhedronGeometry';
  18234. this.parameters = {
  18235. vertices: vertices,
  18236. indices: indices,
  18237. radius: radius,
  18238. detail: detail
  18239. };
  18240. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  18241. this.mergeVertices();
  18242. }
  18243. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  18244. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  18245. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  18246. BufferGeometry.call(this);
  18247. this.type = 'PolyhedronBufferGeometry';
  18248. this.parameters = {
  18249. vertices: vertices,
  18250. indices: indices,
  18251. radius: radius,
  18252. detail: detail
  18253. };
  18254. radius = radius || 1;
  18255. detail = detail || 0; // default buffer data
  18256. var vertexBuffer = [];
  18257. var uvBuffer = []; // the subdivision creates the vertex buffer data
  18258. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  18259. applyRadius(radius); // finally, create the uv data
  18260. generateUVs(); // build non-indexed geometry
  18261. this.addAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  18262. this.addAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  18263. this.addAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  18264. if (detail === 0) {
  18265. this.computeVertexNormals(); // flat normals
  18266. } else {
  18267. this.normalizeNormals(); // smooth normals
  18268. } // helper functions
  18269. function subdivide(detail) {
  18270. var a = new Vector3();
  18271. var b = new Vector3();
  18272. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  18273. for (var i = 0; i < indices.length; i += 3) {
  18274. // get the vertices of the face
  18275. getVertexByIndex(indices[i + 0], a);
  18276. getVertexByIndex(indices[i + 1], b);
  18277. getVertexByIndex(indices[i + 2], c); // perform subdivision
  18278. subdivideFace(a, b, c, detail);
  18279. }
  18280. }
  18281. function subdivideFace(a, b, c, detail) {
  18282. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  18283. var v = [];
  18284. var i, j; // construct all of the vertices for this subdivision
  18285. for (i = 0; i <= cols; i++) {
  18286. v[i] = [];
  18287. var aj = a.clone().lerp(c, i / cols);
  18288. var bj = b.clone().lerp(c, i / cols);
  18289. var rows = cols - i;
  18290. for (j = 0; j <= rows; j++) {
  18291. if (j === 0 && i === cols) {
  18292. v[i][j] = aj;
  18293. } else {
  18294. v[i][j] = aj.clone().lerp(bj, j / rows);
  18295. }
  18296. }
  18297. } // construct all of the faces
  18298. for (i = 0; i < cols; i++) {
  18299. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  18300. var k = Math.floor(j / 2);
  18301. if (j % 2 === 0) {
  18302. pushVertex(v[i][k + 1]);
  18303. pushVertex(v[i + 1][k]);
  18304. pushVertex(v[i][k]);
  18305. } else {
  18306. pushVertex(v[i][k + 1]);
  18307. pushVertex(v[i + 1][k + 1]);
  18308. pushVertex(v[i + 1][k]);
  18309. }
  18310. }
  18311. }
  18312. }
  18313. function applyRadius(radius) {
  18314. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  18315. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18316. vertex.x = vertexBuffer[i + 0];
  18317. vertex.y = vertexBuffer[i + 1];
  18318. vertex.z = vertexBuffer[i + 2];
  18319. vertex.normalize().multiplyScalar(radius);
  18320. vertexBuffer[i + 0] = vertex.x;
  18321. vertexBuffer[i + 1] = vertex.y;
  18322. vertexBuffer[i + 2] = vertex.z;
  18323. }
  18324. }
  18325. function generateUVs() {
  18326. var vertex = new Vector3();
  18327. for (var i = 0; i < vertexBuffer.length; i += 3) {
  18328. vertex.x = vertexBuffer[i + 0];
  18329. vertex.y = vertexBuffer[i + 1];
  18330. vertex.z = vertexBuffer[i + 2];
  18331. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  18332. var v = inclination(vertex) / Math.PI + 0.5;
  18333. uvBuffer.push(u, 1 - v);
  18334. }
  18335. correctUVs();
  18336. correctSeam();
  18337. }
  18338. function correctSeam() {
  18339. // handle case when face straddles the seam, see #3269
  18340. for (var i = 0; i < uvBuffer.length; i += 6) {
  18341. // uv data of a single face
  18342. var x0 = uvBuffer[i + 0];
  18343. var x1 = uvBuffer[i + 2];
  18344. var x2 = uvBuffer[i + 4];
  18345. var max = Math.max(x0, x1, x2);
  18346. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  18347. if (max > 0.9 && min < 0.1) {
  18348. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  18349. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  18350. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  18351. }
  18352. }
  18353. }
  18354. function pushVertex(vertex) {
  18355. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  18356. }
  18357. function getVertexByIndex(index, vertex) {
  18358. var stride = index * 3;
  18359. vertex.x = vertices[stride + 0];
  18360. vertex.y = vertices[stride + 1];
  18361. vertex.z = vertices[stride + 2];
  18362. }
  18363. function correctUVs() {
  18364. var a = new Vector3();
  18365. var b = new Vector3();
  18366. var c = new Vector3();
  18367. var centroid = new Vector3();
  18368. var uvA = new Vector2();
  18369. var uvB = new Vector2();
  18370. var uvC = new Vector2();
  18371. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  18372. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  18373. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  18374. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  18375. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  18376. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  18377. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  18378. centroid.copy(a).add(b).add(c).divideScalar(3);
  18379. var azi = azimuth(centroid);
  18380. correctUV(uvA, j + 0, a, azi);
  18381. correctUV(uvB, j + 2, b, azi);
  18382. correctUV(uvC, j + 4, c, azi);
  18383. }
  18384. }
  18385. function correctUV(uv, stride, vector, azimuth) {
  18386. if (azimuth < 0 && uv.x === 1) {
  18387. uvBuffer[stride] = uv.x - 1;
  18388. }
  18389. if (vector.x === 0 && vector.z === 0) {
  18390. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  18391. }
  18392. } // Angle around the Y axis, counter-clockwise when looking from above.
  18393. function azimuth(vector) {
  18394. return Math.atan2(vector.z, -vector.x);
  18395. } // Angle above the XZ plane.
  18396. function inclination(vector) {
  18397. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  18398. }
  18399. }
  18400. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18401. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  18402. /**
  18403. * @author timothypratley / https://github.com/timothypratley
  18404. * @author Mugen87 / https://github.com/Mugen87
  18405. */
  18406. // TetrahedronGeometry
  18407. function TetrahedronGeometry(radius, detail) {
  18408. Geometry.call(this);
  18409. this.type = 'TetrahedronGeometry';
  18410. this.parameters = {
  18411. radius: radius,
  18412. detail: detail
  18413. };
  18414. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  18415. this.mergeVertices();
  18416. }
  18417. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  18418. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  18419. function TetrahedronBufferGeometry(radius, detail) {
  18420. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18421. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18422. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18423. this.type = 'TetrahedronBufferGeometry';
  18424. this.parameters = {
  18425. radius: radius,
  18426. detail: detail
  18427. };
  18428. }
  18429. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18430. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  18431. /**
  18432. * @author timothypratley / https://github.com/timothypratley
  18433. * @author Mugen87 / https://github.com/Mugen87
  18434. */
  18435. // OctahedronGeometry
  18436. function OctahedronGeometry(radius, detail) {
  18437. Geometry.call(this);
  18438. this.type = 'OctahedronGeometry';
  18439. this.parameters = {
  18440. radius: radius,
  18441. detail: detail
  18442. };
  18443. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  18444. this.mergeVertices();
  18445. }
  18446. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  18447. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  18448. function OctahedronBufferGeometry(radius, detail) {
  18449. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  18450. 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];
  18451. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18452. this.type = 'OctahedronBufferGeometry';
  18453. this.parameters = {
  18454. radius: radius,
  18455. detail: detail
  18456. };
  18457. }
  18458. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18459. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  18460. /**
  18461. * @author timothypratley / https://github.com/timothypratley
  18462. * @author Mugen87 / https://github.com/Mugen87
  18463. */
  18464. // IcosahedronGeometry
  18465. function IcosahedronGeometry(radius, detail) {
  18466. Geometry.call(this);
  18467. this.type = 'IcosahedronGeometry';
  18468. this.parameters = {
  18469. radius: radius,
  18470. detail: detail
  18471. };
  18472. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  18473. this.mergeVertices();
  18474. }
  18475. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  18476. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  18477. function IcosahedronBufferGeometry(radius, detail) {
  18478. var t = (1 + Math.sqrt(5)) / 2;
  18479. 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];
  18480. 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];
  18481. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18482. this.type = 'IcosahedronBufferGeometry';
  18483. this.parameters = {
  18484. radius: radius,
  18485. detail: detail
  18486. };
  18487. }
  18488. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18489. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  18490. /**
  18491. * @author Abe Pazos / https://hamoid.com
  18492. * @author Mugen87 / https://github.com/Mugen87
  18493. */
  18494. // DodecahedronGeometry
  18495. function DodecahedronGeometry(radius, detail) {
  18496. Geometry.call(this);
  18497. this.type = 'DodecahedronGeometry';
  18498. this.parameters = {
  18499. radius: radius,
  18500. detail: detail
  18501. };
  18502. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  18503. this.mergeVertices();
  18504. }
  18505. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  18506. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  18507. function DodecahedronBufferGeometry(radius, detail) {
  18508. var t = (1 + Math.sqrt(5)) / 2;
  18509. var r = 1 / t;
  18510. var vertices = [// (±1, ±1, ±1)
  18511. -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/φ, ±φ)
  18512. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18513. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18514. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18515. 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];
  18516. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  18517. this.type = 'DodecahedronBufferGeometry';
  18518. this.parameters = {
  18519. radius: radius,
  18520. detail: detail
  18521. };
  18522. }
  18523. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  18524. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  18525. /**
  18526. * @author oosmoxiecode / https://github.com/oosmoxiecode
  18527. * @author WestLangley / https://github.com/WestLangley
  18528. * @author zz85 / https://github.com/zz85
  18529. * @author miningold / https://github.com/miningold
  18530. * @author jonobr1 / https://github.com/jonobr1
  18531. * @author Mugen87 / https://github.com/Mugen87
  18532. *
  18533. */
  18534. // TubeGeometry
  18535. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  18536. Geometry.call(this);
  18537. this.type = 'TubeGeometry';
  18538. this.parameters = {
  18539. path: path,
  18540. tubularSegments: tubularSegments,
  18541. radius: radius,
  18542. radialSegments: radialSegments,
  18543. closed: closed
  18544. };
  18545. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  18546. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  18547. this.tangents = bufferGeometry.tangents;
  18548. this.normals = bufferGeometry.normals;
  18549. this.binormals = bufferGeometry.binormals; // create geometry
  18550. this.fromBufferGeometry(bufferGeometry);
  18551. this.mergeVertices();
  18552. }
  18553. TubeGeometry.prototype = Object.create(Geometry.prototype);
  18554. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  18555. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  18556. BufferGeometry.call(this);
  18557. this.type = 'TubeBufferGeometry';
  18558. this.parameters = {
  18559. path: path,
  18560. tubularSegments: tubularSegments,
  18561. radius: radius,
  18562. radialSegments: radialSegments,
  18563. closed: closed
  18564. };
  18565. tubularSegments = tubularSegments || 64;
  18566. radius = radius || 1;
  18567. radialSegments = radialSegments || 8;
  18568. closed = closed || false;
  18569. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18570. this.tangents = frames.tangents;
  18571. this.normals = frames.normals;
  18572. this.binormals = frames.binormals; // helper variables
  18573. var vertex = new Vector3();
  18574. var normal = new Vector3();
  18575. var uv = new Vector2();
  18576. var P = new Vector3();
  18577. var i, j; // buffer
  18578. var vertices = [];
  18579. var normals = [];
  18580. var uvs = [];
  18581. var indices = []; // create buffer data
  18582. generateBufferData(); // build geometry
  18583. this.setIndex(indices);
  18584. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18585. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18586. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18587. function generateBufferData() {
  18588. for (i = 0; i < tubularSegments; i++) {
  18589. generateSegment(i);
  18590. } // if the geometry is not closed, generate the last row of vertices and normals
  18591. // at the regular position on the given path
  18592. //
  18593. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18594. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18595. // this makes it easy compute correct values for closed geometries
  18596. generateUVs(); // finally create faces
  18597. generateIndices();
  18598. }
  18599. function generateSegment(i) {
  18600. // we use getPointAt to sample evenly distributed points from the given path
  18601. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18602. var N = frames.normals[i];
  18603. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  18604. for (j = 0; j <= radialSegments; j++) {
  18605. var v = j / radialSegments * Math.PI * 2;
  18606. var sin = Math.sin(v);
  18607. var cos = -Math.cos(v); // normal
  18608. normal.x = cos * N.x + sin * B.x;
  18609. normal.y = cos * N.y + sin * B.y;
  18610. normal.z = cos * N.z + sin * B.z;
  18611. normal.normalize();
  18612. normals.push(normal.x, normal.y, normal.z); // vertex
  18613. vertex.x = P.x + radius * normal.x;
  18614. vertex.y = P.y + radius * normal.y;
  18615. vertex.z = P.z + radius * normal.z;
  18616. vertices.push(vertex.x, vertex.y, vertex.z);
  18617. }
  18618. }
  18619. function generateIndices() {
  18620. for (j = 1; j <= tubularSegments; j++) {
  18621. for (i = 1; i <= radialSegments; i++) {
  18622. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18623. var b = (radialSegments + 1) * j + (i - 1);
  18624. var c = (radialSegments + 1) * j + i;
  18625. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18626. indices.push(a, b, d);
  18627. indices.push(b, c, d);
  18628. }
  18629. }
  18630. }
  18631. function generateUVs() {
  18632. for (i = 0; i <= tubularSegments; i++) {
  18633. for (j = 0; j <= radialSegments; j++) {
  18634. uv.x = i / tubularSegments;
  18635. uv.y = j / radialSegments;
  18636. uvs.push(uv.x, uv.y);
  18637. }
  18638. }
  18639. }
  18640. }
  18641. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18642. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  18643. TubeBufferGeometry.prototype.toJSON = function () {
  18644. var data = BufferGeometry.prototype.toJSON.call(this);
  18645. data.path = this.parameters.path.toJSON();
  18646. return data;
  18647. };
  18648. /**
  18649. * @author oosmoxiecode
  18650. * @author Mugen87 / https://github.com/Mugen87
  18651. *
  18652. * based on http://www.blackpawn.com/texts/pqtorus/
  18653. */
  18654. // TorusKnotGeometry
  18655. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  18656. Geometry.call(this);
  18657. this.type = 'TorusKnotGeometry';
  18658. this.parameters = {
  18659. radius: radius,
  18660. tube: tube,
  18661. tubularSegments: tubularSegments,
  18662. radialSegments: radialSegments,
  18663. p: p,
  18664. q: q
  18665. };
  18666. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  18667. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  18668. this.mergeVertices();
  18669. }
  18670. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  18671. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  18672. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  18673. BufferGeometry.call(this);
  18674. this.type = 'TorusKnotBufferGeometry';
  18675. this.parameters = {
  18676. radius: radius,
  18677. tube: tube,
  18678. tubularSegments: tubularSegments,
  18679. radialSegments: radialSegments,
  18680. p: p,
  18681. q: q
  18682. };
  18683. radius = radius || 1;
  18684. tube = tube || 0.4;
  18685. tubularSegments = Math.floor(tubularSegments) || 64;
  18686. radialSegments = Math.floor(radialSegments) || 8;
  18687. p = p || 2;
  18688. q = q || 3; // buffers
  18689. var indices = [];
  18690. var vertices = [];
  18691. var normals = [];
  18692. var uvs = []; // helper variables
  18693. var i, j;
  18694. var vertex = new Vector3();
  18695. var normal = new Vector3();
  18696. var P1 = new Vector3();
  18697. var P2 = new Vector3();
  18698. var B = new Vector3();
  18699. var T = new Vector3();
  18700. var N = new Vector3(); // generate vertices, normals and uvs
  18701. for (i = 0; i <= tubularSegments; ++i) {
  18702. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18703. 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.
  18704. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18705. calculatePositionOnCurve(u, p, q, radius, P1);
  18706. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18707. T.subVectors(P2, P1);
  18708. N.addVectors(P2, P1);
  18709. B.crossVectors(T, N);
  18710. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18711. B.normalize();
  18712. N.normalize();
  18713. for (j = 0; j <= radialSegments; ++j) {
  18714. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18715. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18716. var v = j / radialSegments * Math.PI * 2;
  18717. var cx = -tube * Math.cos(v);
  18718. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  18719. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18720. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18721. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18722. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18723. 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)
  18724. normal.subVectors(vertex, P1).normalize();
  18725. normals.push(normal.x, normal.y, normal.z); // uv
  18726. uvs.push(i / tubularSegments);
  18727. uvs.push(j / radialSegments);
  18728. }
  18729. } // generate indices
  18730. for (j = 1; j <= tubularSegments; j++) {
  18731. for (i = 1; i <= radialSegments; i++) {
  18732. // indices
  18733. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  18734. var b = (radialSegments + 1) * j + (i - 1);
  18735. var c = (radialSegments + 1) * j + i;
  18736. var d = (radialSegments + 1) * (j - 1) + i; // faces
  18737. indices.push(a, b, d);
  18738. indices.push(b, c, d);
  18739. }
  18740. } // build geometry
  18741. this.setIndex(indices);
  18742. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18743. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18744. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18745. function calculatePositionOnCurve(u, p, q, radius, position) {
  18746. var cu = Math.cos(u);
  18747. var su = Math.sin(u);
  18748. var quOverP = q / p * u;
  18749. var cs = Math.cos(quOverP);
  18750. position.x = radius * (2 + cs) * 0.5 * cu;
  18751. position.y = radius * (2 + cs) * su * 0.5;
  18752. position.z = radius * Math.sin(quOverP) * 0.5;
  18753. }
  18754. }
  18755. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18756. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  18757. /**
  18758. * @author oosmoxiecode
  18759. * @author mrdoob / http://mrdoob.com/
  18760. * @author Mugen87 / https://github.com/Mugen87
  18761. */
  18762. // TorusGeometry
  18763. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18764. Geometry.call(this);
  18765. this.type = 'TorusGeometry';
  18766. this.parameters = {
  18767. radius: radius,
  18768. tube: tube,
  18769. radialSegments: radialSegments,
  18770. tubularSegments: tubularSegments,
  18771. arc: arc
  18772. };
  18773. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  18774. this.mergeVertices();
  18775. }
  18776. TorusGeometry.prototype = Object.create(Geometry.prototype);
  18777. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  18778. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  18779. BufferGeometry.call(this);
  18780. this.type = 'TorusBufferGeometry';
  18781. this.parameters = {
  18782. radius: radius,
  18783. tube: tube,
  18784. radialSegments: radialSegments,
  18785. tubularSegments: tubularSegments,
  18786. arc: arc
  18787. };
  18788. radius = radius || 1;
  18789. tube = tube || 0.4;
  18790. radialSegments = Math.floor(radialSegments) || 8;
  18791. tubularSegments = Math.floor(tubularSegments) || 6;
  18792. arc = arc || Math.PI * 2; // buffers
  18793. var indices = [];
  18794. var vertices = [];
  18795. var normals = [];
  18796. var uvs = []; // helper variables
  18797. var center = new Vector3();
  18798. var vertex = new Vector3();
  18799. var normal = new Vector3();
  18800. var j, i; // generate vertices, normals and uvs
  18801. for (j = 0; j <= radialSegments; j++) {
  18802. for (i = 0; i <= tubularSegments; i++) {
  18803. var u = i / tubularSegments * arc;
  18804. var v = j / radialSegments * Math.PI * 2; // vertex
  18805. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18806. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18807. vertex.z = tube * Math.sin(v);
  18808. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18809. center.x = radius * Math.cos(u);
  18810. center.y = radius * Math.sin(u);
  18811. normal.subVectors(vertex, center).normalize();
  18812. normals.push(normal.x, normal.y, normal.z); // uv
  18813. uvs.push(i / tubularSegments);
  18814. uvs.push(j / radialSegments);
  18815. }
  18816. } // generate indices
  18817. for (j = 1; j <= radialSegments; j++) {
  18818. for (i = 1; i <= tubularSegments; i++) {
  18819. // indices
  18820. var a = (tubularSegments + 1) * j + i - 1;
  18821. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  18822. var c = (tubularSegments + 1) * (j - 1) + i;
  18823. var d = (tubularSegments + 1) * j + i; // faces
  18824. indices.push(a, b, d);
  18825. indices.push(b, c, d);
  18826. }
  18827. } // build geometry
  18828. this.setIndex(indices);
  18829. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  18830. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  18831. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18832. }
  18833. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18834. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  18835. /**
  18836. * @author Mugen87 / https://github.com/Mugen87
  18837. * Port from https://github.com/mapbox/earcut (v2.1.5)
  18838. */
  18839. var Earcut = {
  18840. triangulate: function (data, holeIndices, dim) {
  18841. dim = dim || 2;
  18842. var hasHoles = holeIndices && holeIndices.length,
  18843. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  18844. outerNode = linkedList(data, 0, outerLen, dim, true),
  18845. triangles = [];
  18846. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18847. var minX, minY, maxX, maxY, x, y, invSize;
  18848. 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
  18849. if (data.length > 80 * dim) {
  18850. minX = maxX = data[0];
  18851. minY = maxY = data[1];
  18852. for (var i = dim; i < outerLen; i += dim) {
  18853. x = data[i];
  18854. y = data[i + 1];
  18855. if (x < minX) minX = x;
  18856. if (y < minY) minY = y;
  18857. if (x > maxX) maxX = x;
  18858. if (y > maxY) maxY = y;
  18859. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18860. invSize = Math.max(maxX - minX, maxY - minY);
  18861. invSize = invSize !== 0 ? 1 / invSize : 0;
  18862. }
  18863. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18864. return triangles;
  18865. }
  18866. }; // create a circular doubly linked list from polygon points in the specified winding order
  18867. function linkedList(data, start, end, dim, clockwise) {
  18868. var i, last;
  18869. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18870. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18871. } else {
  18872. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18873. }
  18874. if (last && equals(last, last.next)) {
  18875. removeNode(last);
  18876. last = last.next;
  18877. }
  18878. return last;
  18879. } // eliminate colinear or duplicate points
  18880. function filterPoints(start, end) {
  18881. if (!start) return start;
  18882. if (!end) end = start;
  18883. var p = start,
  18884. again;
  18885. do {
  18886. again = false;
  18887. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18888. removeNode(p);
  18889. p = end = p.prev;
  18890. if (p === p.next) break;
  18891. again = true;
  18892. } else {
  18893. p = p.next;
  18894. }
  18895. } while (again || p !== end);
  18896. return end;
  18897. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18898. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18899. if (!ear) return; // interlink polygon nodes in z-order
  18900. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18901. var stop = ear,
  18902. prev,
  18903. next; // iterate through ears, slicing them one by one
  18904. while (ear.prev !== ear.next) {
  18905. prev = ear.prev;
  18906. next = ear.next;
  18907. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18908. // cut off the triangle
  18909. triangles.push(prev.i / dim);
  18910. triangles.push(ear.i / dim);
  18911. triangles.push(next.i / dim);
  18912. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18913. ear = next.next;
  18914. stop = next.next;
  18915. continue;
  18916. }
  18917. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18918. if (ear === stop) {
  18919. // try filtering points and slicing again
  18920. if (!pass) {
  18921. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18922. } else if (pass === 1) {
  18923. ear = cureLocalIntersections(ear, triangles, dim);
  18924. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18925. } else if (pass === 2) {
  18926. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18927. }
  18928. break;
  18929. }
  18930. }
  18931. } // check whether a polygon node forms a valid ear with adjacent nodes
  18932. function isEar(ear) {
  18933. var a = ear.prev,
  18934. b = ear,
  18935. c = ear.next;
  18936. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18937. // now make sure we don't have other points inside the potential ear
  18938. var p = ear.next.next;
  18939. while (p !== ear.prev) {
  18940. 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;
  18941. p = p.next;
  18942. }
  18943. return true;
  18944. }
  18945. function isEarHashed(ear, minX, minY, invSize) {
  18946. var a = ear.prev,
  18947. b = ear,
  18948. c = ear.next;
  18949. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18950. // triangle bbox; min & max are calculated like this for speed
  18951. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18952. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18953. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18954. 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;
  18955. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18956. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18957. var p = ear.prevZ,
  18958. n = ear.nextZ; // look for points inside the triangle in both directions
  18959. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18960. 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;
  18961. p = p.prevZ;
  18962. 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;
  18963. n = n.nextZ;
  18964. } // look for remaining points in decreasing z-order
  18965. while (p && p.z >= minZ) {
  18966. 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;
  18967. p = p.prevZ;
  18968. } // look for remaining points in increasing z-order
  18969. while (n && n.z <= maxZ) {
  18970. 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;
  18971. n = n.nextZ;
  18972. }
  18973. return true;
  18974. } // go through all polygon nodes and cure small local self-intersections
  18975. function cureLocalIntersections(start, triangles, dim) {
  18976. var p = start;
  18977. do {
  18978. var a = p.prev,
  18979. b = p.next.next;
  18980. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18981. triangles.push(a.i / dim);
  18982. triangles.push(p.i / dim);
  18983. triangles.push(b.i / dim); // remove two nodes involved
  18984. removeNode(p);
  18985. removeNode(p.next);
  18986. p = start = b;
  18987. }
  18988. p = p.next;
  18989. } while (p !== start);
  18990. return p;
  18991. } // try splitting polygon into two and triangulate them independently
  18992. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18993. // look for a valid diagonal that divides the polygon into two
  18994. var a = start;
  18995. do {
  18996. var b = a.next.next;
  18997. while (b !== a.prev) {
  18998. if (a.i !== b.i && isValidDiagonal(a, b)) {
  18999. // split the polygon in two by the diagonal
  19000. var c = splitPolygon(a, b); // filter colinear points around the cuts
  19001. a = filterPoints(a, a.next);
  19002. c = filterPoints(c, c.next); // run earcut on each half
  19003. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19004. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19005. return;
  19006. }
  19007. b = b.next;
  19008. }
  19009. a = a.next;
  19010. } while (a !== start);
  19011. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19012. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19013. var queue = [],
  19014. i,
  19015. len,
  19016. start,
  19017. end,
  19018. list;
  19019. for (i = 0, len = holeIndices.length; i < len; i++) {
  19020. start = holeIndices[i] * dim;
  19021. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19022. list = linkedList(data, start, end, dim, false);
  19023. if (list === list.next) list.steiner = true;
  19024. queue.push(getLeftmost(list));
  19025. }
  19026. queue.sort(compareX); // process holes from left to right
  19027. for (i = 0; i < queue.length; i++) {
  19028. eliminateHole(queue[i], outerNode);
  19029. outerNode = filterPoints(outerNode, outerNode.next);
  19030. }
  19031. return outerNode;
  19032. }
  19033. function compareX(a, b) {
  19034. return a.x - b.x;
  19035. } // find a bridge between vertices that connects hole with an outer ring and and link it
  19036. function eliminateHole(hole, outerNode) {
  19037. outerNode = findHoleBridge(hole, outerNode);
  19038. if (outerNode) {
  19039. var b = splitPolygon(outerNode, hole);
  19040. filterPoints(b, b.next);
  19041. }
  19042. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19043. function findHoleBridge(hole, outerNode) {
  19044. var p = outerNode,
  19045. hx = hole.x,
  19046. hy = hole.y,
  19047. qx = -Infinity,
  19048. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19049. // segment's endpoint with lesser x will be potential connection point
  19050. do {
  19051. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19052. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19053. if (x <= hx && x > qx) {
  19054. qx = x;
  19055. if (x === hx) {
  19056. if (hy === p.y) return p;
  19057. if (hy === p.next.y) return p.next;
  19058. }
  19059. m = p.x < p.next.x ? p : p.next;
  19060. }
  19061. }
  19062. p = p.next;
  19063. } while (p !== outerNode);
  19064. if (!m) return null;
  19065. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  19066. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19067. // if there are no points found, we have a valid connection;
  19068. // otherwise choose the point of the minimum angle with the ray as connection point
  19069. var stop = m,
  19070. mx = m.x,
  19071. my = m.y,
  19072. tanMin = Infinity,
  19073. tan;
  19074. p = m.next;
  19075. while (p !== stop) {
  19076. 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)) {
  19077. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19078. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  19079. m = p;
  19080. tanMin = tan;
  19081. }
  19082. }
  19083. p = p.next;
  19084. }
  19085. return m;
  19086. } // interlink polygon nodes in z-order
  19087. function indexCurve(start, minX, minY, invSize) {
  19088. var p = start;
  19089. do {
  19090. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19091. p.prevZ = p.prev;
  19092. p.nextZ = p.next;
  19093. p = p.next;
  19094. } while (p !== start);
  19095. p.prevZ.nextZ = null;
  19096. p.prevZ = null;
  19097. sortLinked(p);
  19098. } // Simon Tatham's linked list merge sort algorithm
  19099. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19100. function sortLinked(list) {
  19101. var i,
  19102. p,
  19103. q,
  19104. e,
  19105. tail,
  19106. numMerges,
  19107. pSize,
  19108. qSize,
  19109. inSize = 1;
  19110. do {
  19111. p = list;
  19112. list = null;
  19113. tail = null;
  19114. numMerges = 0;
  19115. while (p) {
  19116. numMerges++;
  19117. q = p;
  19118. pSize = 0;
  19119. for (i = 0; i < inSize; i++) {
  19120. pSize++;
  19121. q = q.nextZ;
  19122. if (!q) break;
  19123. }
  19124. qSize = inSize;
  19125. while (pSize > 0 || qSize > 0 && q) {
  19126. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19127. e = p;
  19128. p = p.nextZ;
  19129. pSize--;
  19130. } else {
  19131. e = q;
  19132. q = q.nextZ;
  19133. qSize--;
  19134. }
  19135. if (tail) tail.nextZ = e;else list = e;
  19136. e.prevZ = tail;
  19137. tail = e;
  19138. }
  19139. p = q;
  19140. }
  19141. tail.nextZ = null;
  19142. inSize *= 2;
  19143. } while (numMerges > 1);
  19144. return list;
  19145. } // z-order of a point given coords and inverse of the longer side of data bbox
  19146. function zOrder(x, y, minX, minY, invSize) {
  19147. // coords are transformed into non-negative 15-bit integer range
  19148. x = 32767 * (x - minX) * invSize;
  19149. y = 32767 * (y - minY) * invSize;
  19150. x = (x | x << 8) & 0x00FF00FF;
  19151. x = (x | x << 4) & 0x0F0F0F0F;
  19152. x = (x | x << 2) & 0x33333333;
  19153. x = (x | x << 1) & 0x55555555;
  19154. y = (y | y << 8) & 0x00FF00FF;
  19155. y = (y | y << 4) & 0x0F0F0F0F;
  19156. y = (y | y << 2) & 0x33333333;
  19157. y = (y | y << 1) & 0x55555555;
  19158. return x | y << 1;
  19159. } // find the leftmost node of a polygon ring
  19160. function getLeftmost(start) {
  19161. var p = start,
  19162. leftmost = start;
  19163. do {
  19164. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19165. p = p.next;
  19166. } while (p !== start);
  19167. return leftmost;
  19168. } // check if a point lies within a convex triangle
  19169. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19170. 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;
  19171. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19172. function isValidDiagonal(a, b) {
  19173. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  19174. } // signed area of a triangle
  19175. function area(p, q, r) {
  19176. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19177. } // check if two points are equal
  19178. function equals(p1, p2) {
  19179. return p1.x === p2.x && p1.y === p2.y;
  19180. } // check if two segments intersect
  19181. function intersects(p1, q1, p2, q2) {
  19182. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  19183. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  19184. } // check if a polygon diagonal intersects any polygon segments
  19185. function intersectsPolygon(a, b) {
  19186. var p = a;
  19187. do {
  19188. 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;
  19189. p = p.next;
  19190. } while (p !== a);
  19191. return false;
  19192. } // check if a polygon diagonal is locally inside the polygon
  19193. function locallyInside(a, b) {
  19194. 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;
  19195. } // check if the middle point of a polygon diagonal is inside the polygon
  19196. function middleInside(a, b) {
  19197. var p = a,
  19198. inside = false,
  19199. px = (a.x + b.x) / 2,
  19200. py = (a.y + b.y) / 2;
  19201. do {
  19202. 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;
  19203. p = p.next;
  19204. } while (p !== a);
  19205. return inside;
  19206. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19207. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19208. function splitPolygon(a, b) {
  19209. var a2 = new Node(a.i, a.x, a.y),
  19210. b2 = new Node(b.i, b.x, b.y),
  19211. an = a.next,
  19212. bp = b.prev;
  19213. a.next = b;
  19214. b.prev = a;
  19215. a2.next = an;
  19216. an.prev = a2;
  19217. b2.next = a2;
  19218. a2.prev = b2;
  19219. bp.next = b2;
  19220. b2.prev = bp;
  19221. return b2;
  19222. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19223. function insertNode(i, x, y, last) {
  19224. var p = new Node(i, x, y);
  19225. if (!last) {
  19226. p.prev = p;
  19227. p.next = p;
  19228. } else {
  19229. p.next = last.next;
  19230. p.prev = last;
  19231. last.next.prev = p;
  19232. last.next = p;
  19233. }
  19234. return p;
  19235. }
  19236. function removeNode(p) {
  19237. p.next.prev = p.prev;
  19238. p.prev.next = p.next;
  19239. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19240. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19241. }
  19242. function Node(i, x, y) {
  19243. // vertex index in coordinates array
  19244. this.i = i; // vertex coordinates
  19245. this.x = x;
  19246. this.y = y; // previous and next vertex nodes in a polygon ring
  19247. this.prev = null;
  19248. this.next = null; // z-order curve value
  19249. this.z = null; // previous and next nodes in z-order
  19250. this.prevZ = null;
  19251. this.nextZ = null; // indicates whether this is a steiner point
  19252. this.steiner = false;
  19253. }
  19254. function signedArea(data, start, end, dim) {
  19255. var sum = 0;
  19256. for (var i = start, j = end - dim; i < end; i += dim) {
  19257. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19258. j = i;
  19259. }
  19260. return sum;
  19261. }
  19262. /**
  19263. * @author zz85 / http://www.lab4games.net/zz85/blog
  19264. */
  19265. var ShapeUtils = {
  19266. // calculate area of the contour polygon
  19267. area: function (contour) {
  19268. var n = contour.length;
  19269. var a = 0.0;
  19270. for (var p = n - 1, q = 0; q < n; p = q++) {
  19271. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19272. }
  19273. return a * 0.5;
  19274. },
  19275. isClockWise: function (pts) {
  19276. return ShapeUtils.area(pts) < 0;
  19277. },
  19278. triangulateShape: function (contour, holes) {
  19279. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19280. var holeIndices = []; // array of hole indices
  19281. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19282. removeDupEndPts(contour);
  19283. addContour(vertices, contour); //
  19284. var holeIndex = contour.length;
  19285. holes.forEach(removeDupEndPts);
  19286. for (var i = 0; i < holes.length; i++) {
  19287. holeIndices.push(holeIndex);
  19288. holeIndex += holes[i].length;
  19289. addContour(vertices, holes[i]);
  19290. } //
  19291. var triangles = Earcut.triangulate(vertices, holeIndices); //
  19292. for (var i = 0; i < triangles.length; i += 3) {
  19293. faces.push(triangles.slice(i, i + 3));
  19294. }
  19295. return faces;
  19296. }
  19297. };
  19298. exports.ShapeUtils = ShapeUtils;
  19299. function removeDupEndPts(points) {
  19300. var l = points.length;
  19301. if (l > 2 && points[l - 1].equals(points[0])) {
  19302. points.pop();
  19303. }
  19304. }
  19305. function addContour(vertices, contour) {
  19306. for (var i = 0; i < contour.length; i++) {
  19307. vertices.push(contour[i].x);
  19308. vertices.push(contour[i].y);
  19309. }
  19310. }
  19311. /**
  19312. * @author zz85 / http://www.lab4games.net/zz85/blog
  19313. *
  19314. * Creates extruded geometry from a path shape.
  19315. *
  19316. * parameters = {
  19317. *
  19318. * curveSegments: <int>, // number of points on the curves
  19319. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19320. * depth: <float>, // Depth to extrude the shape
  19321. *
  19322. * bevelEnabled: <bool>, // turn on bevel
  19323. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19324. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19325. * bevelOffset: <float>, // how far from shape outline does bevel start
  19326. * bevelSegments: <int>, // number of bevel layers
  19327. *
  19328. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19329. *
  19330. * UVGenerator: <Object> // object that provides UV generator functions
  19331. *
  19332. * }
  19333. */
  19334. // ExtrudeGeometry
  19335. function ExtrudeGeometry(shapes, options) {
  19336. Geometry.call(this);
  19337. this.type = 'ExtrudeGeometry';
  19338. this.parameters = {
  19339. shapes: shapes,
  19340. options: options
  19341. };
  19342. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  19343. this.mergeVertices();
  19344. }
  19345. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  19346. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  19347. ExtrudeGeometry.prototype.toJSON = function () {
  19348. var data = Geometry.prototype.toJSON.call(this);
  19349. var shapes = this.parameters.shapes;
  19350. var options = this.parameters.options;
  19351. return toJSON(shapes, options, data);
  19352. }; // ExtrudeBufferGeometry
  19353. function ExtrudeBufferGeometry(shapes, options) {
  19354. BufferGeometry.call(this);
  19355. this.type = 'ExtrudeBufferGeometry';
  19356. this.parameters = {
  19357. shapes: shapes,
  19358. options: options
  19359. };
  19360. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19361. var scope = this;
  19362. var verticesArray = [];
  19363. var uvArray = [];
  19364. for (var i = 0, l = shapes.length; i < l; i++) {
  19365. var shape = shapes[i];
  19366. addShape(shape);
  19367. } // build geometry
  19368. this.addAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19369. this.addAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19370. this.computeVertexNormals(); // functions
  19371. function addShape(shape) {
  19372. var placeholder = []; // options
  19373. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19374. var steps = options.steps !== undefined ? options.steps : 1;
  19375. var depth = options.depth !== undefined ? options.depth : 100;
  19376. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19377. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19378. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19379. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19380. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19381. var extrudePath = options.extrudePath;
  19382. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  19383. if (options.amount !== undefined) {
  19384. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  19385. depth = options.amount;
  19386. } //
  19387. var extrudePts,
  19388. extrudeByPath = false;
  19389. var splineTube, binormal, normal, position2;
  19390. if (extrudePath) {
  19391. extrudePts = extrudePath.getSpacedPoints(steps);
  19392. extrudeByPath = true;
  19393. bevelEnabled = false; // bevels not supported for path extrusion
  19394. // SETUP TNB variables
  19395. // TODO1 - have a .isClosed in spline?
  19396. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19397. binormal = new Vector3();
  19398. normal = new Vector3();
  19399. position2 = new Vector3();
  19400. } // Safeguards if bevels are not enabled
  19401. if (!bevelEnabled) {
  19402. bevelSegments = 0;
  19403. bevelThickness = 0;
  19404. bevelSize = 0;
  19405. bevelOffset = 0;
  19406. } // Variables initialization
  19407. var ahole, h, hl; // looping of holes
  19408. var shapePoints = shape.extractPoints(curveSegments);
  19409. var vertices = shapePoints.shape;
  19410. var holes = shapePoints.holes;
  19411. var reverse = !ShapeUtils.isClockWise(vertices);
  19412. if (reverse) {
  19413. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19414. for (h = 0, hl = holes.length; h < hl; h++) {
  19415. ahole = holes[h];
  19416. if (ShapeUtils.isClockWise(ahole)) {
  19417. holes[h] = ahole.reverse();
  19418. }
  19419. }
  19420. }
  19421. var faces = ShapeUtils.triangulateShape(vertices, holes);
  19422. /* Vertices */
  19423. var contour = vertices; // vertices has all points but contour has only points of circumference
  19424. for (h = 0, hl = holes.length; h < hl; h++) {
  19425. ahole = holes[h];
  19426. vertices = vertices.concat(ahole);
  19427. }
  19428. function scalePt2(pt, vec, size) {
  19429. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  19430. return vec.clone().multiplyScalar(size).add(pt);
  19431. }
  19432. var b,
  19433. bs,
  19434. t,
  19435. z,
  19436. vert,
  19437. vlen = vertices.length,
  19438. face,
  19439. flen = faces.length; // Find directions for point movement
  19440. function getBevelVec(inPt, inPrev, inNext) {
  19441. // computes for inPt the corresponding point inPt' on a new contour
  19442. // shifted by 1 unit (length of normalized vector) to the left
  19443. // if we walk along contour clockwise, this new contour is outside the old one
  19444. //
  19445. // inPt' is the intersection of the two lines parallel to the two
  19446. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19447. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19448. // good reading for geometry algorithms (here: line-line intersection)
  19449. // http://geomalgorithms.com/a05-_intersect-1.html
  19450. var v_prev_x = inPt.x - inPrev.x,
  19451. v_prev_y = inPt.y - inPrev.y;
  19452. var v_next_x = inNext.x - inPt.x,
  19453. v_next_y = inNext.y - inPt.y;
  19454. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  19455. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  19456. if (Math.abs(collinear0) > Number.EPSILON) {
  19457. // not collinear
  19458. // length of vectors for normalizing
  19459. var v_prev_len = Math.sqrt(v_prev_lensq);
  19460. 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
  19461. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  19462. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  19463. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  19464. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  19465. 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
  19466. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  19467. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  19468. // but prevent crazy spikes
  19469. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  19470. if (v_trans_lensq <= 2) {
  19471. return new Vector2(v_trans_x, v_trans_y);
  19472. } else {
  19473. shrink_by = Math.sqrt(v_trans_lensq / 2);
  19474. }
  19475. } else {
  19476. // handle special case of collinear edges
  19477. var direction_eq = false; // assumes: opposite
  19478. if (v_prev_x > Number.EPSILON) {
  19479. if (v_next_x > Number.EPSILON) {
  19480. direction_eq = true;
  19481. }
  19482. } else {
  19483. if (v_prev_x < -Number.EPSILON) {
  19484. if (v_next_x < -Number.EPSILON) {
  19485. direction_eq = true;
  19486. }
  19487. } else {
  19488. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  19489. direction_eq = true;
  19490. }
  19491. }
  19492. }
  19493. if (direction_eq) {
  19494. // console.log("Warning: lines are a straight sequence");
  19495. v_trans_x = -v_prev_y;
  19496. v_trans_y = v_prev_x;
  19497. shrink_by = Math.sqrt(v_prev_lensq);
  19498. } else {
  19499. // console.log("Warning: lines are a straight spike");
  19500. v_trans_x = v_prev_x;
  19501. v_trans_y = v_prev_y;
  19502. shrink_by = Math.sqrt(v_prev_lensq / 2);
  19503. }
  19504. }
  19505. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  19506. }
  19507. var contourMovements = [];
  19508. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19509. if (j === il) j = 0;
  19510. if (k === il) k = 0; // (j)---(i)---(k)
  19511. // console.log('i,j,k', i, j , k)
  19512. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  19513. }
  19514. var holesMovements = [],
  19515. oneHoleMovements,
  19516. verticesMovements = contourMovements.concat();
  19517. for (h = 0, hl = holes.length; h < hl; h++) {
  19518. ahole = holes[h];
  19519. oneHoleMovements = [];
  19520. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19521. if (j === il) j = 0;
  19522. if (k === il) k = 0; // (j)---(i)---(k)
  19523. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  19524. }
  19525. holesMovements.push(oneHoleMovements);
  19526. verticesMovements = verticesMovements.concat(oneHoleMovements);
  19527. } // Loop bevelSegments, 1 for the front, 1 for the back
  19528. for (b = 0; b < bevelSegments; b++) {
  19529. //for ( b = bevelSegments; b > 0; b -- ) {
  19530. t = b / bevelSegments;
  19531. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19532. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19533. for (i = 0, il = contour.length; i < il; i++) {
  19534. vert = scalePt2(contour[i], contourMovements[i], bs);
  19535. v(vert.x, vert.y, -z);
  19536. } // expand holes
  19537. for (h = 0, hl = holes.length; h < hl; h++) {
  19538. ahole = holes[h];
  19539. oneHoleMovements = holesMovements[h];
  19540. for (i = 0, il = ahole.length; i < il; i++) {
  19541. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19542. v(vert.x, vert.y, -z);
  19543. }
  19544. }
  19545. }
  19546. bs = bevelSize + bevelOffset; // Back facing vertices
  19547. for (i = 0; i < vlen; i++) {
  19548. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19549. if (!extrudeByPath) {
  19550. v(vert.x, vert.y, 0);
  19551. } else {
  19552. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19553. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  19554. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  19555. position2.copy(extrudePts[0]).add(normal).add(binormal);
  19556. v(position2.x, position2.y, position2.z);
  19557. }
  19558. } // Add stepped vertices...
  19559. // Including front facing vertices
  19560. var s;
  19561. for (s = 1; s <= steps; s++) {
  19562. for (i = 0; i < vlen; i++) {
  19563. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19564. if (!extrudeByPath) {
  19565. v(vert.x, vert.y, depth / steps * s);
  19566. } else {
  19567. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19568. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  19569. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  19570. position2.copy(extrudePts[s]).add(normal).add(binormal);
  19571. v(position2.x, position2.y, position2.z);
  19572. }
  19573. }
  19574. } // Add bevel segments planes
  19575. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19576. for (b = bevelSegments - 1; b >= 0; b--) {
  19577. t = b / bevelSegments;
  19578. z = bevelThickness * Math.cos(t * Math.PI / 2);
  19579. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19580. for (i = 0, il = contour.length; i < il; i++) {
  19581. vert = scalePt2(contour[i], contourMovements[i], bs);
  19582. v(vert.x, vert.y, depth + z);
  19583. } // expand holes
  19584. for (h = 0, hl = holes.length; h < hl; h++) {
  19585. ahole = holes[h];
  19586. oneHoleMovements = holesMovements[h];
  19587. for (i = 0, il = ahole.length; i < il; i++) {
  19588. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19589. if (!extrudeByPath) {
  19590. v(vert.x, vert.y, depth + z);
  19591. } else {
  19592. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  19593. }
  19594. }
  19595. }
  19596. }
  19597. /* Faces */
  19598. // Top and bottom faces
  19599. buildLidFaces(); // Sides faces
  19600. buildSideFaces(); ///// Internal functions
  19601. function buildLidFaces() {
  19602. var start = verticesArray.length / 3;
  19603. if (bevelEnabled) {
  19604. var layer = 0; // steps + 1
  19605. var offset = vlen * layer; // Bottom faces
  19606. for (i = 0; i < flen; i++) {
  19607. face = faces[i];
  19608. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  19609. }
  19610. layer = steps + bevelSegments * 2;
  19611. offset = vlen * layer; // Top faces
  19612. for (i = 0; i < flen; i++) {
  19613. face = faces[i];
  19614. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  19615. }
  19616. } else {
  19617. // Bottom faces
  19618. for (i = 0; i < flen; i++) {
  19619. face = faces[i];
  19620. f3(face[2], face[1], face[0]);
  19621. } // Top faces
  19622. for (i = 0; i < flen; i++) {
  19623. face = faces[i];
  19624. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  19625. }
  19626. }
  19627. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  19628. } // Create faces for the z-sides of the shape
  19629. function buildSideFaces() {
  19630. var start = verticesArray.length / 3;
  19631. var layeroffset = 0;
  19632. sidewalls(contour, layeroffset);
  19633. layeroffset += contour.length;
  19634. for (h = 0, hl = holes.length; h < hl; h++) {
  19635. ahole = holes[h];
  19636. sidewalls(ahole, layeroffset); //, true
  19637. layeroffset += ahole.length;
  19638. }
  19639. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  19640. }
  19641. function sidewalls(contour, layeroffset) {
  19642. var j, k;
  19643. i = contour.length;
  19644. while (--i >= 0) {
  19645. j = i;
  19646. k = i - 1;
  19647. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  19648. var s = 0,
  19649. sl = steps + bevelSegments * 2;
  19650. for (s = 0; s < sl; s++) {
  19651. var slen1 = vlen * s;
  19652. var slen2 = vlen * (s + 1);
  19653. var a = layeroffset + j + slen1,
  19654. b = layeroffset + k + slen1,
  19655. c = layeroffset + k + slen2,
  19656. d = layeroffset + j + slen2;
  19657. f4(a, b, c, d);
  19658. }
  19659. }
  19660. }
  19661. function v(x, y, z) {
  19662. placeholder.push(x);
  19663. placeholder.push(y);
  19664. placeholder.push(z);
  19665. }
  19666. function f3(a, b, c) {
  19667. addVertex(a);
  19668. addVertex(b);
  19669. addVertex(c);
  19670. var nextIndex = verticesArray.length / 3;
  19671. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19672. addUV(uvs[0]);
  19673. addUV(uvs[1]);
  19674. addUV(uvs[2]);
  19675. }
  19676. function f4(a, b, c, d) {
  19677. addVertex(a);
  19678. addVertex(b);
  19679. addVertex(d);
  19680. addVertex(b);
  19681. addVertex(c);
  19682. addVertex(d);
  19683. var nextIndex = verticesArray.length / 3;
  19684. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19685. addUV(uvs[0]);
  19686. addUV(uvs[1]);
  19687. addUV(uvs[3]);
  19688. addUV(uvs[1]);
  19689. addUV(uvs[2]);
  19690. addUV(uvs[3]);
  19691. }
  19692. function addVertex(index) {
  19693. verticesArray.push(placeholder[index * 3 + 0]);
  19694. verticesArray.push(placeholder[index * 3 + 1]);
  19695. verticesArray.push(placeholder[index * 3 + 2]);
  19696. }
  19697. function addUV(vector2) {
  19698. uvArray.push(vector2.x);
  19699. uvArray.push(vector2.y);
  19700. }
  19701. }
  19702. }
  19703. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19704. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  19705. ExtrudeBufferGeometry.prototype.toJSON = function () {
  19706. var data = BufferGeometry.prototype.toJSON.call(this);
  19707. var shapes = this.parameters.shapes;
  19708. var options = this.parameters.options;
  19709. return toJSON(shapes, options, data);
  19710. }; //
  19711. var WorldUVGenerator = {
  19712. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  19713. var a_x = vertices[indexA * 3];
  19714. var a_y = vertices[indexA * 3 + 1];
  19715. var b_x = vertices[indexB * 3];
  19716. var b_y = vertices[indexB * 3 + 1];
  19717. var c_x = vertices[indexC * 3];
  19718. var c_y = vertices[indexC * 3 + 1];
  19719. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  19720. },
  19721. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  19722. var a_x = vertices[indexA * 3];
  19723. var a_y = vertices[indexA * 3 + 1];
  19724. var a_z = vertices[indexA * 3 + 2];
  19725. var b_x = vertices[indexB * 3];
  19726. var b_y = vertices[indexB * 3 + 1];
  19727. var b_z = vertices[indexB * 3 + 2];
  19728. var c_x = vertices[indexC * 3];
  19729. var c_y = vertices[indexC * 3 + 1];
  19730. var c_z = vertices[indexC * 3 + 2];
  19731. var d_x = vertices[indexD * 3];
  19732. var d_y = vertices[indexD * 3 + 1];
  19733. var d_z = vertices[indexD * 3 + 2];
  19734. if (Math.abs(a_y - b_y) < 0.01) {
  19735. 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)];
  19736. } else {
  19737. 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)];
  19738. }
  19739. }
  19740. };
  19741. function toJSON(shapes, options, data) {
  19742. //
  19743. data.shapes = [];
  19744. if (Array.isArray(shapes)) {
  19745. for (var i = 0, l = shapes.length; i < l; i++) {
  19746. var shape = shapes[i];
  19747. data.shapes.push(shape.uuid);
  19748. }
  19749. } else {
  19750. data.shapes.push(shapes.uuid);
  19751. } //
  19752. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19753. return data;
  19754. }
  19755. /**
  19756. * @author zz85 / http://www.lab4games.net/zz85/blog
  19757. * @author alteredq / http://alteredqualia.com/
  19758. *
  19759. * Text = 3D Text
  19760. *
  19761. * parameters = {
  19762. * font: <THREE.Font>, // font
  19763. *
  19764. * size: <float>, // size of the text
  19765. * height: <float>, // thickness to extrude text
  19766. * curveSegments: <int>, // number of points on the curves
  19767. *
  19768. * bevelEnabled: <bool>, // turn on bevel
  19769. * bevelThickness: <float>, // how deep into text bevel goes
  19770. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19771. * bevelOffset: <float> // how far from text outline does bevel start
  19772. * }
  19773. */
  19774. // TextGeometry
  19775. function TextGeometry(text, parameters) {
  19776. Geometry.call(this);
  19777. this.type = 'TextGeometry';
  19778. this.parameters = {
  19779. text: text,
  19780. parameters: parameters
  19781. };
  19782. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  19783. this.mergeVertices();
  19784. }
  19785. TextGeometry.prototype = Object.create(Geometry.prototype);
  19786. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  19787. function TextBufferGeometry(text, parameters) {
  19788. parameters = parameters || {};
  19789. var font = parameters.font;
  19790. if (!(font && font.isFont)) {
  19791. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19792. return new Geometry();
  19793. }
  19794. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19795. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19796. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19797. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19798. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19799. ExtrudeBufferGeometry.call(this, shapes, parameters);
  19800. this.type = 'TextBufferGeometry';
  19801. }
  19802. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  19803. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  19804. /**
  19805. * @author mrdoob / http://mrdoob.com/
  19806. * @author benaadams / https://twitter.com/ben_a_adams
  19807. * @author Mugen87 / https://github.com/Mugen87
  19808. */
  19809. // SphereGeometry
  19810. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19811. Geometry.call(this);
  19812. this.type = 'SphereGeometry';
  19813. this.parameters = {
  19814. radius: radius,
  19815. widthSegments: widthSegments,
  19816. heightSegments: heightSegments,
  19817. phiStart: phiStart,
  19818. phiLength: phiLength,
  19819. thetaStart: thetaStart,
  19820. thetaLength: thetaLength
  19821. };
  19822. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  19823. this.mergeVertices();
  19824. }
  19825. SphereGeometry.prototype = Object.create(Geometry.prototype);
  19826. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  19827. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19828. BufferGeometry.call(this);
  19829. this.type = 'SphereBufferGeometry';
  19830. this.parameters = {
  19831. radius: radius,
  19832. widthSegments: widthSegments,
  19833. heightSegments: heightSegments,
  19834. phiStart: phiStart,
  19835. phiLength: phiLength,
  19836. thetaStart: thetaStart,
  19837. thetaLength: thetaLength
  19838. };
  19839. radius = radius || 1;
  19840. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  19841. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  19842. phiStart = phiStart !== undefined ? phiStart : 0;
  19843. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19844. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19845. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19846. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19847. var ix, iy;
  19848. var index = 0;
  19849. var grid = [];
  19850. var vertex = new Vector3();
  19851. var normal = new Vector3(); // buffers
  19852. var indices = [];
  19853. var vertices = [];
  19854. var normals = [];
  19855. var uvs = []; // generate vertices, normals and uvs
  19856. for (iy = 0; iy <= heightSegments; iy++) {
  19857. var verticesRow = [];
  19858. var v = iy / heightSegments; // special case for the poles
  19859. var uOffset = 0;
  19860. if (iy == 0 && thetaStart == 0) {
  19861. uOffset = 0.5 / widthSegments;
  19862. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19863. uOffset = -0.5 / widthSegments;
  19864. }
  19865. for (ix = 0; ix <= widthSegments; ix++) {
  19866. var u = ix / widthSegments; // vertex
  19867. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19868. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19869. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19870. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19871. normal.copy(vertex).normalize();
  19872. normals.push(normal.x, normal.y, normal.z); // uv
  19873. uvs.push(u + uOffset, 1 - v);
  19874. verticesRow.push(index++);
  19875. }
  19876. grid.push(verticesRow);
  19877. } // indices
  19878. for (iy = 0; iy < heightSegments; iy++) {
  19879. for (ix = 0; ix < widthSegments; ix++) {
  19880. var a = grid[iy][ix + 1];
  19881. var b = grid[iy][ix];
  19882. var c = grid[iy + 1][ix];
  19883. var d = grid[iy + 1][ix + 1];
  19884. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19885. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19886. }
  19887. } // build geometry
  19888. this.setIndex(indices);
  19889. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19890. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19891. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19892. }
  19893. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19894. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  19895. /**
  19896. * @author Kaleb Murphy
  19897. * @author Mugen87 / https://github.com/Mugen87
  19898. */
  19899. // RingGeometry
  19900. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19901. Geometry.call(this);
  19902. this.type = 'RingGeometry';
  19903. this.parameters = {
  19904. innerRadius: innerRadius,
  19905. outerRadius: outerRadius,
  19906. thetaSegments: thetaSegments,
  19907. phiSegments: phiSegments,
  19908. thetaStart: thetaStart,
  19909. thetaLength: thetaLength
  19910. };
  19911. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19912. this.mergeVertices();
  19913. }
  19914. RingGeometry.prototype = Object.create(Geometry.prototype);
  19915. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  19916. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19917. BufferGeometry.call(this);
  19918. this.type = 'RingBufferGeometry';
  19919. this.parameters = {
  19920. innerRadius: innerRadius,
  19921. outerRadius: outerRadius,
  19922. thetaSegments: thetaSegments,
  19923. phiSegments: phiSegments,
  19924. thetaStart: thetaStart,
  19925. thetaLength: thetaLength
  19926. };
  19927. innerRadius = innerRadius || 0.5;
  19928. outerRadius = outerRadius || 1;
  19929. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19930. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19931. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  19932. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  19933. var indices = [];
  19934. var vertices = [];
  19935. var normals = [];
  19936. var uvs = []; // some helper variables
  19937. var segment;
  19938. var radius = innerRadius;
  19939. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  19940. var vertex = new Vector3();
  19941. var uv = new Vector2();
  19942. var j, i; // generate vertices, normals and uvs
  19943. for (j = 0; j <= phiSegments; j++) {
  19944. for (i = 0; i <= thetaSegments; i++) {
  19945. // values are generate from the inside of the ring to the outside
  19946. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19947. vertex.x = radius * Math.cos(segment);
  19948. vertex.y = radius * Math.sin(segment);
  19949. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19950. normals.push(0, 0, 1); // uv
  19951. uv.x = (vertex.x / outerRadius + 1) / 2;
  19952. uv.y = (vertex.y / outerRadius + 1) / 2;
  19953. uvs.push(uv.x, uv.y);
  19954. } // increase the radius for next row of vertices
  19955. radius += radiusStep;
  19956. } // indices
  19957. for (j = 0; j < phiSegments; j++) {
  19958. var thetaSegmentLevel = j * (thetaSegments + 1);
  19959. for (i = 0; i < thetaSegments; i++) {
  19960. segment = i + thetaSegmentLevel;
  19961. var a = segment;
  19962. var b = segment + thetaSegments + 1;
  19963. var c = segment + thetaSegments + 2;
  19964. var d = segment + 1; // faces
  19965. indices.push(a, b, d);
  19966. indices.push(b, c, d);
  19967. }
  19968. } // build geometry
  19969. this.setIndex(indices);
  19970. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  19971. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  19972. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19973. }
  19974. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19975. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  19976. /**
  19977. * @author zz85 / https://github.com/zz85
  19978. * @author bhouston / http://clara.io
  19979. * @author Mugen87 / https://github.com/Mugen87
  19980. */
  19981. // LatheGeometry
  19982. function LatheGeometry(points, segments, phiStart, phiLength) {
  19983. Geometry.call(this);
  19984. this.type = 'LatheGeometry';
  19985. this.parameters = {
  19986. points: points,
  19987. segments: segments,
  19988. phiStart: phiStart,
  19989. phiLength: phiLength
  19990. };
  19991. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19992. this.mergeVertices();
  19993. }
  19994. LatheGeometry.prototype = Object.create(Geometry.prototype);
  19995. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  19996. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  19997. BufferGeometry.call(this);
  19998. this.type = 'LatheBufferGeometry';
  19999. this.parameters = {
  20000. points: points,
  20001. segments: segments,
  20002. phiStart: phiStart,
  20003. phiLength: phiLength
  20004. };
  20005. segments = Math.floor(segments) || 12;
  20006. phiStart = phiStart || 0;
  20007. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  20008. phiLength = _Math.clamp(phiLength, 0, Math.PI * 2); // buffers
  20009. var indices = [];
  20010. var vertices = [];
  20011. var uvs = []; // helper variables
  20012. var base;
  20013. var inverseSegments = 1.0 / segments;
  20014. var vertex = new Vector3();
  20015. var uv = new Vector2();
  20016. var i, j; // generate vertices and uvs
  20017. for (i = 0; i <= segments; i++) {
  20018. var phi = phiStart + i * inverseSegments * phiLength;
  20019. var sin = Math.sin(phi);
  20020. var cos = Math.cos(phi);
  20021. for (j = 0; j <= points.length - 1; j++) {
  20022. // vertex
  20023. vertex.x = points[j].x * sin;
  20024. vertex.y = points[j].y;
  20025. vertex.z = points[j].x * cos;
  20026. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  20027. uv.x = i / segments;
  20028. uv.y = j / (points.length - 1);
  20029. uvs.push(uv.x, uv.y);
  20030. }
  20031. } // indices
  20032. for (i = 0; i < segments; i++) {
  20033. for (j = 0; j < points.length - 1; j++) {
  20034. base = j + i * points.length;
  20035. var a = base;
  20036. var b = base + points.length;
  20037. var c = base + points.length + 1;
  20038. var d = base + 1; // faces
  20039. indices.push(a, b, d);
  20040. indices.push(b, c, d);
  20041. }
  20042. } // build geometry
  20043. this.setIndex(indices);
  20044. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20045. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  20046. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  20047. // because the corresponding vertices are identical (but still have different UVs).
  20048. if (phiLength === Math.PI * 2) {
  20049. var normals = this.attributes.normal.array;
  20050. var n1 = new Vector3();
  20051. var n2 = new Vector3();
  20052. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  20053. base = segments * points.length * 3;
  20054. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  20055. // select the normal of the vertex in the first line
  20056. n1.x = normals[j + 0];
  20057. n1.y = normals[j + 1];
  20058. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  20059. n2.x = normals[base + j + 0];
  20060. n2.y = normals[base + j + 1];
  20061. n2.z = normals[base + j + 2]; // average normals
  20062. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  20063. normals[j + 0] = normals[base + j + 0] = n.x;
  20064. normals[j + 1] = normals[base + j + 1] = n.y;
  20065. normals[j + 2] = normals[base + j + 2] = n.z;
  20066. }
  20067. }
  20068. }
  20069. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20070. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  20071. /**
  20072. * @author jonobr1 / http://jonobr1.com
  20073. * @author Mugen87 / https://github.com/Mugen87
  20074. */
  20075. // ShapeGeometry
  20076. function ShapeGeometry(shapes, curveSegments) {
  20077. Geometry.call(this);
  20078. this.type = 'ShapeGeometry';
  20079. if (typeof curveSegments === 'object') {
  20080. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  20081. curveSegments = curveSegments.curveSegments;
  20082. }
  20083. this.parameters = {
  20084. shapes: shapes,
  20085. curveSegments: curveSegments
  20086. };
  20087. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  20088. this.mergeVertices();
  20089. }
  20090. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  20091. ShapeGeometry.prototype.constructor = ShapeGeometry;
  20092. ShapeGeometry.prototype.toJSON = function () {
  20093. var data = Geometry.prototype.toJSON.call(this);
  20094. var shapes = this.parameters.shapes;
  20095. return toJSON$1(shapes, data);
  20096. }; // ShapeBufferGeometry
  20097. function ShapeBufferGeometry(shapes, curveSegments) {
  20098. BufferGeometry.call(this);
  20099. this.type = 'ShapeBufferGeometry';
  20100. this.parameters = {
  20101. shapes: shapes,
  20102. curveSegments: curveSegments
  20103. };
  20104. curveSegments = curveSegments || 12; // buffers
  20105. var indices = [];
  20106. var vertices = [];
  20107. var normals = [];
  20108. var uvs = []; // helper variables
  20109. var groupStart = 0;
  20110. var groupCount = 0; // allow single and array values for "shapes" parameter
  20111. if (Array.isArray(shapes) === false) {
  20112. addShape(shapes);
  20113. } else {
  20114. for (var i = 0; i < shapes.length; i++) {
  20115. addShape(shapes[i]);
  20116. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20117. groupStart += groupCount;
  20118. groupCount = 0;
  20119. }
  20120. } // build geometry
  20121. this.setIndex(indices);
  20122. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20123. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20124. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20125. function addShape(shape) {
  20126. var i, l, shapeHole;
  20127. var indexOffset = vertices.length / 3;
  20128. var points = shape.extractPoints(curveSegments);
  20129. var shapeVertices = points.shape;
  20130. var shapeHoles = points.holes; // check direction of vertices
  20131. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20132. shapeVertices = shapeVertices.reverse();
  20133. }
  20134. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20135. shapeHole = shapeHoles[i];
  20136. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20137. shapeHoles[i] = shapeHole.reverse();
  20138. }
  20139. }
  20140. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20141. for (i = 0, l = shapeHoles.length; i < l; i++) {
  20142. shapeHole = shapeHoles[i];
  20143. shapeVertices = shapeVertices.concat(shapeHole);
  20144. } // vertices, normals, uvs
  20145. for (i = 0, l = shapeVertices.length; i < l; i++) {
  20146. var vertex = shapeVertices[i];
  20147. vertices.push(vertex.x, vertex.y, 0);
  20148. normals.push(0, 0, 1);
  20149. uvs.push(vertex.x, vertex.y); // world uvs
  20150. } // incides
  20151. for (i = 0, l = faces.length; i < l; i++) {
  20152. var face = faces[i];
  20153. var a = face[0] + indexOffset;
  20154. var b = face[1] + indexOffset;
  20155. var c = face[2] + indexOffset;
  20156. indices.push(a, b, c);
  20157. groupCount += 3;
  20158. }
  20159. }
  20160. }
  20161. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20162. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  20163. ShapeBufferGeometry.prototype.toJSON = function () {
  20164. var data = BufferGeometry.prototype.toJSON.call(this);
  20165. var shapes = this.parameters.shapes;
  20166. return toJSON$1(shapes, data);
  20167. }; //
  20168. function toJSON$1(shapes, data) {
  20169. data.shapes = [];
  20170. if (Array.isArray(shapes)) {
  20171. for (var i = 0, l = shapes.length; i < l; i++) {
  20172. var shape = shapes[i];
  20173. data.shapes.push(shape.uuid);
  20174. }
  20175. } else {
  20176. data.shapes.push(shapes.uuid);
  20177. }
  20178. return data;
  20179. }
  20180. /**
  20181. * @author WestLangley / http://github.com/WestLangley
  20182. * @author Mugen87 / https://github.com/Mugen87
  20183. */
  20184. function EdgesGeometry(geometry, thresholdAngle) {
  20185. BufferGeometry.call(this);
  20186. this.type = 'EdgesGeometry';
  20187. this.parameters = {
  20188. thresholdAngle: thresholdAngle
  20189. };
  20190. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  20191. var vertices = []; // helper variables
  20192. var thresholdDot = Math.cos(_Math.DEG2RAD * thresholdAngle);
  20193. var edge = [0, 0],
  20194. edges = {},
  20195. edge1,
  20196. edge2;
  20197. var key,
  20198. keys = ['a', 'b', 'c']; // prepare source geometry
  20199. var geometry2;
  20200. if (geometry.isBufferGeometry) {
  20201. geometry2 = new Geometry();
  20202. geometry2.fromBufferGeometry(geometry);
  20203. } else {
  20204. geometry2 = geometry.clone();
  20205. }
  20206. geometry2.mergeVertices();
  20207. geometry2.computeFaceNormals();
  20208. var sourceVertices = geometry2.vertices;
  20209. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  20210. for (var i = 0, l = faces.length; i < l; i++) {
  20211. var face = faces[i];
  20212. for (var j = 0; j < 3; j++) {
  20213. edge1 = face[keys[j]];
  20214. edge2 = face[keys[(j + 1) % 3]];
  20215. edge[0] = Math.min(edge1, edge2);
  20216. edge[1] = Math.max(edge1, edge2);
  20217. key = edge[0] + ',' + edge[1];
  20218. if (edges[key] === undefined) {
  20219. edges[key] = {
  20220. index1: edge[0],
  20221. index2: edge[1],
  20222. face1: i,
  20223. face2: undefined
  20224. };
  20225. } else {
  20226. edges[key].face2 = i;
  20227. }
  20228. }
  20229. } // generate vertices
  20230. for (key in edges) {
  20231. 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.
  20232. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  20233. var vertex = sourceVertices[e.index1];
  20234. vertices.push(vertex.x, vertex.y, vertex.z);
  20235. vertex = sourceVertices[e.index2];
  20236. vertices.push(vertex.x, vertex.y, vertex.z);
  20237. }
  20238. } // build geometry
  20239. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20240. }
  20241. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  20242. EdgesGeometry.prototype.constructor = EdgesGeometry;
  20243. /**
  20244. * @author mrdoob / http://mrdoob.com/
  20245. * @author Mugen87 / https://github.com/Mugen87
  20246. */
  20247. // CylinderGeometry
  20248. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20249. Geometry.call(this);
  20250. this.type = 'CylinderGeometry';
  20251. this.parameters = {
  20252. radiusTop: radiusTop,
  20253. radiusBottom: radiusBottom,
  20254. height: height,
  20255. radialSegments: radialSegments,
  20256. heightSegments: heightSegments,
  20257. openEnded: openEnded,
  20258. thetaStart: thetaStart,
  20259. thetaLength: thetaLength
  20260. };
  20261. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  20262. this.mergeVertices();
  20263. }
  20264. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  20265. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  20266. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20267. BufferGeometry.call(this);
  20268. this.type = 'CylinderBufferGeometry';
  20269. this.parameters = {
  20270. radiusTop: radiusTop,
  20271. radiusBottom: radiusBottom,
  20272. height: height,
  20273. radialSegments: radialSegments,
  20274. heightSegments: heightSegments,
  20275. openEnded: openEnded,
  20276. thetaStart: thetaStart,
  20277. thetaLength: thetaLength
  20278. };
  20279. var scope = this;
  20280. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  20281. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  20282. height = height || 1;
  20283. radialSegments = Math.floor(radialSegments) || 8;
  20284. heightSegments = Math.floor(heightSegments) || 1;
  20285. openEnded = openEnded !== undefined ? openEnded : false;
  20286. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  20287. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20288. var indices = [];
  20289. var vertices = [];
  20290. var normals = [];
  20291. var uvs = []; // helper variables
  20292. var index = 0;
  20293. var indexArray = [];
  20294. var halfHeight = height / 2;
  20295. var groupStart = 0; // generate geometry
  20296. generateTorso();
  20297. if (openEnded === false) {
  20298. if (radiusTop > 0) generateCap(true);
  20299. if (radiusBottom > 0) generateCap(false);
  20300. } // build geometry
  20301. this.setIndex(indices);
  20302. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20303. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20304. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20305. function generateTorso() {
  20306. var x, y;
  20307. var normal = new Vector3();
  20308. var vertex = new Vector3();
  20309. var groupCount = 0; // this will be used to calculate the normal
  20310. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  20311. for (y = 0; y <= heightSegments; y++) {
  20312. var indexRow = [];
  20313. var v = y / heightSegments; // calculate the radius of the current row
  20314. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  20315. for (x = 0; x <= radialSegments; x++) {
  20316. var u = x / radialSegments;
  20317. var theta = u * thetaLength + thetaStart;
  20318. var sinTheta = Math.sin(theta);
  20319. var cosTheta = Math.cos(theta); // vertex
  20320. vertex.x = radius * sinTheta;
  20321. vertex.y = -v * height + halfHeight;
  20322. vertex.z = radius * cosTheta;
  20323. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20324. normal.set(sinTheta, slope, cosTheta).normalize();
  20325. normals.push(normal.x, normal.y, normal.z); // uv
  20326. uvs.push(u, 1 - v); // save index of vertex in respective row
  20327. indexRow.push(index++);
  20328. } // now save vertices of the row in our index array
  20329. indexArray.push(indexRow);
  20330. } // generate indices
  20331. for (x = 0; x < radialSegments; x++) {
  20332. for (y = 0; y < heightSegments; y++) {
  20333. // we use the index array to access the correct indices
  20334. var a = indexArray[y][x];
  20335. var b = indexArray[y + 1][x];
  20336. var c = indexArray[y + 1][x + 1];
  20337. var d = indexArray[y][x + 1]; // faces
  20338. indices.push(a, b, d);
  20339. indices.push(b, c, d); // update group counter
  20340. groupCount += 6;
  20341. }
  20342. } // add a group to the geometry. this will ensure multi material support
  20343. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  20344. groupStart += groupCount;
  20345. }
  20346. function generateCap(top) {
  20347. var x, centerIndexStart, centerIndexEnd;
  20348. var uv = new Vector2();
  20349. var vertex = new Vector3();
  20350. var groupCount = 0;
  20351. var radius = top === true ? radiusTop : radiusBottom;
  20352. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  20353. centerIndexStart = index; // first we generate the center vertex data of the cap.
  20354. // because the geometry needs one set of uvs per face,
  20355. // we must generate a center vertex per face/segment
  20356. for (x = 1; x <= radialSegments; x++) {
  20357. // vertex
  20358. vertices.push(0, halfHeight * sign, 0); // normal
  20359. normals.push(0, sign, 0); // uv
  20360. uvs.push(0.5, 0.5); // increase index
  20361. index++;
  20362. } // save the index of the last center vertex
  20363. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  20364. for (x = 0; x <= radialSegments; x++) {
  20365. var u = x / radialSegments;
  20366. var theta = u * thetaLength + thetaStart;
  20367. var cosTheta = Math.cos(theta);
  20368. var sinTheta = Math.sin(theta); // vertex
  20369. vertex.x = radius * sinTheta;
  20370. vertex.y = halfHeight * sign;
  20371. vertex.z = radius * cosTheta;
  20372. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20373. normals.push(0, sign, 0); // uv
  20374. uv.x = cosTheta * 0.5 + 0.5;
  20375. uv.y = sinTheta * 0.5 * sign + 0.5;
  20376. uvs.push(uv.x, uv.y); // increase index
  20377. index++;
  20378. } // generate indices
  20379. for (x = 0; x < radialSegments; x++) {
  20380. var c = centerIndexStart + x;
  20381. var i = centerIndexEnd + x;
  20382. if (top === true) {
  20383. // face top
  20384. indices.push(i, i + 1, c);
  20385. } else {
  20386. // face bottom
  20387. indices.push(i + 1, i, c);
  20388. }
  20389. groupCount += 3;
  20390. } // add a group to the geometry. this will ensure multi material support
  20391. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  20392. groupStart += groupCount;
  20393. }
  20394. }
  20395. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20396. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  20397. /**
  20398. * @author abelnation / http://github.com/abelnation
  20399. */
  20400. // ConeGeometry
  20401. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20402. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20403. this.type = 'ConeGeometry';
  20404. this.parameters = {
  20405. radius: radius,
  20406. height: height,
  20407. radialSegments: radialSegments,
  20408. heightSegments: heightSegments,
  20409. openEnded: openEnded,
  20410. thetaStart: thetaStart,
  20411. thetaLength: thetaLength
  20412. };
  20413. }
  20414. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  20415. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  20416. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  20417. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  20418. this.type = 'ConeBufferGeometry';
  20419. this.parameters = {
  20420. radius: radius,
  20421. height: height,
  20422. radialSegments: radialSegments,
  20423. heightSegments: heightSegments,
  20424. openEnded: openEnded,
  20425. thetaStart: thetaStart,
  20426. thetaLength: thetaLength
  20427. };
  20428. }
  20429. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  20430. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  20431. /**
  20432. * @author benaadams / https://twitter.com/ben_a_adams
  20433. * @author Mugen87 / https://github.com/Mugen87
  20434. * @author hughes
  20435. */
  20436. // CircleGeometry
  20437. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  20438. Geometry.call(this);
  20439. this.type = 'CircleGeometry';
  20440. this.parameters = {
  20441. radius: radius,
  20442. segments: segments,
  20443. thetaStart: thetaStart,
  20444. thetaLength: thetaLength
  20445. };
  20446. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  20447. this.mergeVertices();
  20448. }
  20449. CircleGeometry.prototype = Object.create(Geometry.prototype);
  20450. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  20451. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  20452. BufferGeometry.call(this);
  20453. this.type = 'CircleBufferGeometry';
  20454. this.parameters = {
  20455. radius: radius,
  20456. segments: segments,
  20457. thetaStart: thetaStart,
  20458. thetaLength: thetaLength
  20459. };
  20460. radius = radius || 1;
  20461. segments = segments !== undefined ? Math.max(3, segments) : 8;
  20462. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20463. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  20464. var indices = [];
  20465. var vertices = [];
  20466. var normals = [];
  20467. var uvs = []; // helper variables
  20468. var i, s;
  20469. var vertex = new Vector3();
  20470. var uv = new Vector2(); // center point
  20471. vertices.push(0, 0, 0);
  20472. normals.push(0, 0, 1);
  20473. uvs.push(0.5, 0.5);
  20474. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  20475. var segment = thetaStart + s / segments * thetaLength; // vertex
  20476. vertex.x = radius * Math.cos(segment);
  20477. vertex.y = radius * Math.sin(segment);
  20478. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20479. normals.push(0, 0, 1); // uvs
  20480. uv.x = (vertices[i] / radius + 1) / 2;
  20481. uv.y = (vertices[i + 1] / radius + 1) / 2;
  20482. uvs.push(uv.x, uv.y);
  20483. } // indices
  20484. for (i = 1; i <= segments; i++) {
  20485. indices.push(i, i + 1, 0);
  20486. } // build geometry
  20487. this.setIndex(indices);
  20488. this.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  20489. this.addAttribute('normal', new Float32BufferAttribute(normals, 3));
  20490. this.addAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20491. }
  20492. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  20493. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  20494. var Geometries =
  20495. /*#__PURE__*/
  20496. Object.freeze({
  20497. WireframeGeometry: WireframeGeometry,
  20498. ParametricGeometry: ParametricGeometry,
  20499. ParametricBufferGeometry: ParametricBufferGeometry,
  20500. TetrahedronGeometry: TetrahedronGeometry,
  20501. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20502. OctahedronGeometry: OctahedronGeometry,
  20503. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20504. IcosahedronGeometry: IcosahedronGeometry,
  20505. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20506. DodecahedronGeometry: DodecahedronGeometry,
  20507. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20508. PolyhedronGeometry: PolyhedronGeometry,
  20509. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20510. TubeGeometry: TubeGeometry,
  20511. TubeBufferGeometry: TubeBufferGeometry,
  20512. TorusKnotGeometry: TorusKnotGeometry,
  20513. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20514. TorusGeometry: TorusGeometry,
  20515. TorusBufferGeometry: TorusBufferGeometry,
  20516. TextGeometry: TextGeometry,
  20517. TextBufferGeometry: TextBufferGeometry,
  20518. SphereGeometry: SphereGeometry,
  20519. SphereBufferGeometry: SphereBufferGeometry,
  20520. RingGeometry: RingGeometry,
  20521. RingBufferGeometry: RingBufferGeometry,
  20522. PlaneGeometry: PlaneGeometry,
  20523. PlaneBufferGeometry: PlaneBufferGeometry,
  20524. LatheGeometry: LatheGeometry,
  20525. LatheBufferGeometry: LatheBufferGeometry,
  20526. ShapeGeometry: ShapeGeometry,
  20527. ShapeBufferGeometry: ShapeBufferGeometry,
  20528. ExtrudeGeometry: ExtrudeGeometry,
  20529. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20530. EdgesGeometry: EdgesGeometry,
  20531. ConeGeometry: ConeGeometry,
  20532. ConeBufferGeometry: ConeBufferGeometry,
  20533. CylinderGeometry: CylinderGeometry,
  20534. CylinderBufferGeometry: CylinderBufferGeometry,
  20535. CircleGeometry: CircleGeometry,
  20536. CircleBufferGeometry: CircleBufferGeometry,
  20537. BoxGeometry: BoxGeometry,
  20538. BoxBufferGeometry: BoxBufferGeometry
  20539. });
  20540. /**
  20541. * @author mrdoob / http://mrdoob.com/
  20542. *
  20543. * parameters = {
  20544. * color: <THREE.Color>
  20545. * }
  20546. */
  20547. function ShadowMaterial(parameters) {
  20548. Material.call(this);
  20549. this.type = 'ShadowMaterial';
  20550. this.color = new Color(0x000000);
  20551. this.transparent = true;
  20552. this.setValues(parameters);
  20553. }
  20554. ShadowMaterial.prototype = Object.create(Material.prototype);
  20555. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20556. ShadowMaterial.prototype.isShadowMaterial = true;
  20557. ShadowMaterial.prototype.copy = function (source) {
  20558. Material.prototype.copy.call(this, source);
  20559. this.color.copy(source.color);
  20560. return this;
  20561. };
  20562. /**
  20563. * @author mrdoob / http://mrdoob.com/
  20564. */
  20565. function RawShaderMaterial(parameters) {
  20566. ShaderMaterial.call(this, parameters);
  20567. this.type = 'RawShaderMaterial';
  20568. }
  20569. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  20570. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20571. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20572. /**
  20573. * @author WestLangley / http://github.com/WestLangley
  20574. *
  20575. * parameters = {
  20576. * color: <hex>,
  20577. * roughness: <float>,
  20578. * metalness: <float>,
  20579. * opacity: <float>,
  20580. *
  20581. * map: new THREE.Texture( <Image> ),
  20582. *
  20583. * lightMap: new THREE.Texture( <Image> ),
  20584. * lightMapIntensity: <float>
  20585. *
  20586. * aoMap: new THREE.Texture( <Image> ),
  20587. * aoMapIntensity: <float>
  20588. *
  20589. * emissive: <hex>,
  20590. * emissiveIntensity: <float>
  20591. * emissiveMap: new THREE.Texture( <Image> ),
  20592. *
  20593. * bumpMap: new THREE.Texture( <Image> ),
  20594. * bumpScale: <float>,
  20595. *
  20596. * normalMap: new THREE.Texture( <Image> ),
  20597. * normalMapType: THREE.TangentSpaceNormalMap,
  20598. * normalScale: <Vector2>,
  20599. *
  20600. * displacementMap: new THREE.Texture( <Image> ),
  20601. * displacementScale: <float>,
  20602. * displacementBias: <float>,
  20603. *
  20604. * roughnessMap: new THREE.Texture( <Image> ),
  20605. *
  20606. * metalnessMap: new THREE.Texture( <Image> ),
  20607. *
  20608. * alphaMap: new THREE.Texture( <Image> ),
  20609. *
  20610. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20611. * envMapIntensity: <float>
  20612. *
  20613. * refractionRatio: <float>,
  20614. *
  20615. * wireframe: <boolean>,
  20616. * wireframeLinewidth: <float>,
  20617. *
  20618. * skinning: <bool>,
  20619. * morphTargets: <bool>,
  20620. * morphNormals: <bool>
  20621. * }
  20622. */
  20623. function MeshStandardMaterial(parameters) {
  20624. Material.call(this);
  20625. this.defines = {
  20626. 'STANDARD': ''
  20627. };
  20628. this.type = 'MeshStandardMaterial';
  20629. this.color = new Color(0xffffff); // diffuse
  20630. this.roughness = 0.5;
  20631. this.metalness = 0.5;
  20632. this.map = null;
  20633. this.lightMap = null;
  20634. this.lightMapIntensity = 1.0;
  20635. this.aoMap = null;
  20636. this.aoMapIntensity = 1.0;
  20637. this.emissive = new Color(0x000000);
  20638. this.emissiveIntensity = 1.0;
  20639. this.emissiveMap = null;
  20640. this.bumpMap = null;
  20641. this.bumpScale = 1;
  20642. this.normalMap = null;
  20643. this.normalMapType = TangentSpaceNormalMap;
  20644. this.normalScale = new Vector2(1, 1);
  20645. this.displacementMap = null;
  20646. this.displacementScale = 1;
  20647. this.displacementBias = 0;
  20648. this.roughnessMap = null;
  20649. this.metalnessMap = null;
  20650. this.alphaMap = null;
  20651. this.envMap = null;
  20652. this.envMapIntensity = 1.0;
  20653. this.refractionRatio = 0.98;
  20654. this.wireframe = false;
  20655. this.wireframeLinewidth = 1;
  20656. this.wireframeLinecap = 'round';
  20657. this.wireframeLinejoin = 'round';
  20658. this.skinning = false;
  20659. this.morphTargets = false;
  20660. this.morphNormals = false;
  20661. this.setValues(parameters);
  20662. }
  20663. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  20664. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20665. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20666. MeshStandardMaterial.prototype.copy = function (source) {
  20667. Material.prototype.copy.call(this, source);
  20668. this.defines = {
  20669. 'STANDARD': ''
  20670. };
  20671. this.color.copy(source.color);
  20672. this.roughness = source.roughness;
  20673. this.metalness = source.metalness;
  20674. this.map = source.map;
  20675. this.lightMap = source.lightMap;
  20676. this.lightMapIntensity = source.lightMapIntensity;
  20677. this.aoMap = source.aoMap;
  20678. this.aoMapIntensity = source.aoMapIntensity;
  20679. this.emissive.copy(source.emissive);
  20680. this.emissiveMap = source.emissiveMap;
  20681. this.emissiveIntensity = source.emissiveIntensity;
  20682. this.bumpMap = source.bumpMap;
  20683. this.bumpScale = source.bumpScale;
  20684. this.normalMap = source.normalMap;
  20685. this.normalMapType = source.normalMapType;
  20686. this.normalScale.copy(source.normalScale);
  20687. this.displacementMap = source.displacementMap;
  20688. this.displacementScale = source.displacementScale;
  20689. this.displacementBias = source.displacementBias;
  20690. this.roughnessMap = source.roughnessMap;
  20691. this.metalnessMap = source.metalnessMap;
  20692. this.alphaMap = source.alphaMap;
  20693. this.envMap = source.envMap;
  20694. this.envMapIntensity = source.envMapIntensity;
  20695. this.refractionRatio = source.refractionRatio;
  20696. this.wireframe = source.wireframe;
  20697. this.wireframeLinewidth = source.wireframeLinewidth;
  20698. this.wireframeLinecap = source.wireframeLinecap;
  20699. this.wireframeLinejoin = source.wireframeLinejoin;
  20700. this.skinning = source.skinning;
  20701. this.morphTargets = source.morphTargets;
  20702. this.morphNormals = source.morphNormals;
  20703. return this;
  20704. };
  20705. /**
  20706. * @author WestLangley / http://github.com/WestLangley
  20707. *
  20708. * parameters = {
  20709. * reflectivity: <float>
  20710. * clearcoat: <float>
  20711. * clearcoatRoughness: <float>
  20712. *
  20713. * sheen: <Color>
  20714. *
  20715. * clearcoatNormalScale: <Vector2>,
  20716. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20717. * }
  20718. */
  20719. function MeshPhysicalMaterial(parameters) {
  20720. MeshStandardMaterial.call(this);
  20721. this.defines = {
  20722. 'STANDARD': '',
  20723. 'PHYSICAL': ''
  20724. };
  20725. this.type = 'MeshPhysicalMaterial';
  20726. this.reflectivity = 0.5; // maps to F0 = 0.04
  20727. this.clearcoat = 0.0;
  20728. this.clearcoatRoughness = 0.0;
  20729. this.sheen = null; // null will disable sheen bsdf
  20730. this.clearcoatNormalScale = new Vector2(1, 1);
  20731. this.clearcoatNormalMap = null;
  20732. this.transparency = 0.0;
  20733. this.setValues(parameters);
  20734. }
  20735. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  20736. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20737. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20738. MeshPhysicalMaterial.prototype.copy = function (source) {
  20739. MeshStandardMaterial.prototype.copy.call(this, source);
  20740. this.defines = {
  20741. 'STANDARD': '',
  20742. 'PHYSICAL': ''
  20743. };
  20744. this.reflectivity = source.reflectivity;
  20745. this.clearcoat = source.clearcoat;
  20746. this.clearcoatRoughness = source.clearcoatRoughness;
  20747. if (source.sheen) this.sheen = (this.sheen || new Color()).copy(source.sheen);else this.sheen = null;
  20748. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20749. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20750. this.transparency = source.transparency;
  20751. return this;
  20752. };
  20753. /**
  20754. * @author mrdoob / http://mrdoob.com/
  20755. * @author alteredq / http://alteredqualia.com/
  20756. *
  20757. * parameters = {
  20758. * color: <hex>,
  20759. * specular: <hex>,
  20760. * shininess: <float>,
  20761. * opacity: <float>,
  20762. *
  20763. * map: new THREE.Texture( <Image> ),
  20764. *
  20765. * lightMap: new THREE.Texture( <Image> ),
  20766. * lightMapIntensity: <float>
  20767. *
  20768. * aoMap: new THREE.Texture( <Image> ),
  20769. * aoMapIntensity: <float>
  20770. *
  20771. * emissive: <hex>,
  20772. * emissiveIntensity: <float>
  20773. * emissiveMap: new THREE.Texture( <Image> ),
  20774. *
  20775. * bumpMap: new THREE.Texture( <Image> ),
  20776. * bumpScale: <float>,
  20777. *
  20778. * normalMap: new THREE.Texture( <Image> ),
  20779. * normalMapType: THREE.TangentSpaceNormalMap,
  20780. * normalScale: <Vector2>,
  20781. *
  20782. * displacementMap: new THREE.Texture( <Image> ),
  20783. * displacementScale: <float>,
  20784. * displacementBias: <float>,
  20785. *
  20786. * specularMap: new THREE.Texture( <Image> ),
  20787. *
  20788. * alphaMap: new THREE.Texture( <Image> ),
  20789. *
  20790. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20791. * combine: THREE.Multiply,
  20792. * reflectivity: <float>,
  20793. * refractionRatio: <float>,
  20794. *
  20795. * wireframe: <boolean>,
  20796. * wireframeLinewidth: <float>,
  20797. *
  20798. * skinning: <bool>,
  20799. * morphTargets: <bool>,
  20800. * morphNormals: <bool>
  20801. * }
  20802. */
  20803. function MeshPhongMaterial(parameters) {
  20804. Material.call(this);
  20805. this.type = 'MeshPhongMaterial';
  20806. this.color = new Color(0xffffff); // diffuse
  20807. this.specular = new Color(0x111111);
  20808. this.shininess = 30;
  20809. this.map = null;
  20810. this.lightMap = null;
  20811. this.lightMapIntensity = 1.0;
  20812. this.aoMap = null;
  20813. this.aoMapIntensity = 1.0;
  20814. this.emissive = new Color(0x000000);
  20815. this.emissiveIntensity = 1.0;
  20816. this.emissiveMap = null;
  20817. this.bumpMap = null;
  20818. this.bumpScale = 1;
  20819. this.normalMap = null;
  20820. this.normalMapType = TangentSpaceNormalMap;
  20821. this.normalScale = new Vector2(1, 1);
  20822. this.displacementMap = null;
  20823. this.displacementScale = 1;
  20824. this.displacementBias = 0;
  20825. this.specularMap = null;
  20826. this.alphaMap = null;
  20827. this.envMap = null;
  20828. this.combine = MultiplyOperation;
  20829. this.reflectivity = 1;
  20830. this.refractionRatio = 0.98;
  20831. this.wireframe = false;
  20832. this.wireframeLinewidth = 1;
  20833. this.wireframeLinecap = 'round';
  20834. this.wireframeLinejoin = 'round';
  20835. this.skinning = false;
  20836. this.morphTargets = false;
  20837. this.morphNormals = false;
  20838. this.setValues(parameters);
  20839. }
  20840. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  20841. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20842. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20843. MeshPhongMaterial.prototype.copy = function (source) {
  20844. Material.prototype.copy.call(this, source);
  20845. this.color.copy(source.color);
  20846. this.specular.copy(source.specular);
  20847. this.shininess = source.shininess;
  20848. this.map = source.map;
  20849. this.lightMap = source.lightMap;
  20850. this.lightMapIntensity = source.lightMapIntensity;
  20851. this.aoMap = source.aoMap;
  20852. this.aoMapIntensity = source.aoMapIntensity;
  20853. this.emissive.copy(source.emissive);
  20854. this.emissiveMap = source.emissiveMap;
  20855. this.emissiveIntensity = source.emissiveIntensity;
  20856. this.bumpMap = source.bumpMap;
  20857. this.bumpScale = source.bumpScale;
  20858. this.normalMap = source.normalMap;
  20859. this.normalMapType = source.normalMapType;
  20860. this.normalScale.copy(source.normalScale);
  20861. this.displacementMap = source.displacementMap;
  20862. this.displacementScale = source.displacementScale;
  20863. this.displacementBias = source.displacementBias;
  20864. this.specularMap = source.specularMap;
  20865. this.alphaMap = source.alphaMap;
  20866. this.envMap = source.envMap;
  20867. this.combine = source.combine;
  20868. this.reflectivity = source.reflectivity;
  20869. this.refractionRatio = source.refractionRatio;
  20870. this.wireframe = source.wireframe;
  20871. this.wireframeLinewidth = source.wireframeLinewidth;
  20872. this.wireframeLinecap = source.wireframeLinecap;
  20873. this.wireframeLinejoin = source.wireframeLinejoin;
  20874. this.skinning = source.skinning;
  20875. this.morphTargets = source.morphTargets;
  20876. this.morphNormals = source.morphNormals;
  20877. return this;
  20878. };
  20879. /**
  20880. * @author takahirox / http://github.com/takahirox
  20881. *
  20882. * parameters = {
  20883. * gradientMap: new THREE.Texture( <Image> )
  20884. * }
  20885. */
  20886. function MeshToonMaterial(parameters) {
  20887. MeshPhongMaterial.call(this);
  20888. this.defines = {
  20889. 'TOON': ''
  20890. };
  20891. this.type = 'MeshToonMaterial';
  20892. this.gradientMap = null;
  20893. this.setValues(parameters);
  20894. }
  20895. MeshToonMaterial.prototype = Object.create(MeshPhongMaterial.prototype);
  20896. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20897. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20898. MeshToonMaterial.prototype.copy = function (source) {
  20899. MeshPhongMaterial.prototype.copy.call(this, source);
  20900. this.gradientMap = source.gradientMap;
  20901. return this;
  20902. };
  20903. /**
  20904. * @author mrdoob / http://mrdoob.com/
  20905. * @author WestLangley / http://github.com/WestLangley
  20906. *
  20907. * parameters = {
  20908. * opacity: <float>,
  20909. *
  20910. * bumpMap: new THREE.Texture( <Image> ),
  20911. * bumpScale: <float>,
  20912. *
  20913. * normalMap: new THREE.Texture( <Image> ),
  20914. * normalMapType: THREE.TangentSpaceNormalMap,
  20915. * normalScale: <Vector2>,
  20916. *
  20917. * displacementMap: new THREE.Texture( <Image> ),
  20918. * displacementScale: <float>,
  20919. * displacementBias: <float>,
  20920. *
  20921. * wireframe: <boolean>,
  20922. * wireframeLinewidth: <float>
  20923. *
  20924. * skinning: <bool>,
  20925. * morphTargets: <bool>,
  20926. * morphNormals: <bool>
  20927. * }
  20928. */
  20929. function MeshNormalMaterial(parameters) {
  20930. Material.call(this);
  20931. this.type = 'MeshNormalMaterial';
  20932. this.bumpMap = null;
  20933. this.bumpScale = 1;
  20934. this.normalMap = null;
  20935. this.normalMapType = TangentSpaceNormalMap;
  20936. this.normalScale = new Vector2(1, 1);
  20937. this.displacementMap = null;
  20938. this.displacementScale = 1;
  20939. this.displacementBias = 0;
  20940. this.wireframe = false;
  20941. this.wireframeLinewidth = 1;
  20942. this.fog = false;
  20943. this.skinning = false;
  20944. this.morphTargets = false;
  20945. this.morphNormals = false;
  20946. this.setValues(parameters);
  20947. }
  20948. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20949. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20950. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20951. MeshNormalMaterial.prototype.copy = function (source) {
  20952. Material.prototype.copy.call(this, source);
  20953. this.bumpMap = source.bumpMap;
  20954. this.bumpScale = source.bumpScale;
  20955. this.normalMap = source.normalMap;
  20956. this.normalMapType = source.normalMapType;
  20957. this.normalScale.copy(source.normalScale);
  20958. this.displacementMap = source.displacementMap;
  20959. this.displacementScale = source.displacementScale;
  20960. this.displacementBias = source.displacementBias;
  20961. this.wireframe = source.wireframe;
  20962. this.wireframeLinewidth = source.wireframeLinewidth;
  20963. this.skinning = source.skinning;
  20964. this.morphTargets = source.morphTargets;
  20965. this.morphNormals = source.morphNormals;
  20966. return this;
  20967. };
  20968. /**
  20969. * @author mrdoob / http://mrdoob.com/
  20970. * @author alteredq / http://alteredqualia.com/
  20971. *
  20972. * parameters = {
  20973. * color: <hex>,
  20974. * opacity: <float>,
  20975. *
  20976. * map: new THREE.Texture( <Image> ),
  20977. *
  20978. * lightMap: new THREE.Texture( <Image> ),
  20979. * lightMapIntensity: <float>
  20980. *
  20981. * aoMap: new THREE.Texture( <Image> ),
  20982. * aoMapIntensity: <float>
  20983. *
  20984. * emissive: <hex>,
  20985. * emissiveIntensity: <float>
  20986. * emissiveMap: new THREE.Texture( <Image> ),
  20987. *
  20988. * specularMap: new THREE.Texture( <Image> ),
  20989. *
  20990. * alphaMap: new THREE.Texture( <Image> ),
  20991. *
  20992. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20993. * combine: THREE.Multiply,
  20994. * reflectivity: <float>,
  20995. * refractionRatio: <float>,
  20996. *
  20997. * wireframe: <boolean>,
  20998. * wireframeLinewidth: <float>,
  20999. *
  21000. * skinning: <bool>,
  21001. * morphTargets: <bool>,
  21002. * morphNormals: <bool>
  21003. * }
  21004. */
  21005. function MeshLambertMaterial(parameters) {
  21006. Material.call(this);
  21007. this.type = 'MeshLambertMaterial';
  21008. this.color = new Color(0xffffff); // diffuse
  21009. this.map = null;
  21010. this.lightMap = null;
  21011. this.lightMapIntensity = 1.0;
  21012. this.aoMap = null;
  21013. this.aoMapIntensity = 1.0;
  21014. this.emissive = new Color(0x000000);
  21015. this.emissiveIntensity = 1.0;
  21016. this.emissiveMap = null;
  21017. this.specularMap = null;
  21018. this.alphaMap = null;
  21019. this.envMap = null;
  21020. this.combine = MultiplyOperation;
  21021. this.reflectivity = 1;
  21022. this.refractionRatio = 0.98;
  21023. this.wireframe = false;
  21024. this.wireframeLinewidth = 1;
  21025. this.wireframeLinecap = 'round';
  21026. this.wireframeLinejoin = 'round';
  21027. this.skinning = false;
  21028. this.morphTargets = false;
  21029. this.morphNormals = false;
  21030. this.setValues(parameters);
  21031. }
  21032. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  21033. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21034. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21035. MeshLambertMaterial.prototype.copy = function (source) {
  21036. Material.prototype.copy.call(this, source);
  21037. this.color.copy(source.color);
  21038. this.map = source.map;
  21039. this.lightMap = source.lightMap;
  21040. this.lightMapIntensity = source.lightMapIntensity;
  21041. this.aoMap = source.aoMap;
  21042. this.aoMapIntensity = source.aoMapIntensity;
  21043. this.emissive.copy(source.emissive);
  21044. this.emissiveMap = source.emissiveMap;
  21045. this.emissiveIntensity = source.emissiveIntensity;
  21046. this.specularMap = source.specularMap;
  21047. this.alphaMap = source.alphaMap;
  21048. this.envMap = source.envMap;
  21049. this.combine = source.combine;
  21050. this.reflectivity = source.reflectivity;
  21051. this.refractionRatio = source.refractionRatio;
  21052. this.wireframe = source.wireframe;
  21053. this.wireframeLinewidth = source.wireframeLinewidth;
  21054. this.wireframeLinecap = source.wireframeLinecap;
  21055. this.wireframeLinejoin = source.wireframeLinejoin;
  21056. this.skinning = source.skinning;
  21057. this.morphTargets = source.morphTargets;
  21058. this.morphNormals = source.morphNormals;
  21059. return this;
  21060. };
  21061. /**
  21062. * @author WestLangley / http://github.com/WestLangley
  21063. *
  21064. * parameters = {
  21065. * color: <hex>,
  21066. * opacity: <float>,
  21067. *
  21068. * matcap: new THREE.Texture( <Image> ),
  21069. *
  21070. * map: new THREE.Texture( <Image> ),
  21071. *
  21072. * bumpMap: new THREE.Texture( <Image> ),
  21073. * bumpScale: <float>,
  21074. *
  21075. * normalMap: new THREE.Texture( <Image> ),
  21076. * normalMapType: THREE.TangentSpaceNormalMap,
  21077. * normalScale: <Vector2>,
  21078. *
  21079. * displacementMap: new THREE.Texture( <Image> ),
  21080. * displacementScale: <float>,
  21081. * displacementBias: <float>,
  21082. *
  21083. * alphaMap: new THREE.Texture( <Image> ),
  21084. *
  21085. * skinning: <bool>,
  21086. * morphTargets: <bool>,
  21087. * morphNormals: <bool>
  21088. * }
  21089. */
  21090. function MeshMatcapMaterial(parameters) {
  21091. Material.call(this);
  21092. this.defines = {
  21093. 'MATCAP': ''
  21094. };
  21095. this.type = 'MeshMatcapMaterial';
  21096. this.color = new Color(0xffffff); // diffuse
  21097. this.matcap = null;
  21098. this.map = null;
  21099. this.bumpMap = null;
  21100. this.bumpScale = 1;
  21101. this.normalMap = null;
  21102. this.normalMapType = TangentSpaceNormalMap;
  21103. this.normalScale = new Vector2(1, 1);
  21104. this.displacementMap = null;
  21105. this.displacementScale = 1;
  21106. this.displacementBias = 0;
  21107. this.alphaMap = null;
  21108. this.skinning = false;
  21109. this.morphTargets = false;
  21110. this.morphNormals = false;
  21111. this.setValues(parameters);
  21112. }
  21113. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  21114. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  21115. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21116. MeshMatcapMaterial.prototype.copy = function (source) {
  21117. Material.prototype.copy.call(this, source);
  21118. this.defines = {
  21119. 'MATCAP': ''
  21120. };
  21121. this.color.copy(source.color);
  21122. this.matcap = source.matcap;
  21123. this.map = source.map;
  21124. this.bumpMap = source.bumpMap;
  21125. this.bumpScale = source.bumpScale;
  21126. this.normalMap = source.normalMap;
  21127. this.normalMapType = source.normalMapType;
  21128. this.normalScale.copy(source.normalScale);
  21129. this.displacementMap = source.displacementMap;
  21130. this.displacementScale = source.displacementScale;
  21131. this.displacementBias = source.displacementBias;
  21132. this.alphaMap = source.alphaMap;
  21133. this.skinning = source.skinning;
  21134. this.morphTargets = source.morphTargets;
  21135. this.morphNormals = source.morphNormals;
  21136. return this;
  21137. };
  21138. /**
  21139. * @author alteredq / http://alteredqualia.com/
  21140. *
  21141. * parameters = {
  21142. * color: <hex>,
  21143. * opacity: <float>,
  21144. *
  21145. * linewidth: <float>,
  21146. *
  21147. * scale: <float>,
  21148. * dashSize: <float>,
  21149. * gapSize: <float>
  21150. * }
  21151. */
  21152. function LineDashedMaterial(parameters) {
  21153. LineBasicMaterial.call(this);
  21154. this.type = 'LineDashedMaterial';
  21155. this.scale = 1;
  21156. this.dashSize = 3;
  21157. this.gapSize = 1;
  21158. this.setValues(parameters);
  21159. }
  21160. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  21161. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21162. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21163. LineDashedMaterial.prototype.copy = function (source) {
  21164. LineBasicMaterial.prototype.copy.call(this, source);
  21165. this.scale = source.scale;
  21166. this.dashSize = source.dashSize;
  21167. this.gapSize = source.gapSize;
  21168. return this;
  21169. };
  21170. var Materials =
  21171. /*#__PURE__*/
  21172. Object.freeze({
  21173. ShadowMaterial: ShadowMaterial,
  21174. SpriteMaterial: SpriteMaterial,
  21175. RawShaderMaterial: RawShaderMaterial,
  21176. ShaderMaterial: ShaderMaterial,
  21177. PointsMaterial: PointsMaterial,
  21178. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21179. MeshStandardMaterial: MeshStandardMaterial,
  21180. MeshPhongMaterial: MeshPhongMaterial,
  21181. MeshToonMaterial: MeshToonMaterial,
  21182. MeshNormalMaterial: MeshNormalMaterial,
  21183. MeshLambertMaterial: MeshLambertMaterial,
  21184. MeshDepthMaterial: MeshDepthMaterial,
  21185. MeshDistanceMaterial: MeshDistanceMaterial,
  21186. MeshBasicMaterial: MeshBasicMaterial,
  21187. MeshMatcapMaterial: MeshMatcapMaterial,
  21188. LineDashedMaterial: LineDashedMaterial,
  21189. LineBasicMaterial: LineBasicMaterial,
  21190. Material: Material
  21191. });
  21192. /**
  21193. * @author tschw
  21194. * @author Ben Houston / http://clara.io/
  21195. * @author David Sarno / http://lighthaus.us/
  21196. */
  21197. var AnimationUtils = {
  21198. // same as Array.prototype.slice, but also works on typed arrays
  21199. arraySlice: function (array, from, to) {
  21200. if (AnimationUtils.isTypedArray(array)) {
  21201. // in ios9 array.subarray(from, undefined) will return empty array
  21202. // but array.subarray(from) or array.subarray(from, len) is correct
  21203. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21204. }
  21205. return array.slice(from, to);
  21206. },
  21207. // converts an array to a specific type
  21208. convertArray: function (array, type, forceClone) {
  21209. if (!array || // let 'undefined' and 'null' pass
  21210. !forceClone && array.constructor === type) return array;
  21211. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21212. return new type(array); // create typed array
  21213. }
  21214. return Array.prototype.slice.call(array); // create Array
  21215. },
  21216. isTypedArray: function (object) {
  21217. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21218. },
  21219. // returns an array by which times and values can be sorted
  21220. getKeyframeOrder: function (times) {
  21221. function compareTime(i, j) {
  21222. return times[i] - times[j];
  21223. }
  21224. var n = times.length;
  21225. var result = new Array(n);
  21226. for (var i = 0; i !== n; ++i) result[i] = i;
  21227. result.sort(compareTime);
  21228. return result;
  21229. },
  21230. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21231. sortedArray: function (values, stride, order) {
  21232. var nValues = values.length;
  21233. var result = new values.constructor(nValues);
  21234. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21235. var srcOffset = order[i] * stride;
  21236. for (var j = 0; j !== stride; ++j) {
  21237. result[dstOffset++] = values[srcOffset + j];
  21238. }
  21239. }
  21240. return result;
  21241. },
  21242. // function for parsing AOS keyframe formats
  21243. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21244. var i = 1,
  21245. key = jsonKeys[0];
  21246. while (key !== undefined && key[valuePropertyName] === undefined) {
  21247. key = jsonKeys[i++];
  21248. }
  21249. if (key === undefined) return; // no data
  21250. var value = key[valuePropertyName];
  21251. if (value === undefined) return; // no data
  21252. if (Array.isArray(value)) {
  21253. do {
  21254. value = key[valuePropertyName];
  21255. if (value !== undefined) {
  21256. times.push(key.time);
  21257. values.push.apply(values, value); // push all elements
  21258. }
  21259. key = jsonKeys[i++];
  21260. } while (key !== undefined);
  21261. } else if (value.toArray !== undefined) {
  21262. // ...assume THREE.Math-ish
  21263. do {
  21264. value = key[valuePropertyName];
  21265. if (value !== undefined) {
  21266. times.push(key.time);
  21267. value.toArray(values, values.length);
  21268. }
  21269. key = jsonKeys[i++];
  21270. } while (key !== undefined);
  21271. } else {
  21272. // otherwise push as-is
  21273. do {
  21274. value = key[valuePropertyName];
  21275. if (value !== undefined) {
  21276. times.push(key.time);
  21277. values.push(value);
  21278. }
  21279. key = jsonKeys[i++];
  21280. } while (key !== undefined);
  21281. }
  21282. }
  21283. };
  21284. /**
  21285. * Abstract base class of interpolants over parametric samples.
  21286. *
  21287. * The parameter domain is one dimensional, typically the time or a path
  21288. * along a curve defined by the data.
  21289. *
  21290. * The sample values can have any dimensionality and derived classes may
  21291. * apply special interpretations to the data.
  21292. *
  21293. * This class provides the interval seek in a Template Method, deferring
  21294. * the actual interpolation to derived classes.
  21295. *
  21296. * Time complexity is O(1) for linear access crossing at most two points
  21297. * and O(log N) for random access, where N is the number of positions.
  21298. *
  21299. * References:
  21300. *
  21301. * http://www.oodesign.com/template-method-pattern.html
  21302. *
  21303. * @author tschw
  21304. */
  21305. exports.AnimationUtils = AnimationUtils;
  21306. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21307. this.parameterPositions = parameterPositions;
  21308. this._cachedIndex = 0;
  21309. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21310. this.sampleValues = sampleValues;
  21311. this.valueSize = sampleSize;
  21312. }
  21313. Object.assign(Interpolant.prototype, {
  21314. evaluate: function (t) {
  21315. var pp = this.parameterPositions,
  21316. i1 = this._cachedIndex,
  21317. t1 = pp[i1],
  21318. t0 = pp[i1 - 1];
  21319. validate_interval: {
  21320. seek: {
  21321. var right;
  21322. linear_scan: {
  21323. //- See http://jsperf.com/comparison-to-undefined/3
  21324. //- slower code:
  21325. //-
  21326. //- if ( t >= t1 || t1 === undefined ) {
  21327. forward_scan: if (!(t < t1)) {
  21328. for (var giveUpAt = i1 + 2;;) {
  21329. if (t1 === undefined) {
  21330. if (t < t0) break forward_scan; // after end
  21331. i1 = pp.length;
  21332. this._cachedIndex = i1;
  21333. return this.afterEnd_(i1 - 1, t, t0);
  21334. }
  21335. if (i1 === giveUpAt) break; // this loop
  21336. t0 = t1;
  21337. t1 = pp[++i1];
  21338. if (t < t1) {
  21339. // we have arrived at the sought interval
  21340. break seek;
  21341. }
  21342. } // prepare binary search on the right side of the index
  21343. right = pp.length;
  21344. break linear_scan;
  21345. } //- slower code:
  21346. //- if ( t < t0 || t0 === undefined ) {
  21347. if (!(t >= t0)) {
  21348. // looping?
  21349. var t1global = pp[1];
  21350. if (t < t1global) {
  21351. i1 = 2; // + 1, using the scan for the details
  21352. t0 = t1global;
  21353. } // linear reverse scan
  21354. for (var giveUpAt = i1 - 2;;) {
  21355. if (t0 === undefined) {
  21356. // before start
  21357. this._cachedIndex = 0;
  21358. return this.beforeStart_(0, t, t1);
  21359. }
  21360. if (i1 === giveUpAt) break; // this loop
  21361. t1 = t0;
  21362. t0 = pp[--i1 - 1];
  21363. if (t >= t0) {
  21364. // we have arrived at the sought interval
  21365. break seek;
  21366. }
  21367. } // prepare binary search on the left side of the index
  21368. right = i1;
  21369. i1 = 0;
  21370. break linear_scan;
  21371. } // the interval is valid
  21372. break validate_interval;
  21373. } // linear scan
  21374. // binary search
  21375. while (i1 < right) {
  21376. var mid = i1 + right >>> 1;
  21377. if (t < pp[mid]) {
  21378. right = mid;
  21379. } else {
  21380. i1 = mid + 1;
  21381. }
  21382. }
  21383. t1 = pp[i1];
  21384. t0 = pp[i1 - 1]; // check boundary cases, again
  21385. if (t0 === undefined) {
  21386. this._cachedIndex = 0;
  21387. return this.beforeStart_(0, t, t1);
  21388. }
  21389. if (t1 === undefined) {
  21390. i1 = pp.length;
  21391. this._cachedIndex = i1;
  21392. return this.afterEnd_(i1 - 1, t0, t);
  21393. }
  21394. } // seek
  21395. this._cachedIndex = i1;
  21396. this.intervalChanged_(i1, t0, t1);
  21397. } // validate_interval
  21398. return this.interpolate_(i1, t0, t, t1);
  21399. },
  21400. settings: null,
  21401. // optional, subclass-specific settings structure
  21402. // Note: The indirection allows central control of many interpolants.
  21403. // --- Protected interface
  21404. DefaultSettings_: {},
  21405. getSettings_: function () {
  21406. return this.settings || this.DefaultSettings_;
  21407. },
  21408. copySampleValue_: function (index) {
  21409. // copies a sample value to the result buffer
  21410. var result = this.resultBuffer,
  21411. values = this.sampleValues,
  21412. stride = this.valueSize,
  21413. offset = index * stride;
  21414. for (var i = 0; i !== stride; ++i) {
  21415. result[i] = values[offset + i];
  21416. }
  21417. return result;
  21418. },
  21419. // Template methods for derived classes:
  21420. interpolate_: function ()
  21421. /* i1, t0, t, t1 */
  21422. {
  21423. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21424. },
  21425. intervalChanged_: function ()
  21426. /* i1, t0, t1 */
  21427. {// empty
  21428. }
  21429. }); //!\ DECLARE ALIAS AFTER assign prototype !
  21430. Object.assign(Interpolant.prototype, {
  21431. //( 0, t, t0 ), returns this.resultBuffer
  21432. beforeStart_: Interpolant.prototype.copySampleValue_,
  21433. //( N-1, tN-1, t ), returns this.resultBuffer
  21434. afterEnd_: Interpolant.prototype.copySampleValue_
  21435. });
  21436. /**
  21437. * Fast and simple cubic spline interpolant.
  21438. *
  21439. * It was derived from a Hermitian construction setting the first derivative
  21440. * at each sample position to the linear slope between neighboring positions
  21441. * over their parameter interval.
  21442. *
  21443. * @author tschw
  21444. */
  21445. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21446. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21447. this._weightPrev = -0;
  21448. this._offsetPrev = -0;
  21449. this._weightNext = -0;
  21450. this._offsetNext = -0;
  21451. }
  21452. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21453. constructor: CubicInterpolant,
  21454. DefaultSettings_: {
  21455. endingStart: ZeroCurvatureEnding,
  21456. endingEnd: ZeroCurvatureEnding
  21457. },
  21458. intervalChanged_: function (i1, t0, t1) {
  21459. var pp = this.parameterPositions,
  21460. iPrev = i1 - 2,
  21461. iNext = i1 + 1,
  21462. tPrev = pp[iPrev],
  21463. tNext = pp[iNext];
  21464. if (tPrev === undefined) {
  21465. switch (this.getSettings_().endingStart) {
  21466. case ZeroSlopeEnding:
  21467. // f'(t0) = 0
  21468. iPrev = i1;
  21469. tPrev = 2 * t0 - t1;
  21470. break;
  21471. case WrapAroundEnding:
  21472. // use the other end of the curve
  21473. iPrev = pp.length - 2;
  21474. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21475. break;
  21476. default:
  21477. // ZeroCurvatureEnding
  21478. // f''(t0) = 0 a.k.a. Natural Spline
  21479. iPrev = i1;
  21480. tPrev = t1;
  21481. }
  21482. }
  21483. if (tNext === undefined) {
  21484. switch (this.getSettings_().endingEnd) {
  21485. case ZeroSlopeEnding:
  21486. // f'(tN) = 0
  21487. iNext = i1;
  21488. tNext = 2 * t1 - t0;
  21489. break;
  21490. case WrapAroundEnding:
  21491. // use the other end of the curve
  21492. iNext = 1;
  21493. tNext = t1 + pp[1] - pp[0];
  21494. break;
  21495. default:
  21496. // ZeroCurvatureEnding
  21497. // f''(tN) = 0, a.k.a. Natural Spline
  21498. iNext = i1 - 1;
  21499. tNext = t0;
  21500. }
  21501. }
  21502. var halfDt = (t1 - t0) * 0.5,
  21503. stride = this.valueSize;
  21504. this._weightPrev = halfDt / (t0 - tPrev);
  21505. this._weightNext = halfDt / (tNext - t1);
  21506. this._offsetPrev = iPrev * stride;
  21507. this._offsetNext = iNext * stride;
  21508. },
  21509. interpolate_: function (i1, t0, t, t1) {
  21510. var result = this.resultBuffer,
  21511. values = this.sampleValues,
  21512. stride = this.valueSize,
  21513. o1 = i1 * stride,
  21514. o0 = o1 - stride,
  21515. oP = this._offsetPrev,
  21516. oN = this._offsetNext,
  21517. wP = this._weightPrev,
  21518. wN = this._weightNext,
  21519. p = (t - t0) / (t1 - t0),
  21520. pp = p * p,
  21521. ppp = pp * p; // evaluate polynomials
  21522. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  21523. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21524. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21525. var sN = wN * ppp - wN * pp; // combine data linearly
  21526. for (var i = 0; i !== stride; ++i) {
  21527. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21528. }
  21529. return result;
  21530. }
  21531. });
  21532. /**
  21533. * @author tschw
  21534. */
  21535. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21536. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21537. }
  21538. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21539. constructor: LinearInterpolant,
  21540. interpolate_: function (i1, t0, t, t1) {
  21541. var result = this.resultBuffer,
  21542. values = this.sampleValues,
  21543. stride = this.valueSize,
  21544. offset1 = i1 * stride,
  21545. offset0 = offset1 - stride,
  21546. weight1 = (t - t0) / (t1 - t0),
  21547. weight0 = 1 - weight1;
  21548. for (var i = 0; i !== stride; ++i) {
  21549. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21550. }
  21551. return result;
  21552. }
  21553. });
  21554. /**
  21555. *
  21556. * Interpolant that evaluates to the sample value at the position preceeding
  21557. * the parameter.
  21558. *
  21559. * @author tschw
  21560. */
  21561. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21562. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21563. }
  21564. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21565. constructor: DiscreteInterpolant,
  21566. interpolate_: function (i1
  21567. /*, t0, t, t1 */
  21568. ) {
  21569. return this.copySampleValue_(i1 - 1);
  21570. }
  21571. });
  21572. /**
  21573. *
  21574. * A timed sequence of keyframes for a specific property.
  21575. *
  21576. *
  21577. * @author Ben Houston / http://clara.io/
  21578. * @author David Sarno / http://lighthaus.us/
  21579. * @author tschw
  21580. */
  21581. function KeyframeTrack(name, times, values, interpolation) {
  21582. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21583. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21584. this.name = name;
  21585. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21586. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21587. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21588. } // Static methods
  21589. Object.assign(KeyframeTrack, {
  21590. // Serialization (in static context, because of constructor invocation
  21591. // and automatic invocation of .toJSON):
  21592. toJSON: function (track) {
  21593. var trackType = track.constructor;
  21594. var json; // derived classes can define a static toJSON method
  21595. if (trackType.toJSON !== undefined) {
  21596. json = trackType.toJSON(track);
  21597. } else {
  21598. // by default, we assume the data can be serialized as-is
  21599. json = {
  21600. 'name': track.name,
  21601. 'times': AnimationUtils.convertArray(track.times, Array),
  21602. 'values': AnimationUtils.convertArray(track.values, Array)
  21603. };
  21604. var interpolation = track.getInterpolation();
  21605. if (interpolation !== track.DefaultInterpolation) {
  21606. json.interpolation = interpolation;
  21607. }
  21608. }
  21609. json.type = track.ValueTypeName; // mandatory
  21610. return json;
  21611. }
  21612. });
  21613. Object.assign(KeyframeTrack.prototype, {
  21614. constructor: KeyframeTrack,
  21615. TimeBufferType: Float32Array,
  21616. ValueBufferType: Float32Array,
  21617. DefaultInterpolation: InterpolateLinear,
  21618. InterpolantFactoryMethodDiscrete: function (result) {
  21619. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21620. },
  21621. InterpolantFactoryMethodLinear: function (result) {
  21622. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21623. },
  21624. InterpolantFactoryMethodSmooth: function (result) {
  21625. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21626. },
  21627. setInterpolation: function (interpolation) {
  21628. var factoryMethod;
  21629. switch (interpolation) {
  21630. case InterpolateDiscrete:
  21631. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21632. break;
  21633. case InterpolateLinear:
  21634. factoryMethod = this.InterpolantFactoryMethodLinear;
  21635. break;
  21636. case InterpolateSmooth:
  21637. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21638. break;
  21639. }
  21640. if (factoryMethod === undefined) {
  21641. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  21642. if (this.createInterpolant === undefined) {
  21643. // fall back to default, unless the default itself is messed up
  21644. if (interpolation !== this.DefaultInterpolation) {
  21645. this.setInterpolation(this.DefaultInterpolation);
  21646. } else {
  21647. throw new Error(message); // fatal, in this case
  21648. }
  21649. }
  21650. console.warn('THREE.KeyframeTrack:', message);
  21651. return this;
  21652. }
  21653. this.createInterpolant = factoryMethod;
  21654. return this;
  21655. },
  21656. getInterpolation: function () {
  21657. switch (this.createInterpolant) {
  21658. case this.InterpolantFactoryMethodDiscrete:
  21659. return InterpolateDiscrete;
  21660. case this.InterpolantFactoryMethodLinear:
  21661. return InterpolateLinear;
  21662. case this.InterpolantFactoryMethodSmooth:
  21663. return InterpolateSmooth;
  21664. }
  21665. },
  21666. getValueSize: function () {
  21667. return this.values.length / this.times.length;
  21668. },
  21669. // move all keyframes either forwards or backwards in time
  21670. shift: function (timeOffset) {
  21671. if (timeOffset !== 0.0) {
  21672. var times = this.times;
  21673. for (var i = 0, n = times.length; i !== n; ++i) {
  21674. times[i] += timeOffset;
  21675. }
  21676. }
  21677. return this;
  21678. },
  21679. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21680. scale: function (timeScale) {
  21681. if (timeScale !== 1.0) {
  21682. var times = this.times;
  21683. for (var i = 0, n = times.length; i !== n; ++i) {
  21684. times[i] *= timeScale;
  21685. }
  21686. }
  21687. return this;
  21688. },
  21689. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21690. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21691. trim: function (startTime, endTime) {
  21692. var times = this.times,
  21693. nKeys = times.length,
  21694. from = 0,
  21695. to = nKeys - 1;
  21696. while (from !== nKeys && times[from] < startTime) {
  21697. ++from;
  21698. }
  21699. while (to !== -1 && times[to] > endTime) {
  21700. --to;
  21701. }
  21702. ++to; // inclusive -> exclusive bound
  21703. if (from !== 0 || to !== nKeys) {
  21704. // empty tracks are forbidden, so keep at least one keyframe
  21705. if (from >= to) to = Math.max(to, 1), from = to - 1;
  21706. var stride = this.getValueSize();
  21707. this.times = AnimationUtils.arraySlice(times, from, to);
  21708. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21709. }
  21710. return this;
  21711. },
  21712. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21713. validate: function () {
  21714. var valid = true;
  21715. var valueSize = this.getValueSize();
  21716. if (valueSize - Math.floor(valueSize) !== 0) {
  21717. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21718. valid = false;
  21719. }
  21720. var times = this.times,
  21721. values = this.values,
  21722. nKeys = times.length;
  21723. if (nKeys === 0) {
  21724. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21725. valid = false;
  21726. }
  21727. var prevTime = null;
  21728. for (var i = 0; i !== nKeys; i++) {
  21729. var currTime = times[i];
  21730. if (typeof currTime === 'number' && isNaN(currTime)) {
  21731. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21732. valid = false;
  21733. break;
  21734. }
  21735. if (prevTime !== null && prevTime > currTime) {
  21736. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21737. valid = false;
  21738. break;
  21739. }
  21740. prevTime = currTime;
  21741. }
  21742. if (values !== undefined) {
  21743. if (AnimationUtils.isTypedArray(values)) {
  21744. for (var i = 0, n = values.length; i !== n; ++i) {
  21745. var value = values[i];
  21746. if (isNaN(value)) {
  21747. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21748. valid = false;
  21749. break;
  21750. }
  21751. }
  21752. }
  21753. }
  21754. return valid;
  21755. },
  21756. // removes equivalent sequential keys as common in morph target sequences
  21757. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21758. optimize: function () {
  21759. var times = this.times,
  21760. values = this.values,
  21761. stride = this.getValueSize(),
  21762. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21763. writeIndex = 1,
  21764. lastIndex = times.length - 1;
  21765. for (var i = 1; i < lastIndex; ++i) {
  21766. var keep = false;
  21767. var time = times[i];
  21768. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21769. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21770. if (!smoothInterpolation) {
  21771. // remove unnecessary keyframes same as their neighbors
  21772. var offset = i * stride,
  21773. offsetP = offset - stride,
  21774. offsetN = offset + stride;
  21775. for (var j = 0; j !== stride; ++j) {
  21776. var value = values[offset + j];
  21777. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21778. keep = true;
  21779. break;
  21780. }
  21781. }
  21782. } else {
  21783. keep = true;
  21784. }
  21785. } // in-place compaction
  21786. if (keep) {
  21787. if (i !== writeIndex) {
  21788. times[writeIndex] = times[i];
  21789. var readOffset = i * stride,
  21790. writeOffset = writeIndex * stride;
  21791. for (var j = 0; j !== stride; ++j) {
  21792. values[writeOffset + j] = values[readOffset + j];
  21793. }
  21794. }
  21795. ++writeIndex;
  21796. }
  21797. } // flush last keyframe (compaction looks ahead)
  21798. if (lastIndex > 0) {
  21799. times[writeIndex] = times[lastIndex];
  21800. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21801. values[writeOffset + j] = values[readOffset + j];
  21802. }
  21803. ++writeIndex;
  21804. }
  21805. if (writeIndex !== times.length) {
  21806. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21807. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21808. }
  21809. return this;
  21810. },
  21811. clone: function () {
  21812. var times = AnimationUtils.arraySlice(this.times, 0);
  21813. var values = AnimationUtils.arraySlice(this.values, 0);
  21814. var TypedKeyframeTrack = this.constructor;
  21815. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21816. track.createInterpolant = this.createInterpolant;
  21817. return track;
  21818. }
  21819. });
  21820. /**
  21821. *
  21822. * A Track of Boolean keyframe values.
  21823. *
  21824. *
  21825. * @author Ben Houston / http://clara.io/
  21826. * @author David Sarno / http://lighthaus.us/
  21827. * @author tschw
  21828. */
  21829. function BooleanKeyframeTrack(name, times, values) {
  21830. KeyframeTrack.call(this, name, times, values);
  21831. }
  21832. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21833. constructor: BooleanKeyframeTrack,
  21834. ValueTypeName: 'bool',
  21835. ValueBufferType: Array,
  21836. DefaultInterpolation: InterpolateDiscrete,
  21837. InterpolantFactoryMethodLinear: undefined,
  21838. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21839. // representation of a single value and a custom interpolant that
  21840. // computes "firstValue ^ isOdd( index )".
  21841. });
  21842. /**
  21843. *
  21844. * A Track of keyframe values that represent color.
  21845. *
  21846. *
  21847. * @author Ben Houston / http://clara.io/
  21848. * @author David Sarno / http://lighthaus.us/
  21849. * @author tschw
  21850. */
  21851. function ColorKeyframeTrack(name, times, values, interpolation) {
  21852. KeyframeTrack.call(this, name, times, values, interpolation);
  21853. }
  21854. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21855. constructor: ColorKeyframeTrack,
  21856. ValueTypeName: 'color' // ValueBufferType is inherited
  21857. // DefaultInterpolation is inherited
  21858. // Note: Very basic implementation and nothing special yet.
  21859. // However, this is the place for color space parameterization.
  21860. });
  21861. /**
  21862. *
  21863. * A Track of numeric keyframe values.
  21864. *
  21865. * @author Ben Houston / http://clara.io/
  21866. * @author David Sarno / http://lighthaus.us/
  21867. * @author tschw
  21868. */
  21869. function NumberKeyframeTrack(name, times, values, interpolation) {
  21870. KeyframeTrack.call(this, name, times, values, interpolation);
  21871. }
  21872. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21873. constructor: NumberKeyframeTrack,
  21874. ValueTypeName: 'number' // ValueBufferType is inherited
  21875. // DefaultInterpolation is inherited
  21876. });
  21877. /**
  21878. * Spherical linear unit quaternion interpolant.
  21879. *
  21880. * @author tschw
  21881. */
  21882. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21883. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21884. }
  21885. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21886. constructor: QuaternionLinearInterpolant,
  21887. interpolate_: function (i1, t0, t, t1) {
  21888. var result = this.resultBuffer,
  21889. values = this.sampleValues,
  21890. stride = this.valueSize,
  21891. offset = i1 * stride,
  21892. alpha = (t - t0) / (t1 - t0);
  21893. for (var end = offset + stride; offset !== end; offset += 4) {
  21894. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21895. }
  21896. return result;
  21897. }
  21898. });
  21899. /**
  21900. *
  21901. * A Track of quaternion keyframe values.
  21902. *
  21903. * @author Ben Houston / http://clara.io/
  21904. * @author David Sarno / http://lighthaus.us/
  21905. * @author tschw
  21906. */
  21907. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21908. KeyframeTrack.call(this, name, times, values, interpolation);
  21909. }
  21910. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21911. constructor: QuaternionKeyframeTrack,
  21912. ValueTypeName: 'quaternion',
  21913. // ValueBufferType is inherited
  21914. DefaultInterpolation: InterpolateLinear,
  21915. InterpolantFactoryMethodLinear: function (result) {
  21916. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21917. },
  21918. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21919. });
  21920. /**
  21921. *
  21922. * A Track that interpolates Strings
  21923. *
  21924. *
  21925. * @author Ben Houston / http://clara.io/
  21926. * @author David Sarno / http://lighthaus.us/
  21927. * @author tschw
  21928. */
  21929. function StringKeyframeTrack(name, times, values, interpolation) {
  21930. KeyframeTrack.call(this, name, times, values, interpolation);
  21931. }
  21932. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21933. constructor: StringKeyframeTrack,
  21934. ValueTypeName: 'string',
  21935. ValueBufferType: Array,
  21936. DefaultInterpolation: InterpolateDiscrete,
  21937. InterpolantFactoryMethodLinear: undefined,
  21938. InterpolantFactoryMethodSmooth: undefined
  21939. });
  21940. /**
  21941. *
  21942. * A Track of vectored keyframe values.
  21943. *
  21944. *
  21945. * @author Ben Houston / http://clara.io/
  21946. * @author David Sarno / http://lighthaus.us/
  21947. * @author tschw
  21948. */
  21949. function VectorKeyframeTrack(name, times, values, interpolation) {
  21950. KeyframeTrack.call(this, name, times, values, interpolation);
  21951. }
  21952. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21953. constructor: VectorKeyframeTrack,
  21954. ValueTypeName: 'vector' // ValueBufferType is inherited
  21955. // DefaultInterpolation is inherited
  21956. });
  21957. /**
  21958. *
  21959. * Reusable set of Tracks that represent an animation.
  21960. *
  21961. * @author Ben Houston / http://clara.io/
  21962. * @author David Sarno / http://lighthaus.us/
  21963. */
  21964. function AnimationClip(name, duration, tracks) {
  21965. this.name = name;
  21966. this.tracks = tracks;
  21967. this.duration = duration !== undefined ? duration : -1;
  21968. this.uuid = _Math.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21969. if (this.duration < 0) {
  21970. this.resetDuration();
  21971. }
  21972. }
  21973. function getTrackTypeForValueTypeName(typeName) {
  21974. switch (typeName.toLowerCase()) {
  21975. case 'scalar':
  21976. case 'double':
  21977. case 'float':
  21978. case 'number':
  21979. case 'integer':
  21980. return NumberKeyframeTrack;
  21981. case 'vector':
  21982. case 'vector2':
  21983. case 'vector3':
  21984. case 'vector4':
  21985. return VectorKeyframeTrack;
  21986. case 'color':
  21987. return ColorKeyframeTrack;
  21988. case 'quaternion':
  21989. return QuaternionKeyframeTrack;
  21990. case 'bool':
  21991. case 'boolean':
  21992. return BooleanKeyframeTrack;
  21993. case 'string':
  21994. return StringKeyframeTrack;
  21995. }
  21996. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21997. }
  21998. function parseKeyframeTrack(json) {
  21999. if (json.type === undefined) {
  22000. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22001. }
  22002. var trackType = getTrackTypeForValueTypeName(json.type);
  22003. if (json.times === undefined) {
  22004. var times = [],
  22005. values = [];
  22006. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22007. json.times = times;
  22008. json.values = values;
  22009. } // derived classes can define a static parse method
  22010. if (trackType.parse !== undefined) {
  22011. return trackType.parse(json);
  22012. } else {
  22013. // by default, we assume a constructor compatible with the base
  22014. return new trackType(json.name, json.times, json.values, json.interpolation);
  22015. }
  22016. }
  22017. Object.assign(AnimationClip, {
  22018. parse: function (json) {
  22019. var tracks = [],
  22020. jsonTracks = json.tracks,
  22021. frameTime = 1.0 / (json.fps || 1.0);
  22022. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  22023. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22024. }
  22025. return new AnimationClip(json.name, json.duration, tracks);
  22026. },
  22027. toJSON: function (clip) {
  22028. var tracks = [],
  22029. clipTracks = clip.tracks;
  22030. var json = {
  22031. 'name': clip.name,
  22032. 'duration': clip.duration,
  22033. 'tracks': tracks,
  22034. 'uuid': clip.uuid
  22035. };
  22036. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  22037. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22038. }
  22039. return json;
  22040. },
  22041. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  22042. var numMorphTargets = morphTargetSequence.length;
  22043. var tracks = [];
  22044. for (var i = 0; i < numMorphTargets; i++) {
  22045. var times = [];
  22046. var values = [];
  22047. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22048. values.push(0, 1, 0);
  22049. var order = AnimationUtils.getKeyframeOrder(times);
  22050. times = AnimationUtils.sortedArray(times, 1, order);
  22051. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22052. // last frame as well for perfect loop.
  22053. if (!noLoop && times[0] === 0) {
  22054. times.push(numMorphTargets);
  22055. values.push(values[0]);
  22056. }
  22057. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22058. }
  22059. return new AnimationClip(name, -1, tracks);
  22060. },
  22061. findByName: function (objectOrClipArray, name) {
  22062. var clipArray = objectOrClipArray;
  22063. if (!Array.isArray(objectOrClipArray)) {
  22064. var o = objectOrClipArray;
  22065. clipArray = o.geometry && o.geometry.animations || o.animations;
  22066. }
  22067. for (var i = 0; i < clipArray.length; i++) {
  22068. if (clipArray[i].name === name) {
  22069. return clipArray[i];
  22070. }
  22071. }
  22072. return null;
  22073. },
  22074. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  22075. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22076. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22077. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22078. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22079. for (var i = 0, il = morphTargets.length; i < il; i++) {
  22080. var morphTarget = morphTargets[i];
  22081. var parts = morphTarget.name.match(pattern);
  22082. if (parts && parts.length > 1) {
  22083. var name = parts[1];
  22084. var animationMorphTargets = animationToMorphTargets[name];
  22085. if (!animationMorphTargets) {
  22086. animationToMorphTargets[name] = animationMorphTargets = [];
  22087. }
  22088. animationMorphTargets.push(morphTarget);
  22089. }
  22090. }
  22091. var clips = [];
  22092. for (var name in animationToMorphTargets) {
  22093. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22094. }
  22095. return clips;
  22096. },
  22097. // parse the animation.hierarchy format
  22098. parseAnimation: function (animation, bones) {
  22099. if (!animation) {
  22100. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22101. return null;
  22102. }
  22103. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22104. // only return track if there are actually keys.
  22105. if (animationKeys.length !== 0) {
  22106. var times = [];
  22107. var values = [];
  22108. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22109. if (times.length !== 0) {
  22110. destTracks.push(new trackType(trackName, times, values));
  22111. }
  22112. }
  22113. };
  22114. var tracks = [];
  22115. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  22116. var duration = animation.length || -1;
  22117. var fps = animation.fps || 30;
  22118. var hierarchyTracks = animation.hierarchy || [];
  22119. for (var h = 0; h < hierarchyTracks.length; h++) {
  22120. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22121. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22122. if (animationKeys[0].morphTargets) {
  22123. // figure out all morph targets used in this track
  22124. var morphTargetNames = {};
  22125. for (var k = 0; k < animationKeys.length; k++) {
  22126. if (animationKeys[k].morphTargets) {
  22127. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22128. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22129. }
  22130. }
  22131. } // create a track for each morph target with all zero
  22132. // morphTargetInfluences except for the keys in which
  22133. // the morphTarget is named.
  22134. for (var morphTargetName in morphTargetNames) {
  22135. var times = [];
  22136. var values = [];
  22137. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22138. var animationKey = animationKeys[k];
  22139. times.push(animationKey.time);
  22140. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22141. }
  22142. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22143. }
  22144. duration = morphTargetNames.length * (fps || 1.0);
  22145. } else {
  22146. // ...assume skeletal animation
  22147. var boneName = '.bones[' + bones[h].name + ']';
  22148. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22149. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22150. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22151. }
  22152. }
  22153. if (tracks.length === 0) {
  22154. return null;
  22155. }
  22156. var clip = new AnimationClip(clipName, duration, tracks);
  22157. return clip;
  22158. }
  22159. });
  22160. Object.assign(AnimationClip.prototype, {
  22161. resetDuration: function () {
  22162. var tracks = this.tracks,
  22163. duration = 0;
  22164. for (var i = 0, n = tracks.length; i !== n; ++i) {
  22165. var track = this.tracks[i];
  22166. duration = Math.max(duration, track.times[track.times.length - 1]);
  22167. }
  22168. this.duration = duration;
  22169. return this;
  22170. },
  22171. trim: function () {
  22172. for (var i = 0; i < this.tracks.length; i++) {
  22173. this.tracks[i].trim(0, this.duration);
  22174. }
  22175. return this;
  22176. },
  22177. validate: function () {
  22178. var valid = true;
  22179. for (var i = 0; i < this.tracks.length; i++) {
  22180. valid = valid && this.tracks[i].validate();
  22181. }
  22182. return valid;
  22183. },
  22184. optimize: function () {
  22185. for (var i = 0; i < this.tracks.length; i++) {
  22186. this.tracks[i].optimize();
  22187. }
  22188. return this;
  22189. },
  22190. clone: function () {
  22191. var tracks = [];
  22192. for (var i = 0; i < this.tracks.length; i++) {
  22193. tracks.push(this.tracks[i].clone());
  22194. }
  22195. return new AnimationClip(this.name, this.duration, tracks);
  22196. }
  22197. });
  22198. /**
  22199. * @author mrdoob / http://mrdoob.com/
  22200. */
  22201. var Cache = {
  22202. enabled: false,
  22203. files: {},
  22204. add: function (key, file) {
  22205. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22206. this.files[key] = file;
  22207. },
  22208. get: function (key) {
  22209. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22210. return this.files[key];
  22211. },
  22212. remove: function (key) {
  22213. delete this.files[key];
  22214. },
  22215. clear: function () {
  22216. this.files = {};
  22217. }
  22218. };
  22219. /**
  22220. * @author mrdoob / http://mrdoob.com/
  22221. */
  22222. exports.Cache = Cache;
  22223. function LoadingManager(onLoad, onProgress, onError) {
  22224. var scope = this;
  22225. var isLoading = false;
  22226. var itemsLoaded = 0;
  22227. var itemsTotal = 0;
  22228. var urlModifier = undefined;
  22229. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22230. // in the constructor
  22231. this.onStart = undefined;
  22232. this.onLoad = onLoad;
  22233. this.onProgress = onProgress;
  22234. this.onError = onError;
  22235. this.itemStart = function (url) {
  22236. itemsTotal++;
  22237. if (isLoading === false) {
  22238. if (scope.onStart !== undefined) {
  22239. scope.onStart(url, itemsLoaded, itemsTotal);
  22240. }
  22241. }
  22242. isLoading = true;
  22243. };
  22244. this.itemEnd = function (url) {
  22245. itemsLoaded++;
  22246. if (scope.onProgress !== undefined) {
  22247. scope.onProgress(url, itemsLoaded, itemsTotal);
  22248. }
  22249. if (itemsLoaded === itemsTotal) {
  22250. isLoading = false;
  22251. if (scope.onLoad !== undefined) {
  22252. scope.onLoad();
  22253. }
  22254. }
  22255. };
  22256. this.itemError = function (url) {
  22257. if (scope.onError !== undefined) {
  22258. scope.onError(url);
  22259. }
  22260. };
  22261. this.resolveURL = function (url) {
  22262. if (urlModifier) {
  22263. return urlModifier(url);
  22264. }
  22265. return url;
  22266. };
  22267. this.setURLModifier = function (transform) {
  22268. urlModifier = transform;
  22269. return this;
  22270. };
  22271. this.addHandler = function (regex, loader) {
  22272. handlers.push(regex, loader);
  22273. return this;
  22274. };
  22275. this.removeHandler = function (regex) {
  22276. var index = handlers.indexOf(regex);
  22277. if (index !== -1) {
  22278. handlers.splice(index, 2);
  22279. }
  22280. return this;
  22281. };
  22282. this.getHandler = function (file) {
  22283. for (var i = 0, l = handlers.length; i < l; i += 2) {
  22284. var regex = handlers[i];
  22285. var loader = handlers[i + 1];
  22286. if (regex.test(file)) {
  22287. return loader;
  22288. }
  22289. }
  22290. return null;
  22291. };
  22292. }
  22293. var DefaultLoadingManager = new LoadingManager();
  22294. /**
  22295. * @author alteredq / http://alteredqualia.com/
  22296. */
  22297. exports.DefaultLoadingManager = DefaultLoadingManager;
  22298. function Loader(manager) {
  22299. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22300. this.crossOrigin = 'anonymous';
  22301. this.path = '';
  22302. this.resourcePath = '';
  22303. }
  22304. Object.assign(Loader.prototype, {
  22305. load: function ()
  22306. /* url, onLoad, onProgress, onError */
  22307. {},
  22308. parse: function ()
  22309. /* data */
  22310. {},
  22311. setCrossOrigin: function (crossOrigin) {
  22312. this.crossOrigin = crossOrigin;
  22313. return this;
  22314. },
  22315. setPath: function (path) {
  22316. this.path = path;
  22317. return this;
  22318. },
  22319. setResourcePath: function (resourcePath) {
  22320. this.resourcePath = resourcePath;
  22321. return this;
  22322. }
  22323. });
  22324. /**
  22325. * @author mrdoob / http://mrdoob.com/
  22326. */
  22327. var loading = {};
  22328. function FileLoader(manager) {
  22329. Loader.call(this, manager);
  22330. }
  22331. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22332. constructor: FileLoader,
  22333. load: function (url, onLoad, onProgress, onError) {
  22334. if (url === undefined) url = '';
  22335. if (this.path !== undefined) url = this.path + url;
  22336. url = this.manager.resolveURL(url);
  22337. var scope = this;
  22338. var cached = Cache.get(url);
  22339. if (cached !== undefined) {
  22340. scope.manager.itemStart(url);
  22341. setTimeout(function () {
  22342. if (onLoad) onLoad(cached);
  22343. scope.manager.itemEnd(url);
  22344. }, 0);
  22345. return cached;
  22346. } // Check if request is duplicate
  22347. if (loading[url] !== undefined) {
  22348. loading[url].push({
  22349. onLoad: onLoad,
  22350. onProgress: onProgress,
  22351. onError: onError
  22352. });
  22353. return;
  22354. } // Check for data: URI
  22355. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22356. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22357. if (dataUriRegexResult) {
  22358. var mimeType = dataUriRegexResult[1];
  22359. var isBase64 = !!dataUriRegexResult[2];
  22360. var data = dataUriRegexResult[3];
  22361. data = decodeURIComponent(data);
  22362. if (isBase64) data = atob(data);
  22363. try {
  22364. var response;
  22365. var responseType = (this.responseType || '').toLowerCase();
  22366. switch (responseType) {
  22367. case 'arraybuffer':
  22368. case 'blob':
  22369. var view = new Uint8Array(data.length);
  22370. for (var i = 0; i < data.length; i++) {
  22371. view[i] = data.charCodeAt(i);
  22372. }
  22373. if (responseType === 'blob') {
  22374. response = new Blob([view.buffer], {
  22375. type: mimeType
  22376. });
  22377. } else {
  22378. response = view.buffer;
  22379. }
  22380. break;
  22381. case 'document':
  22382. var parser = new DOMParser();
  22383. response = parser.parseFromString(data, mimeType);
  22384. break;
  22385. case 'json':
  22386. response = JSON.parse(data);
  22387. break;
  22388. default:
  22389. // 'text' or other
  22390. response = data;
  22391. break;
  22392. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22393. setTimeout(function () {
  22394. if (onLoad) onLoad(response);
  22395. scope.manager.itemEnd(url);
  22396. }, 0);
  22397. } catch (error) {
  22398. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22399. setTimeout(function () {
  22400. if (onError) onError(error);
  22401. scope.manager.itemError(url);
  22402. scope.manager.itemEnd(url);
  22403. }, 0);
  22404. }
  22405. } else {
  22406. // Initialise array for duplicate requests
  22407. loading[url] = [];
  22408. loading[url].push({
  22409. onLoad: onLoad,
  22410. onProgress: onProgress,
  22411. onError: onError
  22412. });
  22413. var request = new XMLHttpRequest();
  22414. request.open('GET', url, true);
  22415. request.addEventListener('load', function (event) {
  22416. var response = this.response;
  22417. Cache.add(url, response);
  22418. var callbacks = loading[url];
  22419. delete loading[url];
  22420. if (this.status === 200 || this.status === 0) {
  22421. // Some browsers return HTTP Status 0 when using non-http protocol
  22422. // e.g. 'file://' or 'data://'. Handle as success.
  22423. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.');
  22424. for (var i = 0, il = callbacks.length; i < il; i++) {
  22425. var callback = callbacks[i];
  22426. if (callback.onLoad) callback.onLoad(response);
  22427. }
  22428. scope.manager.itemEnd(url);
  22429. } else {
  22430. for (var i = 0, il = callbacks.length; i < il; i++) {
  22431. var callback = callbacks[i];
  22432. if (callback.onError) callback.onError(event);
  22433. }
  22434. scope.manager.itemError(url);
  22435. scope.manager.itemEnd(url);
  22436. }
  22437. }, false);
  22438. request.addEventListener('progress', function (event) {
  22439. var callbacks = loading[url];
  22440. for (var i = 0, il = callbacks.length; i < il; i++) {
  22441. var callback = callbacks[i];
  22442. if (callback.onProgress) callback.onProgress(event);
  22443. }
  22444. }, false);
  22445. request.addEventListener('error', function (event) {
  22446. var callbacks = loading[url];
  22447. delete loading[url];
  22448. for (var i = 0, il = callbacks.length; i < il; i++) {
  22449. var callback = callbacks[i];
  22450. if (callback.onError) callback.onError(event);
  22451. }
  22452. scope.manager.itemError(url);
  22453. scope.manager.itemEnd(url);
  22454. }, false);
  22455. request.addEventListener('abort', function (event) {
  22456. var callbacks = loading[url];
  22457. delete loading[url];
  22458. for (var i = 0, il = callbacks.length; i < il; i++) {
  22459. var callback = callbacks[i];
  22460. if (callback.onError) callback.onError(event);
  22461. }
  22462. scope.manager.itemError(url);
  22463. scope.manager.itemEnd(url);
  22464. }, false);
  22465. if (this.responseType !== undefined) request.responseType = this.responseType;
  22466. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22467. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22468. for (var header in this.requestHeader) {
  22469. request.setRequestHeader(header, this.requestHeader[header]);
  22470. }
  22471. request.send(null);
  22472. }
  22473. scope.manager.itemStart(url);
  22474. return request;
  22475. },
  22476. setResponseType: function (value) {
  22477. this.responseType = value;
  22478. return this;
  22479. },
  22480. setWithCredentials: function (value) {
  22481. this.withCredentials = value;
  22482. return this;
  22483. },
  22484. setMimeType: function (value) {
  22485. this.mimeType = value;
  22486. return this;
  22487. },
  22488. setRequestHeader: function (value) {
  22489. this.requestHeader = value;
  22490. return this;
  22491. }
  22492. });
  22493. /**
  22494. * @author bhouston / http://clara.io/
  22495. */
  22496. function AnimationLoader(manager) {
  22497. Loader.call(this, manager);
  22498. }
  22499. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22500. constructor: AnimationLoader,
  22501. load: function (url, onLoad, onProgress, onError) {
  22502. var scope = this;
  22503. var loader = new FileLoader(scope.manager);
  22504. loader.setPath(scope.path);
  22505. loader.load(url, function (text) {
  22506. onLoad(scope.parse(JSON.parse(text)));
  22507. }, onProgress, onError);
  22508. },
  22509. parse: function (json) {
  22510. var animations = [];
  22511. for (var i = 0; i < json.length; i++) {
  22512. var clip = AnimationClip.parse(json[i]);
  22513. animations.push(clip);
  22514. }
  22515. return animations;
  22516. }
  22517. });
  22518. /**
  22519. * @author mrdoob / http://mrdoob.com/
  22520. *
  22521. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22522. *
  22523. * Sub classes have to implement the parse() method which will be used in load().
  22524. */
  22525. function CompressedTextureLoader(manager) {
  22526. Loader.call(this, manager);
  22527. }
  22528. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22529. constructor: CompressedTextureLoader,
  22530. load: function (url, onLoad, onProgress, onError) {
  22531. var scope = this;
  22532. var images = [];
  22533. var texture = new CompressedTexture();
  22534. texture.image = images;
  22535. var loader = new FileLoader(this.manager);
  22536. loader.setPath(this.path);
  22537. loader.setResponseType('arraybuffer');
  22538. function loadTexture(i) {
  22539. loader.load(url[i], function (buffer) {
  22540. var texDatas = scope.parse(buffer, true);
  22541. images[i] = {
  22542. width: texDatas.width,
  22543. height: texDatas.height,
  22544. format: texDatas.format,
  22545. mipmaps: texDatas.mipmaps
  22546. };
  22547. loaded += 1;
  22548. if (loaded === 6) {
  22549. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22550. texture.format = texDatas.format;
  22551. texture.needsUpdate = true;
  22552. if (onLoad) onLoad(texture);
  22553. }
  22554. }, onProgress, onError);
  22555. }
  22556. if (Array.isArray(url)) {
  22557. var loaded = 0;
  22558. for (var i = 0, il = url.length; i < il; ++i) {
  22559. loadTexture(i);
  22560. }
  22561. } else {
  22562. // compressed cubemap texture stored in a single DDS file
  22563. loader.load(url, function (buffer) {
  22564. var texDatas = scope.parse(buffer, true);
  22565. if (texDatas.isCubemap) {
  22566. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22567. for (var f = 0; f < faces; f++) {
  22568. images[f] = {
  22569. mipmaps: []
  22570. };
  22571. for (var i = 0; i < texDatas.mipmapCount; i++) {
  22572. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22573. images[f].format = texDatas.format;
  22574. images[f].width = texDatas.width;
  22575. images[f].height = texDatas.height;
  22576. }
  22577. }
  22578. } else {
  22579. texture.image.width = texDatas.width;
  22580. texture.image.height = texDatas.height;
  22581. texture.mipmaps = texDatas.mipmaps;
  22582. }
  22583. if (texDatas.mipmapCount === 1) {
  22584. texture.minFilter = LinearFilter;
  22585. }
  22586. texture.format = texDatas.format;
  22587. texture.needsUpdate = true;
  22588. if (onLoad) onLoad(texture);
  22589. }, onProgress, onError);
  22590. }
  22591. return texture;
  22592. }
  22593. });
  22594. /**
  22595. * @author Nikos M. / https://github.com/foo123/
  22596. *
  22597. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22598. *
  22599. * Sub classes have to implement the parse() method which will be used in load().
  22600. */
  22601. function DataTextureLoader(manager) {
  22602. Loader.call(this, manager);
  22603. }
  22604. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22605. constructor: DataTextureLoader,
  22606. load: function (url, onLoad, onProgress, onError) {
  22607. var scope = this;
  22608. var texture = new DataTexture();
  22609. var loader = new FileLoader(this.manager);
  22610. loader.setResponseType('arraybuffer');
  22611. loader.setPath(this.path);
  22612. loader.load(url, function (buffer) {
  22613. var texData = scope.parse(buffer);
  22614. if (!texData) return;
  22615. if (texData.image !== undefined) {
  22616. texture.image = texData.image;
  22617. } else if (texData.data !== undefined) {
  22618. texture.image.width = texData.width;
  22619. texture.image.height = texData.height;
  22620. texture.image.data = texData.data;
  22621. }
  22622. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22623. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22624. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22625. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipmapLinearFilter;
  22626. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22627. if (texData.format !== undefined) {
  22628. texture.format = texData.format;
  22629. }
  22630. if (texData.type !== undefined) {
  22631. texture.type = texData.type;
  22632. }
  22633. if (texData.mipmaps !== undefined) {
  22634. texture.mipmaps = texData.mipmaps;
  22635. }
  22636. if (texData.mipmapCount === 1) {
  22637. texture.minFilter = LinearFilter;
  22638. }
  22639. texture.needsUpdate = true;
  22640. if (onLoad) onLoad(texture, texData);
  22641. }, onProgress, onError);
  22642. return texture;
  22643. }
  22644. });
  22645. /**
  22646. * @author mrdoob / http://mrdoob.com/
  22647. */
  22648. function ImageLoader(manager) {
  22649. Loader.call(this, manager);
  22650. }
  22651. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22652. constructor: ImageLoader,
  22653. load: function (url, onLoad, onProgress, onError) {
  22654. if (this.path !== undefined) url = this.path + url;
  22655. url = this.manager.resolveURL(url);
  22656. var scope = this;
  22657. var cached = Cache.get(url);
  22658. if (cached !== undefined) {
  22659. scope.manager.itemStart(url);
  22660. setTimeout(function () {
  22661. if (onLoad) onLoad(cached);
  22662. scope.manager.itemEnd(url);
  22663. }, 0);
  22664. return cached;
  22665. }
  22666. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22667. function onImageLoad() {
  22668. image.removeEventListener('load', onImageLoad, false);
  22669. image.removeEventListener('error', onImageError, false);
  22670. Cache.add(url, this);
  22671. if (onLoad) onLoad(this);
  22672. scope.manager.itemEnd(url);
  22673. }
  22674. function onImageError(event) {
  22675. image.removeEventListener('load', onImageLoad, false);
  22676. image.removeEventListener('error', onImageError, false);
  22677. if (onError) onError(event);
  22678. scope.manager.itemError(url);
  22679. scope.manager.itemEnd(url);
  22680. }
  22681. image.addEventListener('load', onImageLoad, false);
  22682. image.addEventListener('error', onImageError, false);
  22683. if (url.substr(0, 5) !== 'data:') {
  22684. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22685. }
  22686. scope.manager.itemStart(url);
  22687. image.src = url;
  22688. return image;
  22689. }
  22690. });
  22691. /**
  22692. * @author mrdoob / http://mrdoob.com/
  22693. */
  22694. function CubeTextureLoader(manager) {
  22695. Loader.call(this, manager);
  22696. }
  22697. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22698. constructor: CubeTextureLoader,
  22699. load: function (urls, onLoad, onProgress, onError) {
  22700. var texture = new CubeTexture();
  22701. var loader = new ImageLoader(this.manager);
  22702. loader.setCrossOrigin(this.crossOrigin);
  22703. loader.setPath(this.path);
  22704. var loaded = 0;
  22705. function loadTexture(i) {
  22706. loader.load(urls[i], function (image) {
  22707. texture.images[i] = image;
  22708. loaded++;
  22709. if (loaded === 6) {
  22710. texture.needsUpdate = true;
  22711. if (onLoad) onLoad(texture);
  22712. }
  22713. }, undefined, onError);
  22714. }
  22715. for (var i = 0; i < urls.length; ++i) {
  22716. loadTexture(i);
  22717. }
  22718. return texture;
  22719. }
  22720. });
  22721. /**
  22722. * @author mrdoob / http://mrdoob.com/
  22723. */
  22724. function TextureLoader(manager) {
  22725. Loader.call(this, manager);
  22726. }
  22727. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22728. constructor: TextureLoader,
  22729. load: function (url, onLoad, onProgress, onError) {
  22730. var texture = new Texture();
  22731. var loader = new ImageLoader(this.manager);
  22732. loader.setCrossOrigin(this.crossOrigin);
  22733. loader.setPath(this.path);
  22734. loader.load(url, function (image) {
  22735. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22736. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22737. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22738. texture.needsUpdate = true;
  22739. if (onLoad !== undefined) {
  22740. onLoad(texture);
  22741. }
  22742. }, onProgress, onError);
  22743. return texture;
  22744. }
  22745. });
  22746. /**
  22747. * @author zz85 / http://www.lab4games.net/zz85/blog
  22748. * Extensible curve object
  22749. *
  22750. * Some common of curve methods:
  22751. * .getPoint( t, optionalTarget ), .getTangent( t )
  22752. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  22753. * .getPoints(), .getSpacedPoints()
  22754. * .getLength()
  22755. * .updateArcLengths()
  22756. *
  22757. * This following curves inherit from THREE.Curve:
  22758. *
  22759. * -- 2D curves --
  22760. * THREE.ArcCurve
  22761. * THREE.CubicBezierCurve
  22762. * THREE.EllipseCurve
  22763. * THREE.LineCurve
  22764. * THREE.QuadraticBezierCurve
  22765. * THREE.SplineCurve
  22766. *
  22767. * -- 3D curves --
  22768. * THREE.CatmullRomCurve3
  22769. * THREE.CubicBezierCurve3
  22770. * THREE.LineCurve3
  22771. * THREE.QuadraticBezierCurve3
  22772. *
  22773. * A series of curves can be represented as a THREE.CurvePath.
  22774. *
  22775. **/
  22776. /**************************************************************
  22777. * Abstract Curve base class
  22778. **************************************************************/
  22779. function Curve() {
  22780. this.type = 'Curve';
  22781. this.arcLengthDivisions = 200;
  22782. }
  22783. Object.assign(Curve.prototype, {
  22784. // Virtual base class method to overwrite and implement in subclasses
  22785. // - t [0 .. 1]
  22786. getPoint: function ()
  22787. /* t, optionalTarget */
  22788. {
  22789. console.warn('THREE.Curve: .getPoint() not implemented.');
  22790. return null;
  22791. },
  22792. // Get point at relative position in curve according to arc length
  22793. // - u [0 .. 1]
  22794. getPointAt: function (u, optionalTarget) {
  22795. var t = this.getUtoTmapping(u);
  22796. return this.getPoint(t, optionalTarget);
  22797. },
  22798. // Get sequence of points using getPoint( t )
  22799. getPoints: function (divisions) {
  22800. if (divisions === undefined) divisions = 5;
  22801. var points = [];
  22802. for (var d = 0; d <= divisions; d++) {
  22803. points.push(this.getPoint(d / divisions));
  22804. }
  22805. return points;
  22806. },
  22807. // Get sequence of points using getPointAt( u )
  22808. getSpacedPoints: function (divisions) {
  22809. if (divisions === undefined) divisions = 5;
  22810. var points = [];
  22811. for (var d = 0; d <= divisions; d++) {
  22812. points.push(this.getPointAt(d / divisions));
  22813. }
  22814. return points;
  22815. },
  22816. // Get total curve arc length
  22817. getLength: function () {
  22818. var lengths = this.getLengths();
  22819. return lengths[lengths.length - 1];
  22820. },
  22821. // Get list of cumulative segment lengths
  22822. getLengths: function (divisions) {
  22823. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22824. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22825. return this.cacheArcLengths;
  22826. }
  22827. this.needsUpdate = false;
  22828. var cache = [];
  22829. var current,
  22830. last = this.getPoint(0);
  22831. var p,
  22832. sum = 0;
  22833. cache.push(0);
  22834. for (p = 1; p <= divisions; p++) {
  22835. current = this.getPoint(p / divisions);
  22836. sum += current.distanceTo(last);
  22837. cache.push(sum);
  22838. last = current;
  22839. }
  22840. this.cacheArcLengths = cache;
  22841. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22842. },
  22843. updateArcLengths: function () {
  22844. this.needsUpdate = true;
  22845. this.getLengths();
  22846. },
  22847. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22848. getUtoTmapping: function (u, distance) {
  22849. var arcLengths = this.getLengths();
  22850. var i = 0,
  22851. il = arcLengths.length;
  22852. var targetArcLength; // The targeted u distance value to get
  22853. if (distance) {
  22854. targetArcLength = distance;
  22855. } else {
  22856. targetArcLength = u * arcLengths[il - 1];
  22857. } // binary search for the index with largest value smaller than target u distance
  22858. var low = 0,
  22859. high = il - 1,
  22860. comparison;
  22861. while (low <= high) {
  22862. 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
  22863. comparison = arcLengths[i] - targetArcLength;
  22864. if (comparison < 0) {
  22865. low = i + 1;
  22866. } else if (comparison > 0) {
  22867. high = i - 1;
  22868. } else {
  22869. high = i;
  22870. break; // DONE
  22871. }
  22872. }
  22873. i = high;
  22874. if (arcLengths[i] === targetArcLength) {
  22875. return i / (il - 1);
  22876. } // we could get finer grain at lengths, or use simple interpolation between two points
  22877. var lengthBefore = arcLengths[i];
  22878. var lengthAfter = arcLengths[i + 1];
  22879. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22880. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22881. var t = (i + segmentFraction) / (il - 1);
  22882. return t;
  22883. },
  22884. // Returns a unit vector tangent at t
  22885. // In case any sub curve does not implement its tangent derivation,
  22886. // 2 points a small delta apart will be used to find its gradient
  22887. // which seems to give a reasonable approximation
  22888. getTangent: function (t) {
  22889. var delta = 0.0001;
  22890. var t1 = t - delta;
  22891. var t2 = t + delta; // Capping in case of danger
  22892. if (t1 < 0) t1 = 0;
  22893. if (t2 > 1) t2 = 1;
  22894. var pt1 = this.getPoint(t1);
  22895. var pt2 = this.getPoint(t2);
  22896. var vec = pt2.clone().sub(pt1);
  22897. return vec.normalize();
  22898. },
  22899. getTangentAt: function (u) {
  22900. var t = this.getUtoTmapping(u);
  22901. return this.getTangent(t);
  22902. },
  22903. computeFrenetFrames: function (segments, closed) {
  22904. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22905. var normal = new Vector3();
  22906. var tangents = [];
  22907. var normals = [];
  22908. var binormals = [];
  22909. var vec = new Vector3();
  22910. var mat = new Matrix4();
  22911. var i, u, theta; // compute the tangent vectors for each segment on the curve
  22912. for (i = 0; i <= segments; i++) {
  22913. u = i / segments;
  22914. tangents[i] = this.getTangentAt(u);
  22915. tangents[i].normalize();
  22916. } // select an initial normal vector perpendicular to the first tangent vector,
  22917. // and in the direction of the minimum tangent xyz component
  22918. normals[0] = new Vector3();
  22919. binormals[0] = new Vector3();
  22920. var min = Number.MAX_VALUE;
  22921. var tx = Math.abs(tangents[0].x);
  22922. var ty = Math.abs(tangents[0].y);
  22923. var tz = Math.abs(tangents[0].z);
  22924. if (tx <= min) {
  22925. min = tx;
  22926. normal.set(1, 0, 0);
  22927. }
  22928. if (ty <= min) {
  22929. min = ty;
  22930. normal.set(0, 1, 0);
  22931. }
  22932. if (tz <= min) {
  22933. normal.set(0, 0, 1);
  22934. }
  22935. vec.crossVectors(tangents[0], normal).normalize();
  22936. normals[0].crossVectors(tangents[0], vec);
  22937. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22938. for (i = 1; i <= segments; i++) {
  22939. normals[i] = normals[i - 1].clone();
  22940. binormals[i] = binormals[i - 1].clone();
  22941. vec.crossVectors(tangents[i - 1], tangents[i]);
  22942. if (vec.length() > Number.EPSILON) {
  22943. vec.normalize();
  22944. theta = Math.acos(_Math.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22945. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22946. }
  22947. binormals[i].crossVectors(tangents[i], normals[i]);
  22948. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22949. if (closed === true) {
  22950. theta = Math.acos(_Math.clamp(normals[0].dot(normals[segments]), -1, 1));
  22951. theta /= segments;
  22952. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22953. theta = -theta;
  22954. }
  22955. for (i = 1; i <= segments; i++) {
  22956. // twist a little...
  22957. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22958. binormals[i].crossVectors(tangents[i], normals[i]);
  22959. }
  22960. }
  22961. return {
  22962. tangents: tangents,
  22963. normals: normals,
  22964. binormals: binormals
  22965. };
  22966. },
  22967. clone: function () {
  22968. return new this.constructor().copy(this);
  22969. },
  22970. copy: function (source) {
  22971. this.arcLengthDivisions = source.arcLengthDivisions;
  22972. return this;
  22973. },
  22974. toJSON: function () {
  22975. var data = {
  22976. metadata: {
  22977. version: 4.5,
  22978. type: 'Curve',
  22979. generator: 'Curve.toJSON'
  22980. }
  22981. };
  22982. data.arcLengthDivisions = this.arcLengthDivisions;
  22983. data.type = this.type;
  22984. return data;
  22985. },
  22986. fromJSON: function (json) {
  22987. this.arcLengthDivisions = json.arcLengthDivisions;
  22988. return this;
  22989. }
  22990. });
  22991. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22992. Curve.call(this);
  22993. this.type = 'EllipseCurve';
  22994. this.aX = aX || 0;
  22995. this.aY = aY || 0;
  22996. this.xRadius = xRadius || 1;
  22997. this.yRadius = yRadius || 1;
  22998. this.aStartAngle = aStartAngle || 0;
  22999. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23000. this.aClockwise = aClockwise || false;
  23001. this.aRotation = aRotation || 0;
  23002. }
  23003. EllipseCurve.prototype = Object.create(Curve.prototype);
  23004. EllipseCurve.prototype.constructor = EllipseCurve;
  23005. EllipseCurve.prototype.isEllipseCurve = true;
  23006. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  23007. var point = optionalTarget || new Vector2();
  23008. var twoPi = Math.PI * 2;
  23009. var deltaAngle = this.aEndAngle - this.aStartAngle;
  23010. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  23011. while (deltaAngle < 0) deltaAngle += twoPi;
  23012. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  23013. if (deltaAngle < Number.EPSILON) {
  23014. if (samePoints) {
  23015. deltaAngle = 0;
  23016. } else {
  23017. deltaAngle = twoPi;
  23018. }
  23019. }
  23020. if (this.aClockwise === true && !samePoints) {
  23021. if (deltaAngle === twoPi) {
  23022. deltaAngle = -twoPi;
  23023. } else {
  23024. deltaAngle = deltaAngle - twoPi;
  23025. }
  23026. }
  23027. var angle = this.aStartAngle + t * deltaAngle;
  23028. var x = this.aX + this.xRadius * Math.cos(angle);
  23029. var y = this.aY + this.yRadius * Math.sin(angle);
  23030. if (this.aRotation !== 0) {
  23031. var cos = Math.cos(this.aRotation);
  23032. var sin = Math.sin(this.aRotation);
  23033. var tx = x - this.aX;
  23034. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  23035. x = tx * cos - ty * sin + this.aX;
  23036. y = tx * sin + ty * cos + this.aY;
  23037. }
  23038. return point.set(x, y);
  23039. };
  23040. EllipseCurve.prototype.copy = function (source) {
  23041. Curve.prototype.copy.call(this, source);
  23042. this.aX = source.aX;
  23043. this.aY = source.aY;
  23044. this.xRadius = source.xRadius;
  23045. this.yRadius = source.yRadius;
  23046. this.aStartAngle = source.aStartAngle;
  23047. this.aEndAngle = source.aEndAngle;
  23048. this.aClockwise = source.aClockwise;
  23049. this.aRotation = source.aRotation;
  23050. return this;
  23051. };
  23052. EllipseCurve.prototype.toJSON = function () {
  23053. var data = Curve.prototype.toJSON.call(this);
  23054. data.aX = this.aX;
  23055. data.aY = this.aY;
  23056. data.xRadius = this.xRadius;
  23057. data.yRadius = this.yRadius;
  23058. data.aStartAngle = this.aStartAngle;
  23059. data.aEndAngle = this.aEndAngle;
  23060. data.aClockwise = this.aClockwise;
  23061. data.aRotation = this.aRotation;
  23062. return data;
  23063. };
  23064. EllipseCurve.prototype.fromJSON = function (json) {
  23065. Curve.prototype.fromJSON.call(this, json);
  23066. this.aX = json.aX;
  23067. this.aY = json.aY;
  23068. this.xRadius = json.xRadius;
  23069. this.yRadius = json.yRadius;
  23070. this.aStartAngle = json.aStartAngle;
  23071. this.aEndAngle = json.aEndAngle;
  23072. this.aClockwise = json.aClockwise;
  23073. this.aRotation = json.aRotation;
  23074. return this;
  23075. };
  23076. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23077. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23078. this.type = 'ArcCurve';
  23079. }
  23080. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  23081. ArcCurve.prototype.constructor = ArcCurve;
  23082. ArcCurve.prototype.isArcCurve = true;
  23083. /**
  23084. * @author zz85 https://github.com/zz85
  23085. *
  23086. * Centripetal CatmullRom Curve - which is useful for avoiding
  23087. * cusps and self-intersections in non-uniform catmull rom curves.
  23088. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23089. *
  23090. * curve.type accepts centripetal(default), chordal and catmullrom
  23091. * curve.tension is used for catmullrom which defaults to 0.5
  23092. */
  23093. /*
  23094. Based on an optimized c++ solution in
  23095. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23096. - http://ideone.com/NoEbVM
  23097. This CubicPoly class could be used for reusing some variables and calculations,
  23098. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23099. which can be placed in CurveUtils.
  23100. */
  23101. function CubicPoly() {
  23102. var c0 = 0,
  23103. c1 = 0,
  23104. c2 = 0,
  23105. c3 = 0;
  23106. /*
  23107. * Compute coefficients for a cubic polynomial
  23108. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23109. * such that
  23110. * p(0) = x0, p(1) = x1
  23111. * and
  23112. * p'(0) = t0, p'(1) = t1.
  23113. */
  23114. function init(x0, x1, t0, t1) {
  23115. c0 = x0;
  23116. c1 = t0;
  23117. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23118. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23119. }
  23120. return {
  23121. initCatmullRom: function (x0, x1, x2, x3, tension) {
  23122. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  23123. },
  23124. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  23125. // compute tangents when parameterized in [t1,t2]
  23126. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  23127. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  23128. t1 *= dt1;
  23129. t2 *= dt1;
  23130. init(x1, x2, t1, t2);
  23131. },
  23132. calc: function (t) {
  23133. var t2 = t * t;
  23134. var t3 = t2 * t;
  23135. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23136. }
  23137. };
  23138. } //
  23139. var tmp = new Vector3();
  23140. var px = new CubicPoly(),
  23141. py = new CubicPoly(),
  23142. pz = new CubicPoly();
  23143. function CatmullRomCurve3(points, closed, curveType, tension) {
  23144. Curve.call(this);
  23145. this.type = 'CatmullRomCurve3';
  23146. this.points = points || [];
  23147. this.closed = closed || false;
  23148. this.curveType = curveType || 'centripetal';
  23149. this.tension = tension || 0.5;
  23150. }
  23151. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  23152. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23153. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23154. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  23155. var point = optionalTarget || new Vector3();
  23156. var points = this.points;
  23157. var l = points.length;
  23158. var p = (l - (this.closed ? 0 : 1)) * t;
  23159. var intPoint = Math.floor(p);
  23160. var weight = p - intPoint;
  23161. if (this.closed) {
  23162. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  23163. } else if (weight === 0 && intPoint === l - 1) {
  23164. intPoint = l - 2;
  23165. weight = 1;
  23166. }
  23167. var p0, p1, p2, p3; // 4 points
  23168. if (this.closed || intPoint > 0) {
  23169. p0 = points[(intPoint - 1) % l];
  23170. } else {
  23171. // extrapolate first point
  23172. tmp.subVectors(points[0], points[1]).add(points[0]);
  23173. p0 = tmp;
  23174. }
  23175. p1 = points[intPoint % l];
  23176. p2 = points[(intPoint + 1) % l];
  23177. if (this.closed || intPoint + 2 < l) {
  23178. p3 = points[(intPoint + 2) % l];
  23179. } else {
  23180. // extrapolate last point
  23181. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  23182. p3 = tmp;
  23183. }
  23184. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  23185. // init Centripetal / Chordal Catmull-Rom
  23186. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23187. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  23188. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  23189. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  23190. if (dt1 < 1e-4) dt1 = 1.0;
  23191. if (dt0 < 1e-4) dt0 = dt1;
  23192. if (dt2 < 1e-4) dt2 = dt1;
  23193. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  23194. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  23195. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  23196. } else if (this.curveType === 'catmullrom') {
  23197. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  23198. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  23199. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  23200. }
  23201. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  23202. return point;
  23203. };
  23204. CatmullRomCurve3.prototype.copy = function (source) {
  23205. Curve.prototype.copy.call(this, source);
  23206. this.points = [];
  23207. for (var i = 0, l = source.points.length; i < l; i++) {
  23208. var point = source.points[i];
  23209. this.points.push(point.clone());
  23210. }
  23211. this.closed = source.closed;
  23212. this.curveType = source.curveType;
  23213. this.tension = source.tension;
  23214. return this;
  23215. };
  23216. CatmullRomCurve3.prototype.toJSON = function () {
  23217. var data = Curve.prototype.toJSON.call(this);
  23218. data.points = [];
  23219. for (var i = 0, l = this.points.length; i < l; i++) {
  23220. var point = this.points[i];
  23221. data.points.push(point.toArray());
  23222. }
  23223. data.closed = this.closed;
  23224. data.curveType = this.curveType;
  23225. data.tension = this.tension;
  23226. return data;
  23227. };
  23228. CatmullRomCurve3.prototype.fromJSON = function (json) {
  23229. Curve.prototype.fromJSON.call(this, json);
  23230. this.points = [];
  23231. for (var i = 0, l = json.points.length; i < l; i++) {
  23232. var point = json.points[i];
  23233. this.points.push(new Vector3().fromArray(point));
  23234. }
  23235. this.closed = json.closed;
  23236. this.curveType = json.curveType;
  23237. this.tension = json.tension;
  23238. return this;
  23239. };
  23240. /**
  23241. * @author zz85 / http://www.lab4games.net/zz85/blog
  23242. *
  23243. * Bezier Curves formulas obtained from
  23244. * http://en.wikipedia.org/wiki/Bézier_curve
  23245. */
  23246. function CatmullRom(t, p0, p1, p2, p3) {
  23247. var v0 = (p2 - p0) * 0.5;
  23248. var v1 = (p3 - p1) * 0.5;
  23249. var t2 = t * t;
  23250. var t3 = t * t2;
  23251. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  23252. } //
  23253. function QuadraticBezierP0(t, p) {
  23254. var k = 1 - t;
  23255. return k * k * p;
  23256. }
  23257. function QuadraticBezierP1(t, p) {
  23258. return 2 * (1 - t) * t * p;
  23259. }
  23260. function QuadraticBezierP2(t, p) {
  23261. return t * t * p;
  23262. }
  23263. function QuadraticBezier(t, p0, p1, p2) {
  23264. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  23265. } //
  23266. function CubicBezierP0(t, p) {
  23267. var k = 1 - t;
  23268. return k * k * k * p;
  23269. }
  23270. function CubicBezierP1(t, p) {
  23271. var k = 1 - t;
  23272. return 3 * k * k * t * p;
  23273. }
  23274. function CubicBezierP2(t, p) {
  23275. return 3 * (1 - t) * t * t * p;
  23276. }
  23277. function CubicBezierP3(t, p) {
  23278. return t * t * t * p;
  23279. }
  23280. function CubicBezier(t, p0, p1, p2, p3) {
  23281. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  23282. }
  23283. function CubicBezierCurve(v0, v1, v2, v3) {
  23284. Curve.call(this);
  23285. this.type = 'CubicBezierCurve';
  23286. this.v0 = v0 || new Vector2();
  23287. this.v1 = v1 || new Vector2();
  23288. this.v2 = v2 || new Vector2();
  23289. this.v3 = v3 || new Vector2();
  23290. }
  23291. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  23292. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23293. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23294. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23295. var point = optionalTarget || new Vector2();
  23296. var v0 = this.v0,
  23297. v1 = this.v1,
  23298. v2 = this.v2,
  23299. v3 = this.v3;
  23300. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  23301. return point;
  23302. };
  23303. CubicBezierCurve.prototype.copy = function (source) {
  23304. Curve.prototype.copy.call(this, source);
  23305. this.v0.copy(source.v0);
  23306. this.v1.copy(source.v1);
  23307. this.v2.copy(source.v2);
  23308. this.v3.copy(source.v3);
  23309. return this;
  23310. };
  23311. CubicBezierCurve.prototype.toJSON = function () {
  23312. var data = Curve.prototype.toJSON.call(this);
  23313. data.v0 = this.v0.toArray();
  23314. data.v1 = this.v1.toArray();
  23315. data.v2 = this.v2.toArray();
  23316. data.v3 = this.v3.toArray();
  23317. return data;
  23318. };
  23319. CubicBezierCurve.prototype.fromJSON = function (json) {
  23320. Curve.prototype.fromJSON.call(this, json);
  23321. this.v0.fromArray(json.v0);
  23322. this.v1.fromArray(json.v1);
  23323. this.v2.fromArray(json.v2);
  23324. this.v3.fromArray(json.v3);
  23325. return this;
  23326. };
  23327. function CubicBezierCurve3(v0, v1, v2, v3) {
  23328. Curve.call(this);
  23329. this.type = 'CubicBezierCurve3';
  23330. this.v0 = v0 || new Vector3();
  23331. this.v1 = v1 || new Vector3();
  23332. this.v2 = v2 || new Vector3();
  23333. this.v3 = v3 || new Vector3();
  23334. }
  23335. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  23336. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23337. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23338. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23339. var point = optionalTarget || new Vector3();
  23340. var v0 = this.v0,
  23341. v1 = this.v1,
  23342. v2 = this.v2,
  23343. v3 = this.v3;
  23344. 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));
  23345. return point;
  23346. };
  23347. CubicBezierCurve3.prototype.copy = function (source) {
  23348. Curve.prototype.copy.call(this, source);
  23349. this.v0.copy(source.v0);
  23350. this.v1.copy(source.v1);
  23351. this.v2.copy(source.v2);
  23352. this.v3.copy(source.v3);
  23353. return this;
  23354. };
  23355. CubicBezierCurve3.prototype.toJSON = function () {
  23356. var data = Curve.prototype.toJSON.call(this);
  23357. data.v0 = this.v0.toArray();
  23358. data.v1 = this.v1.toArray();
  23359. data.v2 = this.v2.toArray();
  23360. data.v3 = this.v3.toArray();
  23361. return data;
  23362. };
  23363. CubicBezierCurve3.prototype.fromJSON = function (json) {
  23364. Curve.prototype.fromJSON.call(this, json);
  23365. this.v0.fromArray(json.v0);
  23366. this.v1.fromArray(json.v1);
  23367. this.v2.fromArray(json.v2);
  23368. this.v3.fromArray(json.v3);
  23369. return this;
  23370. };
  23371. function LineCurve(v1, v2) {
  23372. Curve.call(this);
  23373. this.type = 'LineCurve';
  23374. this.v1 = v1 || new Vector2();
  23375. this.v2 = v2 || new Vector2();
  23376. }
  23377. LineCurve.prototype = Object.create(Curve.prototype);
  23378. LineCurve.prototype.constructor = LineCurve;
  23379. LineCurve.prototype.isLineCurve = true;
  23380. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  23381. var point = optionalTarget || new Vector2();
  23382. if (t === 1) {
  23383. point.copy(this.v2);
  23384. } else {
  23385. point.copy(this.v2).sub(this.v1);
  23386. point.multiplyScalar(t).add(this.v1);
  23387. }
  23388. return point;
  23389. }; // Line curve is linear, so we can overwrite default getPointAt
  23390. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  23391. return this.getPoint(u, optionalTarget);
  23392. };
  23393. LineCurve.prototype.getTangent = function ()
  23394. /* t */
  23395. {
  23396. var tangent = this.v2.clone().sub(this.v1);
  23397. return tangent.normalize();
  23398. };
  23399. LineCurve.prototype.copy = function (source) {
  23400. Curve.prototype.copy.call(this, source);
  23401. this.v1.copy(source.v1);
  23402. this.v2.copy(source.v2);
  23403. return this;
  23404. };
  23405. LineCurve.prototype.toJSON = function () {
  23406. var data = Curve.prototype.toJSON.call(this);
  23407. data.v1 = this.v1.toArray();
  23408. data.v2 = this.v2.toArray();
  23409. return data;
  23410. };
  23411. LineCurve.prototype.fromJSON = function (json) {
  23412. Curve.prototype.fromJSON.call(this, json);
  23413. this.v1.fromArray(json.v1);
  23414. this.v2.fromArray(json.v2);
  23415. return this;
  23416. };
  23417. function LineCurve3(v1, v2) {
  23418. Curve.call(this);
  23419. this.type = 'LineCurve3';
  23420. this.v1 = v1 || new Vector3();
  23421. this.v2 = v2 || new Vector3();
  23422. }
  23423. LineCurve3.prototype = Object.create(Curve.prototype);
  23424. LineCurve3.prototype.constructor = LineCurve3;
  23425. LineCurve3.prototype.isLineCurve3 = true;
  23426. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  23427. var point = optionalTarget || new Vector3();
  23428. if (t === 1) {
  23429. point.copy(this.v2);
  23430. } else {
  23431. point.copy(this.v2).sub(this.v1);
  23432. point.multiplyScalar(t).add(this.v1);
  23433. }
  23434. return point;
  23435. }; // Line curve is linear, so we can overwrite default getPointAt
  23436. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  23437. return this.getPoint(u, optionalTarget);
  23438. };
  23439. LineCurve3.prototype.copy = function (source) {
  23440. Curve.prototype.copy.call(this, source);
  23441. this.v1.copy(source.v1);
  23442. this.v2.copy(source.v2);
  23443. return this;
  23444. };
  23445. LineCurve3.prototype.toJSON = function () {
  23446. var data = Curve.prototype.toJSON.call(this);
  23447. data.v1 = this.v1.toArray();
  23448. data.v2 = this.v2.toArray();
  23449. return data;
  23450. };
  23451. LineCurve3.prototype.fromJSON = function (json) {
  23452. Curve.prototype.fromJSON.call(this, json);
  23453. this.v1.fromArray(json.v1);
  23454. this.v2.fromArray(json.v2);
  23455. return this;
  23456. };
  23457. function QuadraticBezierCurve(v0, v1, v2) {
  23458. Curve.call(this);
  23459. this.type = 'QuadraticBezierCurve';
  23460. this.v0 = v0 || new Vector2();
  23461. this.v1 = v1 || new Vector2();
  23462. this.v2 = v2 || new Vector2();
  23463. }
  23464. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  23465. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23466. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23467. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  23468. var point = optionalTarget || new Vector2();
  23469. var v0 = this.v0,
  23470. v1 = this.v1,
  23471. v2 = this.v2;
  23472. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  23473. return point;
  23474. };
  23475. QuadraticBezierCurve.prototype.copy = function (source) {
  23476. Curve.prototype.copy.call(this, source);
  23477. this.v0.copy(source.v0);
  23478. this.v1.copy(source.v1);
  23479. this.v2.copy(source.v2);
  23480. return this;
  23481. };
  23482. QuadraticBezierCurve.prototype.toJSON = function () {
  23483. var data = Curve.prototype.toJSON.call(this);
  23484. data.v0 = this.v0.toArray();
  23485. data.v1 = this.v1.toArray();
  23486. data.v2 = this.v2.toArray();
  23487. return data;
  23488. };
  23489. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  23490. Curve.prototype.fromJSON.call(this, json);
  23491. this.v0.fromArray(json.v0);
  23492. this.v1.fromArray(json.v1);
  23493. this.v2.fromArray(json.v2);
  23494. return this;
  23495. };
  23496. function QuadraticBezierCurve3(v0, v1, v2) {
  23497. Curve.call(this);
  23498. this.type = 'QuadraticBezierCurve3';
  23499. this.v0 = v0 || new Vector3();
  23500. this.v1 = v1 || new Vector3();
  23501. this.v2 = v2 || new Vector3();
  23502. }
  23503. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  23504. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23505. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23506. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  23507. var point = optionalTarget || new Vector3();
  23508. var v0 = this.v0,
  23509. v1 = this.v1,
  23510. v2 = this.v2;
  23511. 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));
  23512. return point;
  23513. };
  23514. QuadraticBezierCurve3.prototype.copy = function (source) {
  23515. Curve.prototype.copy.call(this, source);
  23516. this.v0.copy(source.v0);
  23517. this.v1.copy(source.v1);
  23518. this.v2.copy(source.v2);
  23519. return this;
  23520. };
  23521. QuadraticBezierCurve3.prototype.toJSON = function () {
  23522. var data = Curve.prototype.toJSON.call(this);
  23523. data.v0 = this.v0.toArray();
  23524. data.v1 = this.v1.toArray();
  23525. data.v2 = this.v2.toArray();
  23526. return data;
  23527. };
  23528. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  23529. Curve.prototype.fromJSON.call(this, json);
  23530. this.v0.fromArray(json.v0);
  23531. this.v1.fromArray(json.v1);
  23532. this.v2.fromArray(json.v2);
  23533. return this;
  23534. };
  23535. function SplineCurve(points
  23536. /* array of Vector2 */
  23537. ) {
  23538. Curve.call(this);
  23539. this.type = 'SplineCurve';
  23540. this.points = points || [];
  23541. }
  23542. SplineCurve.prototype = Object.create(Curve.prototype);
  23543. SplineCurve.prototype.constructor = SplineCurve;
  23544. SplineCurve.prototype.isSplineCurve = true;
  23545. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  23546. var point = optionalTarget || new Vector2();
  23547. var points = this.points;
  23548. var p = (points.length - 1) * t;
  23549. var intPoint = Math.floor(p);
  23550. var weight = p - intPoint;
  23551. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  23552. var p1 = points[intPoint];
  23553. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  23554. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  23555. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  23556. return point;
  23557. };
  23558. SplineCurve.prototype.copy = function (source) {
  23559. Curve.prototype.copy.call(this, source);
  23560. this.points = [];
  23561. for (var i = 0, l = source.points.length; i < l; i++) {
  23562. var point = source.points[i];
  23563. this.points.push(point.clone());
  23564. }
  23565. return this;
  23566. };
  23567. SplineCurve.prototype.toJSON = function () {
  23568. var data = Curve.prototype.toJSON.call(this);
  23569. data.points = [];
  23570. for (var i = 0, l = this.points.length; i < l; i++) {
  23571. var point = this.points[i];
  23572. data.points.push(point.toArray());
  23573. }
  23574. return data;
  23575. };
  23576. SplineCurve.prototype.fromJSON = function (json) {
  23577. Curve.prototype.fromJSON.call(this, json);
  23578. this.points = [];
  23579. for (var i = 0, l = json.points.length; i < l; i++) {
  23580. var point = json.points[i];
  23581. this.points.push(new Vector2().fromArray(point));
  23582. }
  23583. return this;
  23584. };
  23585. var Curves =
  23586. /*#__PURE__*/
  23587. Object.freeze({
  23588. ArcCurve: ArcCurve,
  23589. CatmullRomCurve3: CatmullRomCurve3,
  23590. CubicBezierCurve: CubicBezierCurve,
  23591. CubicBezierCurve3: CubicBezierCurve3,
  23592. EllipseCurve: EllipseCurve,
  23593. LineCurve: LineCurve,
  23594. LineCurve3: LineCurve3,
  23595. QuadraticBezierCurve: QuadraticBezierCurve,
  23596. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23597. SplineCurve: SplineCurve
  23598. });
  23599. /**
  23600. * @author zz85 / http://www.lab4games.net/zz85/blog
  23601. *
  23602. **/
  23603. /**************************************************************
  23604. * Curved Path - a curve path is simply a array of connected
  23605. * curves, but retains the api of a curve
  23606. **************************************************************/
  23607. function CurvePath() {
  23608. Curve.call(this);
  23609. this.type = 'CurvePath';
  23610. this.curves = [];
  23611. this.autoClose = false; // Automatically closes the path
  23612. }
  23613. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  23614. constructor: CurvePath,
  23615. add: function (curve) {
  23616. this.curves.push(curve);
  23617. },
  23618. closePath: function () {
  23619. // Add a line curve if start and end of lines are not connected
  23620. var startPoint = this.curves[0].getPoint(0);
  23621. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  23622. if (!startPoint.equals(endPoint)) {
  23623. this.curves.push(new LineCurve(endPoint, startPoint));
  23624. }
  23625. },
  23626. // To get accurate point with reference to
  23627. // entire path distance at time t,
  23628. // following has to be done:
  23629. // 1. Length of each sub path have to be known
  23630. // 2. Locate and identify type of curve
  23631. // 3. Get t for the curve
  23632. // 4. Return curve.getPointAt(t')
  23633. getPoint: function (t) {
  23634. var d = t * this.getLength();
  23635. var curveLengths = this.getCurveLengths();
  23636. var i = 0; // To think about boundaries points.
  23637. while (i < curveLengths.length) {
  23638. if (curveLengths[i] >= d) {
  23639. var diff = curveLengths[i] - d;
  23640. var curve = this.curves[i];
  23641. var segmentLength = curve.getLength();
  23642. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23643. return curve.getPointAt(u);
  23644. }
  23645. i++;
  23646. }
  23647. return null; // loop where sum != 0, sum > d , sum+1 <d
  23648. },
  23649. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23650. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23651. // getPoint() depends on getLength
  23652. getLength: function () {
  23653. var lens = this.getCurveLengths();
  23654. return lens[lens.length - 1];
  23655. },
  23656. // cacheLengths must be recalculated.
  23657. updateArcLengths: function () {
  23658. this.needsUpdate = true;
  23659. this.cacheLengths = null;
  23660. this.getCurveLengths();
  23661. },
  23662. // Compute lengths and cache them
  23663. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23664. getCurveLengths: function () {
  23665. // We use cache values if curves and cache array are same length
  23666. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  23667. return this.cacheLengths;
  23668. } // Get length of sub-curve
  23669. // Push sums into cached array
  23670. var lengths = [],
  23671. sums = 0;
  23672. for (var i = 0, l = this.curves.length; i < l; i++) {
  23673. sums += this.curves[i].getLength();
  23674. lengths.push(sums);
  23675. }
  23676. this.cacheLengths = lengths;
  23677. return lengths;
  23678. },
  23679. getSpacedPoints: function (divisions) {
  23680. if (divisions === undefined) divisions = 40;
  23681. var points = [];
  23682. for (var i = 0; i <= divisions; i++) {
  23683. points.push(this.getPoint(i / divisions));
  23684. }
  23685. if (this.autoClose) {
  23686. points.push(points[0]);
  23687. }
  23688. return points;
  23689. },
  23690. getPoints: function (divisions) {
  23691. divisions = divisions || 12;
  23692. var points = [],
  23693. last;
  23694. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  23695. var curve = curves[i];
  23696. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  23697. var pts = curve.getPoints(resolution);
  23698. for (var j = 0; j < pts.length; j++) {
  23699. var point = pts[j];
  23700. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  23701. points.push(point);
  23702. last = point;
  23703. }
  23704. }
  23705. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  23706. points.push(points[0]);
  23707. }
  23708. return points;
  23709. },
  23710. copy: function (source) {
  23711. Curve.prototype.copy.call(this, source);
  23712. this.curves = [];
  23713. for (var i = 0, l = source.curves.length; i < l; i++) {
  23714. var curve = source.curves[i];
  23715. this.curves.push(curve.clone());
  23716. }
  23717. this.autoClose = source.autoClose;
  23718. return this;
  23719. },
  23720. toJSON: function () {
  23721. var data = Curve.prototype.toJSON.call(this);
  23722. data.autoClose = this.autoClose;
  23723. data.curves = [];
  23724. for (var i = 0, l = this.curves.length; i < l; i++) {
  23725. var curve = this.curves[i];
  23726. data.curves.push(curve.toJSON());
  23727. }
  23728. return data;
  23729. },
  23730. fromJSON: function (json) {
  23731. Curve.prototype.fromJSON.call(this, json);
  23732. this.autoClose = json.autoClose;
  23733. this.curves = [];
  23734. for (var i = 0, l = json.curves.length; i < l; i++) {
  23735. var curve = json.curves[i];
  23736. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23737. }
  23738. return this;
  23739. }
  23740. });
  23741. /**
  23742. * @author zz85 / http://www.lab4games.net/zz85/blog
  23743. * Creates free form 2d path using series of points, lines or curves.
  23744. **/
  23745. function Path(points) {
  23746. CurvePath.call(this);
  23747. this.type = 'Path';
  23748. this.currentPoint = new Vector2();
  23749. if (points) {
  23750. this.setFromPoints(points);
  23751. }
  23752. }
  23753. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23754. constructor: Path,
  23755. setFromPoints: function (points) {
  23756. this.moveTo(points[0].x, points[0].y);
  23757. for (var i = 1, l = points.length; i < l; i++) {
  23758. this.lineTo(points[i].x, points[i].y);
  23759. }
  23760. },
  23761. moveTo: function (x, y) {
  23762. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23763. },
  23764. lineTo: function (x, y) {
  23765. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23766. this.curves.push(curve);
  23767. this.currentPoint.set(x, y);
  23768. },
  23769. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23770. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23771. this.curves.push(curve);
  23772. this.currentPoint.set(aX, aY);
  23773. },
  23774. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23775. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23776. this.curves.push(curve);
  23777. this.currentPoint.set(aX, aY);
  23778. },
  23779. splineThru: function (pts
  23780. /*Array of Vector*/
  23781. ) {
  23782. var npts = [this.currentPoint.clone()].concat(pts);
  23783. var curve = new SplineCurve(npts);
  23784. this.curves.push(curve);
  23785. this.currentPoint.copy(pts[pts.length - 1]);
  23786. },
  23787. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23788. var x0 = this.currentPoint.x;
  23789. var y0 = this.currentPoint.y;
  23790. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23791. },
  23792. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23793. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23794. },
  23795. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23796. var x0 = this.currentPoint.x;
  23797. var y0 = this.currentPoint.y;
  23798. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23799. },
  23800. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23801. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23802. if (this.curves.length > 0) {
  23803. // if a previous curve is present, attempt to join
  23804. var firstPoint = curve.getPoint(0);
  23805. if (!firstPoint.equals(this.currentPoint)) {
  23806. this.lineTo(firstPoint.x, firstPoint.y);
  23807. }
  23808. }
  23809. this.curves.push(curve);
  23810. var lastPoint = curve.getPoint(1);
  23811. this.currentPoint.copy(lastPoint);
  23812. },
  23813. copy: function (source) {
  23814. CurvePath.prototype.copy.call(this, source);
  23815. this.currentPoint.copy(source.currentPoint);
  23816. return this;
  23817. },
  23818. toJSON: function () {
  23819. var data = CurvePath.prototype.toJSON.call(this);
  23820. data.currentPoint = this.currentPoint.toArray();
  23821. return data;
  23822. },
  23823. fromJSON: function (json) {
  23824. CurvePath.prototype.fromJSON.call(this, json);
  23825. this.currentPoint.fromArray(json.currentPoint);
  23826. return this;
  23827. }
  23828. });
  23829. /**
  23830. * @author zz85 / http://www.lab4games.net/zz85/blog
  23831. * Defines a 2d shape plane using paths.
  23832. **/
  23833. // STEP 1 Create a path.
  23834. // STEP 2 Turn path into shape.
  23835. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  23836. // STEP 3a - Extract points from each shape, turn to vertices
  23837. // STEP 3b - Triangulate each shape, add faces.
  23838. function Shape(points) {
  23839. Path.call(this, points);
  23840. this.uuid = _Math.generateUUID();
  23841. this.type = 'Shape';
  23842. this.holes = [];
  23843. }
  23844. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23845. constructor: Shape,
  23846. getPointsHoles: function (divisions) {
  23847. var holesPts = [];
  23848. for (var i = 0, l = this.holes.length; i < l; i++) {
  23849. holesPts[i] = this.holes[i].getPoints(divisions);
  23850. }
  23851. return holesPts;
  23852. },
  23853. // get points of shape and holes (keypoints based on segments parameter)
  23854. extractPoints: function (divisions) {
  23855. return {
  23856. shape: this.getPoints(divisions),
  23857. holes: this.getPointsHoles(divisions)
  23858. };
  23859. },
  23860. copy: function (source) {
  23861. Path.prototype.copy.call(this, source);
  23862. this.holes = [];
  23863. for (var i = 0, l = source.holes.length; i < l; i++) {
  23864. var hole = source.holes[i];
  23865. this.holes.push(hole.clone());
  23866. }
  23867. return this;
  23868. },
  23869. toJSON: function () {
  23870. var data = Path.prototype.toJSON.call(this);
  23871. data.uuid = this.uuid;
  23872. data.holes = [];
  23873. for (var i = 0, l = this.holes.length; i < l; i++) {
  23874. var hole = this.holes[i];
  23875. data.holes.push(hole.toJSON());
  23876. }
  23877. return data;
  23878. },
  23879. fromJSON: function (json) {
  23880. Path.prototype.fromJSON.call(this, json);
  23881. this.uuid = json.uuid;
  23882. this.holes = [];
  23883. for (var i = 0, l = json.holes.length; i < l; i++) {
  23884. var hole = json.holes[i];
  23885. this.holes.push(new Path().fromJSON(hole));
  23886. }
  23887. return this;
  23888. }
  23889. });
  23890. /**
  23891. * @author mrdoob / http://mrdoob.com/
  23892. * @author alteredq / http://alteredqualia.com/
  23893. */
  23894. function Light(color, intensity) {
  23895. Object3D.call(this);
  23896. this.type = 'Light';
  23897. this.color = new Color(color);
  23898. this.intensity = intensity !== undefined ? intensity : 1;
  23899. this.receiveShadow = undefined;
  23900. }
  23901. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23902. constructor: Light,
  23903. isLight: true,
  23904. copy: function (source) {
  23905. Object3D.prototype.copy.call(this, source);
  23906. this.color.copy(source.color);
  23907. this.intensity = source.intensity;
  23908. return this;
  23909. },
  23910. toJSON: function (meta) {
  23911. var data = Object3D.prototype.toJSON.call(this, meta);
  23912. data.object.color = this.color.getHex();
  23913. data.object.intensity = this.intensity;
  23914. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23915. if (this.distance !== undefined) data.object.distance = this.distance;
  23916. if (this.angle !== undefined) data.object.angle = this.angle;
  23917. if (this.decay !== undefined) data.object.decay = this.decay;
  23918. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23919. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23920. return data;
  23921. }
  23922. });
  23923. /**
  23924. * @author alteredq / http://alteredqualia.com/
  23925. */
  23926. function HemisphereLight(skyColor, groundColor, intensity) {
  23927. Light.call(this, skyColor, intensity);
  23928. this.type = 'HemisphereLight';
  23929. this.castShadow = undefined;
  23930. this.position.copy(Object3D.DefaultUp);
  23931. this.updateMatrix();
  23932. this.groundColor = new Color(groundColor);
  23933. }
  23934. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23935. constructor: HemisphereLight,
  23936. isHemisphereLight: true,
  23937. copy: function (source) {
  23938. Light.prototype.copy.call(this, source);
  23939. this.groundColor.copy(source.groundColor);
  23940. return this;
  23941. }
  23942. });
  23943. /**
  23944. * @author mrdoob / http://mrdoob.com/
  23945. */
  23946. function LightShadow(camera) {
  23947. this.camera = camera;
  23948. this.bias = 0;
  23949. this.radius = 1;
  23950. this.mapSize = new Vector2(512, 512);
  23951. this.map = null;
  23952. this.mapPass = null;
  23953. this.matrix = new Matrix4();
  23954. this._frustum = new Frustum();
  23955. this._frameExtents = new Vector2(1, 1);
  23956. this._viewportCount = 1;
  23957. this._viewports = [new Vector4(0, 0, 1, 1)];
  23958. }
  23959. Object.assign(LightShadow.prototype, {
  23960. _projScreenMatrix: new Matrix4(),
  23961. _lightPositionWorld: new Vector3(),
  23962. _lookTarget: new Vector3(),
  23963. getViewportCount: function () {
  23964. return this._viewportCount;
  23965. },
  23966. getFrustum: function () {
  23967. return this._frustum;
  23968. },
  23969. updateMatrices: function (light) {
  23970. var shadowCamera = this.camera,
  23971. shadowMatrix = this.matrix,
  23972. projScreenMatrix = this._projScreenMatrix,
  23973. lookTarget = this._lookTarget,
  23974. lightPositionWorld = this._lightPositionWorld;
  23975. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23976. shadowCamera.position.copy(lightPositionWorld);
  23977. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23978. shadowCamera.lookAt(lookTarget);
  23979. shadowCamera.updateMatrixWorld();
  23980. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23981. this._frustum.setFromMatrix(projScreenMatrix);
  23982. 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);
  23983. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23984. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23985. },
  23986. getViewport: function (viewportIndex) {
  23987. return this._viewports[viewportIndex];
  23988. },
  23989. getFrameExtents: function () {
  23990. return this._frameExtents;
  23991. },
  23992. copy: function (source) {
  23993. this.camera = source.camera.clone();
  23994. this.bias = source.bias;
  23995. this.radius = source.radius;
  23996. this.mapSize.copy(source.mapSize);
  23997. return this;
  23998. },
  23999. clone: function () {
  24000. return new this.constructor().copy(this);
  24001. },
  24002. toJSON: function () {
  24003. var object = {};
  24004. if (this.bias !== 0) object.bias = this.bias;
  24005. if (this.radius !== 1) object.radius = this.radius;
  24006. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  24007. object.camera = this.camera.toJSON(false).object;
  24008. delete object.camera.matrix;
  24009. return object;
  24010. }
  24011. });
  24012. /**
  24013. * @author mrdoob / http://mrdoob.com/
  24014. */
  24015. function SpotLightShadow() {
  24016. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  24017. }
  24018. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24019. constructor: SpotLightShadow,
  24020. isSpotLightShadow: true,
  24021. updateMatrices: function (light, viewCamera, viewportIndex) {
  24022. var camera = this.camera;
  24023. var fov = _Math.RAD2DEG * 2 * light.angle;
  24024. var aspect = this.mapSize.width / this.mapSize.height;
  24025. var far = light.distance || camera.far;
  24026. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  24027. camera.fov = fov;
  24028. camera.aspect = aspect;
  24029. camera.far = far;
  24030. camera.updateProjectionMatrix();
  24031. }
  24032. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24033. }
  24034. });
  24035. /**
  24036. * @author alteredq / http://alteredqualia.com/
  24037. */
  24038. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  24039. Light.call(this, color, intensity);
  24040. this.type = 'SpotLight';
  24041. this.position.copy(Object3D.DefaultUp);
  24042. this.updateMatrix();
  24043. this.target = new Object3D();
  24044. Object.defineProperty(this, 'power', {
  24045. get: function () {
  24046. // intensity = power per solid angle.
  24047. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24048. return this.intensity * Math.PI;
  24049. },
  24050. set: function (power) {
  24051. // intensity = power per solid angle.
  24052. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24053. this.intensity = power / Math.PI;
  24054. }
  24055. });
  24056. this.distance = distance !== undefined ? distance : 0;
  24057. this.angle = angle !== undefined ? angle : Math.PI / 3;
  24058. this.penumbra = penumbra !== undefined ? penumbra : 0;
  24059. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24060. this.shadow = new SpotLightShadow();
  24061. }
  24062. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  24063. constructor: SpotLight,
  24064. isSpotLight: true,
  24065. copy: function (source) {
  24066. Light.prototype.copy.call(this, source);
  24067. this.distance = source.distance;
  24068. this.angle = source.angle;
  24069. this.penumbra = source.penumbra;
  24070. this.decay = source.decay;
  24071. this.target = source.target.clone();
  24072. this.shadow = source.shadow.clone();
  24073. return this;
  24074. }
  24075. });
  24076. function PointLightShadow() {
  24077. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  24078. this._frameExtents = new Vector2(4, 2);
  24079. this._viewportCount = 6;
  24080. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  24081. // following orientation:
  24082. //
  24083. // xzXZ
  24084. // y Y
  24085. //
  24086. // X - Positive x direction
  24087. // x - Negative x direction
  24088. // Y - Positive y direction
  24089. // y - Negative y direction
  24090. // Z - Positive z direction
  24091. // z - Negative z direction
  24092. // positive X
  24093. new Vector4(2, 1, 1, 1), // negative X
  24094. new Vector4(0, 1, 1, 1), // positive Z
  24095. new Vector4(3, 1, 1, 1), // negative Z
  24096. new Vector4(1, 1, 1, 1), // positive Y
  24097. new Vector4(3, 0, 1, 1), // negative Y
  24098. new Vector4(1, 0, 1, 1)];
  24099. 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)];
  24100. 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)];
  24101. }
  24102. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24103. constructor: PointLightShadow,
  24104. isPointLightShadow: true,
  24105. updateMatrices: function (light, viewCamera, viewportIndex) {
  24106. var camera = this.camera,
  24107. shadowMatrix = this.matrix,
  24108. lightPositionWorld = this._lightPositionWorld,
  24109. lookTarget = this._lookTarget,
  24110. projScreenMatrix = this._projScreenMatrix;
  24111. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  24112. camera.position.copy(lightPositionWorld);
  24113. lookTarget.copy(camera.position);
  24114. lookTarget.add(this._cubeDirections[viewportIndex]);
  24115. camera.up.copy(this._cubeUps[viewportIndex]);
  24116. camera.lookAt(lookTarget);
  24117. camera.updateMatrixWorld();
  24118. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  24119. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  24120. this._frustum.setFromMatrix(projScreenMatrix);
  24121. }
  24122. });
  24123. /**
  24124. * @author mrdoob / http://mrdoob.com/
  24125. */
  24126. function PointLight(color, intensity, distance, decay) {
  24127. Light.call(this, color, intensity);
  24128. this.type = 'PointLight';
  24129. Object.defineProperty(this, 'power', {
  24130. get: function () {
  24131. // intensity = power per solid angle.
  24132. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24133. return this.intensity * 4 * Math.PI;
  24134. },
  24135. set: function (power) {
  24136. // intensity = power per solid angle.
  24137. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24138. this.intensity = power / (4 * Math.PI);
  24139. }
  24140. });
  24141. this.distance = distance !== undefined ? distance : 0;
  24142. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  24143. this.shadow = new PointLightShadow();
  24144. }
  24145. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  24146. constructor: PointLight,
  24147. isPointLight: true,
  24148. copy: function (source) {
  24149. Light.prototype.copy.call(this, source);
  24150. this.distance = source.distance;
  24151. this.decay = source.decay;
  24152. this.shadow = source.shadow.clone();
  24153. return this;
  24154. }
  24155. });
  24156. /**
  24157. * @author alteredq / http://alteredqualia.com/
  24158. * @author arose / http://github.com/arose
  24159. */
  24160. function OrthographicCamera(left, right, top, bottom, near, far) {
  24161. Camera.call(this);
  24162. this.type = 'OrthographicCamera';
  24163. this.zoom = 1;
  24164. this.view = null;
  24165. this.left = left !== undefined ? left : -1;
  24166. this.right = right !== undefined ? right : 1;
  24167. this.top = top !== undefined ? top : 1;
  24168. this.bottom = bottom !== undefined ? bottom : -1;
  24169. this.near = near !== undefined ? near : 0.1;
  24170. this.far = far !== undefined ? far : 2000;
  24171. this.updateProjectionMatrix();
  24172. }
  24173. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  24174. constructor: OrthographicCamera,
  24175. isOrthographicCamera: true,
  24176. copy: function (source, recursive) {
  24177. Camera.prototype.copy.call(this, source, recursive);
  24178. this.left = source.left;
  24179. this.right = source.right;
  24180. this.top = source.top;
  24181. this.bottom = source.bottom;
  24182. this.near = source.near;
  24183. this.far = source.far;
  24184. this.zoom = source.zoom;
  24185. this.view = source.view === null ? null : Object.assign({}, source.view);
  24186. return this;
  24187. },
  24188. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  24189. if (this.view === null) {
  24190. this.view = {
  24191. enabled: true,
  24192. fullWidth: 1,
  24193. fullHeight: 1,
  24194. offsetX: 0,
  24195. offsetY: 0,
  24196. width: 1,
  24197. height: 1
  24198. };
  24199. }
  24200. this.view.enabled = true;
  24201. this.view.fullWidth = fullWidth;
  24202. this.view.fullHeight = fullHeight;
  24203. this.view.offsetX = x;
  24204. this.view.offsetY = y;
  24205. this.view.width = width;
  24206. this.view.height = height;
  24207. this.updateProjectionMatrix();
  24208. },
  24209. clearViewOffset: function () {
  24210. if (this.view !== null) {
  24211. this.view.enabled = false;
  24212. }
  24213. this.updateProjectionMatrix();
  24214. },
  24215. updateProjectionMatrix: function () {
  24216. var dx = (this.right - this.left) / (2 * this.zoom);
  24217. var dy = (this.top - this.bottom) / (2 * this.zoom);
  24218. var cx = (this.right + this.left) / 2;
  24219. var cy = (this.top + this.bottom) / 2;
  24220. var left = cx - dx;
  24221. var right = cx + dx;
  24222. var top = cy + dy;
  24223. var bottom = cy - dy;
  24224. if (this.view !== null && this.view.enabled) {
  24225. var zoomW = this.zoom / (this.view.width / this.view.fullWidth);
  24226. var zoomH = this.zoom / (this.view.height / this.view.fullHeight);
  24227. var scaleW = (this.right - this.left) / this.view.width;
  24228. var scaleH = (this.top - this.bottom) / this.view.height;
  24229. left += scaleW * (this.view.offsetX / zoomW);
  24230. right = left + scaleW * (this.view.width / zoomW);
  24231. top -= scaleH * (this.view.offsetY / zoomH);
  24232. bottom = top - scaleH * (this.view.height / zoomH);
  24233. }
  24234. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  24235. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  24236. },
  24237. toJSON: function (meta) {
  24238. var data = Object3D.prototype.toJSON.call(this, meta);
  24239. data.object.zoom = this.zoom;
  24240. data.object.left = this.left;
  24241. data.object.right = this.right;
  24242. data.object.top = this.top;
  24243. data.object.bottom = this.bottom;
  24244. data.object.near = this.near;
  24245. data.object.far = this.far;
  24246. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  24247. return data;
  24248. }
  24249. });
  24250. /**
  24251. * @author mrdoob / http://mrdoob.com/
  24252. */
  24253. function DirectionalLightShadow() {
  24254. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  24255. }
  24256. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  24257. constructor: DirectionalLightShadow,
  24258. isDirectionalLightShadow: true,
  24259. updateMatrices: function (light, viewCamera, viewportIndex) {
  24260. LightShadow.prototype.updateMatrices.call(this, light, viewCamera, viewportIndex);
  24261. }
  24262. });
  24263. /**
  24264. * @author mrdoob / http://mrdoob.com/
  24265. * @author alteredq / http://alteredqualia.com/
  24266. */
  24267. function DirectionalLight(color, intensity) {
  24268. Light.call(this, color, intensity);
  24269. this.type = 'DirectionalLight';
  24270. this.position.copy(Object3D.DefaultUp);
  24271. this.updateMatrix();
  24272. this.target = new Object3D();
  24273. this.shadow = new DirectionalLightShadow();
  24274. }
  24275. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  24276. constructor: DirectionalLight,
  24277. isDirectionalLight: true,
  24278. copy: function (source) {
  24279. Light.prototype.copy.call(this, source);
  24280. this.target = source.target.clone();
  24281. this.shadow = source.shadow.clone();
  24282. return this;
  24283. }
  24284. });
  24285. /**
  24286. * @author mrdoob / http://mrdoob.com/
  24287. */
  24288. function AmbientLight(color, intensity) {
  24289. Light.call(this, color, intensity);
  24290. this.type = 'AmbientLight';
  24291. this.castShadow = undefined;
  24292. }
  24293. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  24294. constructor: AmbientLight,
  24295. isAmbientLight: true
  24296. });
  24297. /**
  24298. * @author abelnation / http://github.com/abelnation
  24299. */
  24300. function RectAreaLight(color, intensity, width, height) {
  24301. Light.call(this, color, intensity);
  24302. this.type = 'RectAreaLight';
  24303. this.width = width !== undefined ? width : 10;
  24304. this.height = height !== undefined ? height : 10;
  24305. }
  24306. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  24307. constructor: RectAreaLight,
  24308. isRectAreaLight: true,
  24309. copy: function (source) {
  24310. Light.prototype.copy.call(this, source);
  24311. this.width = source.width;
  24312. this.height = source.height;
  24313. return this;
  24314. },
  24315. toJSON: function (meta) {
  24316. var data = Light.prototype.toJSON.call(this, meta);
  24317. data.object.width = this.width;
  24318. data.object.height = this.height;
  24319. return data;
  24320. }
  24321. });
  24322. /**
  24323. * @author mrdoob / http://mrdoob.com/
  24324. */
  24325. function MaterialLoader(manager) {
  24326. Loader.call(this, manager);
  24327. this.textures = {};
  24328. }
  24329. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24330. constructor: MaterialLoader,
  24331. load: function (url, onLoad, onProgress, onError) {
  24332. var scope = this;
  24333. var loader = new FileLoader(scope.manager);
  24334. loader.setPath(scope.path);
  24335. loader.load(url, function (text) {
  24336. onLoad(scope.parse(JSON.parse(text)));
  24337. }, onProgress, onError);
  24338. },
  24339. parse: function (json) {
  24340. var textures = this.textures;
  24341. function getTexture(name) {
  24342. if (textures[name] === undefined) {
  24343. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24344. }
  24345. return textures[name];
  24346. }
  24347. var material = new Materials[json.type]();
  24348. if (json.uuid !== undefined) material.uuid = json.uuid;
  24349. if (json.name !== undefined) material.name = json.name;
  24350. if (json.color !== undefined) material.color.setHex(json.color);
  24351. if (json.roughness !== undefined) material.roughness = json.roughness;
  24352. if (json.metalness !== undefined) material.metalness = json.metalness;
  24353. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  24354. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  24355. if (json.specular !== undefined) material.specular.setHex(json.specular);
  24356. if (json.shininess !== undefined) material.shininess = json.shininess;
  24357. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24358. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24359. if (json.vertexColors !== undefined) material.vertexColors = json.vertexColors;
  24360. if (json.fog !== undefined) material.fog = json.fog;
  24361. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24362. if (json.blending !== undefined) material.blending = json.blending;
  24363. if (json.combine !== undefined) material.combine = json.combine;
  24364. if (json.side !== undefined) material.side = json.side;
  24365. if (json.opacity !== undefined) material.opacity = json.opacity;
  24366. if (json.transparent !== undefined) material.transparent = json.transparent;
  24367. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24368. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24369. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24370. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24371. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24372. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24373. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24374. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24375. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24376. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24377. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24378. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24379. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24380. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24381. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24382. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24383. if (json.rotation !== undefined) material.rotation = json.rotation;
  24384. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24385. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24386. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24387. if (json.scale !== undefined) material.scale = json.scale;
  24388. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24389. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24390. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24391. if (json.skinning !== undefined) material.skinning = json.skinning;
  24392. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  24393. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  24394. if (json.dithering !== undefined) material.dithering = json.dithering;
  24395. if (json.visible !== undefined) material.visible = json.visible;
  24396. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24397. if (json.userData !== undefined) material.userData = json.userData; // Shader Material
  24398. if (json.uniforms !== undefined) {
  24399. for (var name in json.uniforms) {
  24400. var uniform = json.uniforms[name];
  24401. material.uniforms[name] = {};
  24402. switch (uniform.type) {
  24403. case 't':
  24404. material.uniforms[name].value = getTexture(uniform.value);
  24405. break;
  24406. case 'c':
  24407. material.uniforms[name].value = new Color().setHex(uniform.value);
  24408. break;
  24409. case 'v2':
  24410. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24411. break;
  24412. case 'v3':
  24413. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24414. break;
  24415. case 'v4':
  24416. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24417. break;
  24418. case 'm3':
  24419. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24420. case 'm4':
  24421. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24422. break;
  24423. default:
  24424. material.uniforms[name].value = uniform.value;
  24425. }
  24426. }
  24427. }
  24428. if (json.defines !== undefined) material.defines = json.defines;
  24429. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24430. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24431. if (json.extensions !== undefined) {
  24432. for (var key in json.extensions) {
  24433. material.extensions[key] = json.extensions[key];
  24434. }
  24435. } // Deprecated
  24436. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24437. // for PointsMaterial
  24438. if (json.size !== undefined) material.size = json.size;
  24439. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24440. if (json.map !== undefined) material.map = getTexture(json.map);
  24441. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24442. if (json.alphaMap !== undefined) {
  24443. material.alphaMap = getTexture(json.alphaMap);
  24444. material.transparent = true;
  24445. }
  24446. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24447. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24448. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24449. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24450. if (json.normalScale !== undefined) {
  24451. var normalScale = json.normalScale;
  24452. if (Array.isArray(normalScale) === false) {
  24453. // Blender exporter used to export a scalar. See #7459
  24454. normalScale = [normalScale, normalScale];
  24455. }
  24456. material.normalScale = new Vector2().fromArray(normalScale);
  24457. }
  24458. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24459. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24460. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24461. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24462. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24463. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24464. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24465. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24466. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24467. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24468. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24469. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24470. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24471. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24472. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24473. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24474. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24475. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24476. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24477. return material;
  24478. },
  24479. setTextures: function (value) {
  24480. this.textures = value;
  24481. return this;
  24482. }
  24483. });
  24484. /**
  24485. * @author Don McCurdy / https://www.donmccurdy.com
  24486. */
  24487. var LoaderUtils = {
  24488. decodeText: function (array) {
  24489. if (typeof TextDecoder !== 'undefined') {
  24490. return new TextDecoder().decode(array);
  24491. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24492. // throws a "maximum call stack size exceeded" error for large arrays.
  24493. var s = '';
  24494. for (var i = 0, il = array.length; i < il; i++) {
  24495. // Implicitly assumes little-endian.
  24496. s += String.fromCharCode(array[i]);
  24497. }
  24498. try {
  24499. // merges multi-byte utf-8 characters.
  24500. return decodeURIComponent(escape(s));
  24501. } catch (e) {
  24502. // see #16358
  24503. return s;
  24504. }
  24505. },
  24506. extractUrlBase: function (url) {
  24507. var index = url.lastIndexOf('/');
  24508. if (index === -1) return './';
  24509. return url.substr(0, index + 1);
  24510. }
  24511. };
  24512. /**
  24513. * @author benaadams / https://twitter.com/ben_a_adams
  24514. */
  24515. exports.LoaderUtils = LoaderUtils;
  24516. function InstancedBufferGeometry() {
  24517. BufferGeometry.call(this);
  24518. this.type = 'InstancedBufferGeometry';
  24519. this.maxInstancedCount = undefined;
  24520. }
  24521. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  24522. constructor: InstancedBufferGeometry,
  24523. isInstancedBufferGeometry: true,
  24524. copy: function (source) {
  24525. BufferGeometry.prototype.copy.call(this, source);
  24526. this.maxInstancedCount = source.maxInstancedCount;
  24527. return this;
  24528. },
  24529. clone: function () {
  24530. return new this.constructor().copy(this);
  24531. },
  24532. toJSON: function () {
  24533. var data = BufferGeometry.prototype.toJSON.call(this);
  24534. data.maxInstancedCount = this.maxInstancedCount;
  24535. data.isInstancedBufferGeometry = true;
  24536. return data;
  24537. }
  24538. });
  24539. /**
  24540. * @author benaadams / https://twitter.com/ben_a_adams
  24541. */
  24542. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  24543. if (typeof normalized === 'number') {
  24544. meshPerAttribute = normalized;
  24545. normalized = false;
  24546. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  24547. }
  24548. BufferAttribute.call(this, array, itemSize, normalized);
  24549. this.meshPerAttribute = meshPerAttribute || 1;
  24550. }
  24551. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  24552. constructor: InstancedBufferAttribute,
  24553. isInstancedBufferAttribute: true,
  24554. copy: function (source) {
  24555. BufferAttribute.prototype.copy.call(this, source);
  24556. this.meshPerAttribute = source.meshPerAttribute;
  24557. return this;
  24558. },
  24559. toJSON: function () {
  24560. var data = BufferAttribute.prototype.toJSON.call(this);
  24561. data.meshPerAttribute = this.meshPerAttribute;
  24562. data.isInstancedBufferAttribute = true;
  24563. return data;
  24564. }
  24565. });
  24566. /**
  24567. * @author mrdoob / http://mrdoob.com/
  24568. */
  24569. function BufferGeometryLoader(manager) {
  24570. Loader.call(this, manager);
  24571. }
  24572. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24573. constructor: BufferGeometryLoader,
  24574. load: function (url, onLoad, onProgress, onError) {
  24575. var scope = this;
  24576. var loader = new FileLoader(scope.manager);
  24577. loader.setPath(scope.path);
  24578. loader.load(url, function (text) {
  24579. onLoad(scope.parse(JSON.parse(text)));
  24580. }, onProgress, onError);
  24581. },
  24582. parse: function (json) {
  24583. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24584. var index = json.data.index;
  24585. if (index !== undefined) {
  24586. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  24587. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24588. }
  24589. var attributes = json.data.attributes;
  24590. for (var key in attributes) {
  24591. var attribute = attributes[key];
  24592. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24593. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24594. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24595. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24596. geometry.addAttribute(key, bufferAttribute);
  24597. }
  24598. var morphAttributes = json.data.morphAttributes;
  24599. if (morphAttributes) {
  24600. for (var key in morphAttributes) {
  24601. var attributeArray = morphAttributes[key];
  24602. var array = [];
  24603. for (var i = 0, il = attributeArray.length; i < il; i++) {
  24604. var attribute = attributeArray[i];
  24605. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  24606. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24607. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24608. array.push(bufferAttribute);
  24609. }
  24610. geometry.morphAttributes[key] = array;
  24611. }
  24612. }
  24613. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24614. if (groups !== undefined) {
  24615. for (var i = 0, n = groups.length; i !== n; ++i) {
  24616. var group = groups[i];
  24617. geometry.addGroup(group.start, group.count, group.materialIndex);
  24618. }
  24619. }
  24620. var boundingSphere = json.data.boundingSphere;
  24621. if (boundingSphere !== undefined) {
  24622. var center = new Vector3();
  24623. if (boundingSphere.center !== undefined) {
  24624. center.fromArray(boundingSphere.center);
  24625. }
  24626. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24627. }
  24628. if (json.name) geometry.name = json.name;
  24629. if (json.userData) geometry.userData = json.userData;
  24630. return geometry;
  24631. }
  24632. });
  24633. var TYPED_ARRAYS = {
  24634. Int8Array: Int8Array,
  24635. Uint8Array: Uint8Array,
  24636. // Workaround for IE11 pre KB2929437. See #11440
  24637. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  24638. Int16Array: Int16Array,
  24639. Uint16Array: Uint16Array,
  24640. Int32Array: Int32Array,
  24641. Uint32Array: Uint32Array,
  24642. Float32Array: Float32Array,
  24643. Float64Array: Float64Array
  24644. };
  24645. /**
  24646. * @author mrdoob / http://mrdoob.com/
  24647. */
  24648. function ObjectLoader(manager) {
  24649. Loader.call(this, manager);
  24650. }
  24651. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24652. constructor: ObjectLoader,
  24653. load: function (url, onLoad, onProgress, onError) {
  24654. var scope = this;
  24655. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24656. this.resourcePath = this.resourcePath || path;
  24657. var loader = new FileLoader(scope.manager);
  24658. loader.setPath(this.path);
  24659. loader.load(url, function (text) {
  24660. var json = null;
  24661. try {
  24662. json = JSON.parse(text);
  24663. } catch (error) {
  24664. if (onError !== undefined) onError(error);
  24665. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24666. return;
  24667. }
  24668. var metadata = json.metadata;
  24669. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24670. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24671. return;
  24672. }
  24673. scope.parse(json, onLoad);
  24674. }, onProgress, onError);
  24675. },
  24676. parse: function (json, onLoad) {
  24677. var shapes = this.parseShape(json.shapes);
  24678. var geometries = this.parseGeometries(json.geometries, shapes);
  24679. var images = this.parseImages(json.images, function () {
  24680. if (onLoad !== undefined) onLoad(object);
  24681. });
  24682. var textures = this.parseTextures(json.textures, images);
  24683. var materials = this.parseMaterials(json.materials, textures);
  24684. var object = this.parseObject(json.object, geometries, materials);
  24685. if (json.animations) {
  24686. object.animations = this.parseAnimations(json.animations);
  24687. }
  24688. if (json.images === undefined || json.images.length === 0) {
  24689. if (onLoad !== undefined) onLoad(object);
  24690. }
  24691. return object;
  24692. },
  24693. parseShape: function (json) {
  24694. var shapes = {};
  24695. if (json !== undefined) {
  24696. for (var i = 0, l = json.length; i < l; i++) {
  24697. var shape = new Shape().fromJSON(json[i]);
  24698. shapes[shape.uuid] = shape;
  24699. }
  24700. }
  24701. return shapes;
  24702. },
  24703. parseGeometries: function (json, shapes) {
  24704. var geometries = {};
  24705. if (json !== undefined) {
  24706. var bufferGeometryLoader = new BufferGeometryLoader();
  24707. for (var i = 0, l = json.length; i < l; i++) {
  24708. var geometry;
  24709. var data = json[i];
  24710. switch (data.type) {
  24711. case 'PlaneGeometry':
  24712. case 'PlaneBufferGeometry':
  24713. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24714. break;
  24715. case 'BoxGeometry':
  24716. case 'BoxBufferGeometry':
  24717. case 'CubeGeometry':
  24718. // backwards compatible
  24719. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24720. break;
  24721. case 'CircleGeometry':
  24722. case 'CircleBufferGeometry':
  24723. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24724. break;
  24725. case 'CylinderGeometry':
  24726. case 'CylinderBufferGeometry':
  24727. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24728. break;
  24729. case 'ConeGeometry':
  24730. case 'ConeBufferGeometry':
  24731. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24732. break;
  24733. case 'SphereGeometry':
  24734. case 'SphereBufferGeometry':
  24735. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24736. break;
  24737. case 'DodecahedronGeometry':
  24738. case 'DodecahedronBufferGeometry':
  24739. case 'IcosahedronGeometry':
  24740. case 'IcosahedronBufferGeometry':
  24741. case 'OctahedronGeometry':
  24742. case 'OctahedronBufferGeometry':
  24743. case 'TetrahedronGeometry':
  24744. case 'TetrahedronBufferGeometry':
  24745. geometry = new Geometries[data.type](data.radius, data.detail);
  24746. break;
  24747. case 'RingGeometry':
  24748. case 'RingBufferGeometry':
  24749. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24750. break;
  24751. case 'TorusGeometry':
  24752. case 'TorusBufferGeometry':
  24753. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24754. break;
  24755. case 'TorusKnotGeometry':
  24756. case 'TorusKnotBufferGeometry':
  24757. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24758. break;
  24759. case 'TubeGeometry':
  24760. case 'TubeBufferGeometry':
  24761. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24762. // User defined curves or instances of CurvePath will not be deserialized.
  24763. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24764. break;
  24765. case 'LatheGeometry':
  24766. case 'LatheBufferGeometry':
  24767. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24768. break;
  24769. case 'PolyhedronGeometry':
  24770. case 'PolyhedronBufferGeometry':
  24771. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24772. break;
  24773. case 'ShapeGeometry':
  24774. case 'ShapeBufferGeometry':
  24775. var geometryShapes = [];
  24776. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24777. var shape = shapes[data.shapes[j]];
  24778. geometryShapes.push(shape);
  24779. }
  24780. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24781. break;
  24782. case 'ExtrudeGeometry':
  24783. case 'ExtrudeBufferGeometry':
  24784. var geometryShapes = [];
  24785. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24786. var shape = shapes[data.shapes[j]];
  24787. geometryShapes.push(shape);
  24788. }
  24789. var extrudePath = data.options.extrudePath;
  24790. if (extrudePath !== undefined) {
  24791. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24792. }
  24793. geometry = new Geometries[data.type](geometryShapes, data.options);
  24794. break;
  24795. case 'BufferGeometry':
  24796. case 'InstancedBufferGeometry':
  24797. geometry = bufferGeometryLoader.parse(data);
  24798. break;
  24799. case 'Geometry':
  24800. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  24801. var geometryLoader = new THREE.LegacyJSONLoader();
  24802. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  24803. } else {
  24804. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  24805. }
  24806. break;
  24807. default:
  24808. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24809. continue;
  24810. }
  24811. geometry.uuid = data.uuid;
  24812. if (data.name !== undefined) geometry.name = data.name;
  24813. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24814. geometries[data.uuid] = geometry;
  24815. }
  24816. }
  24817. return geometries;
  24818. },
  24819. parseMaterials: function (json, textures) {
  24820. var cache = {}; // MultiMaterial
  24821. var materials = {};
  24822. if (json !== undefined) {
  24823. var loader = new MaterialLoader();
  24824. loader.setTextures(textures);
  24825. for (var i = 0, l = json.length; i < l; i++) {
  24826. var data = json[i];
  24827. if (data.type === 'MultiMaterial') {
  24828. // Deprecated
  24829. var array = [];
  24830. for (var j = 0; j < data.materials.length; j++) {
  24831. var material = data.materials[j];
  24832. if (cache[material.uuid] === undefined) {
  24833. cache[material.uuid] = loader.parse(material);
  24834. }
  24835. array.push(cache[material.uuid]);
  24836. }
  24837. materials[data.uuid] = array;
  24838. } else {
  24839. if (cache[data.uuid] === undefined) {
  24840. cache[data.uuid] = loader.parse(data);
  24841. }
  24842. materials[data.uuid] = cache[data.uuid];
  24843. }
  24844. }
  24845. }
  24846. return materials;
  24847. },
  24848. parseAnimations: function (json) {
  24849. var animations = [];
  24850. for (var i = 0; i < json.length; i++) {
  24851. var data = json[i];
  24852. var clip = AnimationClip.parse(data);
  24853. if (data.uuid !== undefined) clip.uuid = data.uuid;
  24854. animations.push(clip);
  24855. }
  24856. return animations;
  24857. },
  24858. parseImages: function (json, onLoad) {
  24859. var scope = this;
  24860. var images = {};
  24861. function loadImage(url) {
  24862. scope.manager.itemStart(url);
  24863. return loader.load(url, function () {
  24864. scope.manager.itemEnd(url);
  24865. }, undefined, function () {
  24866. scope.manager.itemError(url);
  24867. scope.manager.itemEnd(url);
  24868. });
  24869. }
  24870. if (json !== undefined && json.length > 0) {
  24871. var manager = new LoadingManager(onLoad);
  24872. var loader = new ImageLoader(manager);
  24873. loader.setCrossOrigin(this.crossOrigin);
  24874. for (var i = 0, il = json.length; i < il; i++) {
  24875. var image = json[i];
  24876. var url = image.url;
  24877. if (Array.isArray(url)) {
  24878. // load array of images e.g CubeTexture
  24879. images[image.uuid] = [];
  24880. for (var j = 0, jl = url.length; j < jl; j++) {
  24881. var currentUrl = url[j];
  24882. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  24883. images[image.uuid].push(loadImage(path));
  24884. }
  24885. } else {
  24886. // load single image
  24887. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  24888. images[image.uuid] = loadImage(path);
  24889. }
  24890. }
  24891. }
  24892. return images;
  24893. },
  24894. parseTextures: function (json, images) {
  24895. function parseConstant(value, type) {
  24896. if (typeof value === 'number') return value;
  24897. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24898. return type[value];
  24899. }
  24900. var textures = {};
  24901. if (json !== undefined) {
  24902. for (var i = 0, l = json.length; i < l; i++) {
  24903. var data = json[i];
  24904. if (data.image === undefined) {
  24905. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24906. }
  24907. if (images[data.image] === undefined) {
  24908. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24909. }
  24910. var texture;
  24911. if (Array.isArray(images[data.image])) {
  24912. texture = new CubeTexture(images[data.image]);
  24913. } else {
  24914. texture = new Texture(images[data.image]);
  24915. }
  24916. texture.needsUpdate = true;
  24917. texture.uuid = data.uuid;
  24918. if (data.name !== undefined) texture.name = data.name;
  24919. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24920. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24921. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24922. if (data.center !== undefined) texture.center.fromArray(data.center);
  24923. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24924. if (data.wrap !== undefined) {
  24925. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24926. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24927. }
  24928. if (data.format !== undefined) texture.format = data.format;
  24929. if (data.type !== undefined) texture.type = data.type;
  24930. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24931. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24932. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24933. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24934. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24935. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24936. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24937. textures[data.uuid] = texture;
  24938. }
  24939. }
  24940. return textures;
  24941. },
  24942. parseObject: function (data, geometries, materials) {
  24943. var object;
  24944. function getGeometry(name) {
  24945. if (geometries[name] === undefined) {
  24946. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24947. }
  24948. return geometries[name];
  24949. }
  24950. function getMaterial(name) {
  24951. if (name === undefined) return undefined;
  24952. if (Array.isArray(name)) {
  24953. var array = [];
  24954. for (var i = 0, l = name.length; i < l; i++) {
  24955. var uuid = name[i];
  24956. if (materials[uuid] === undefined) {
  24957. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24958. }
  24959. array.push(materials[uuid]);
  24960. }
  24961. return array;
  24962. }
  24963. if (materials[name] === undefined) {
  24964. console.warn('THREE.ObjectLoader: Undefined material', name);
  24965. }
  24966. return materials[name];
  24967. }
  24968. switch (data.type) {
  24969. case 'Scene':
  24970. object = new Scene();
  24971. if (data.background !== undefined) {
  24972. if (Number.isInteger(data.background)) {
  24973. object.background = new Color(data.background);
  24974. }
  24975. }
  24976. if (data.fog !== undefined) {
  24977. if (data.fog.type === 'Fog') {
  24978. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24979. } else if (data.fog.type === 'FogExp2') {
  24980. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24981. }
  24982. }
  24983. break;
  24984. case 'PerspectiveCamera':
  24985. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24986. if (data.focus !== undefined) object.focus = data.focus;
  24987. if (data.zoom !== undefined) object.zoom = data.zoom;
  24988. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24989. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24990. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24991. break;
  24992. case 'OrthographicCamera':
  24993. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24994. if (data.zoom !== undefined) object.zoom = data.zoom;
  24995. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24996. break;
  24997. case 'AmbientLight':
  24998. object = new AmbientLight(data.color, data.intensity);
  24999. break;
  25000. case 'DirectionalLight':
  25001. object = new DirectionalLight(data.color, data.intensity);
  25002. break;
  25003. case 'PointLight':
  25004. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  25005. break;
  25006. case 'RectAreaLight':
  25007. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  25008. break;
  25009. case 'SpotLight':
  25010. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  25011. break;
  25012. case 'HemisphereLight':
  25013. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  25014. break;
  25015. case 'SkinnedMesh':
  25016. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  25017. case 'Mesh':
  25018. var geometry = getGeometry(data.geometry);
  25019. var material = getMaterial(data.material);
  25020. if (geometry.bones && geometry.bones.length > 0) {
  25021. object = new SkinnedMesh(geometry, material);
  25022. } else {
  25023. object = new Mesh(geometry, material);
  25024. }
  25025. if (data.drawMode !== undefined) object.setDrawMode(data.drawMode);
  25026. break;
  25027. case 'LOD':
  25028. object = new LOD();
  25029. break;
  25030. case 'Line':
  25031. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  25032. break;
  25033. case 'LineLoop':
  25034. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  25035. break;
  25036. case 'LineSegments':
  25037. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  25038. break;
  25039. case 'PointCloud':
  25040. case 'Points':
  25041. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  25042. break;
  25043. case 'Sprite':
  25044. object = new Sprite(getMaterial(data.material));
  25045. break;
  25046. case 'Group':
  25047. object = new Group();
  25048. break;
  25049. default:
  25050. object = new Object3D();
  25051. }
  25052. object.uuid = data.uuid;
  25053. if (data.name !== undefined) object.name = data.name;
  25054. if (data.matrix !== undefined) {
  25055. object.matrix.fromArray(data.matrix);
  25056. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25057. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  25058. } else {
  25059. if (data.position !== undefined) object.position.fromArray(data.position);
  25060. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  25061. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  25062. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  25063. }
  25064. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  25065. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  25066. if (data.shadow) {
  25067. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  25068. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  25069. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  25070. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  25071. }
  25072. if (data.visible !== undefined) object.visible = data.visible;
  25073. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  25074. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  25075. if (data.userData !== undefined) object.userData = data.userData;
  25076. if (data.layers !== undefined) object.layers.mask = data.layers;
  25077. if (data.children !== undefined) {
  25078. var children = data.children;
  25079. for (var i = 0; i < children.length; i++) {
  25080. object.add(this.parseObject(children[i], geometries, materials));
  25081. }
  25082. }
  25083. if (data.type === 'LOD') {
  25084. var levels = data.levels;
  25085. for (var l = 0; l < levels.length; l++) {
  25086. var level = levels[l];
  25087. var child = object.getObjectByProperty('uuid', level.object);
  25088. if (child !== undefined) {
  25089. object.addLevel(child, level.distance);
  25090. }
  25091. }
  25092. }
  25093. return object;
  25094. }
  25095. });
  25096. var TEXTURE_MAPPING = {
  25097. UVMapping: UVMapping,
  25098. CubeReflectionMapping: CubeReflectionMapping,
  25099. CubeRefractionMapping: CubeRefractionMapping,
  25100. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25101. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25102. SphericalReflectionMapping: SphericalReflectionMapping,
  25103. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25104. CubeUVRefractionMapping: CubeUVRefractionMapping
  25105. };
  25106. var TEXTURE_WRAPPING = {
  25107. RepeatWrapping: RepeatWrapping,
  25108. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25109. MirroredRepeatWrapping: MirroredRepeatWrapping
  25110. };
  25111. var TEXTURE_FILTER = {
  25112. NearestFilter: NearestFilter,
  25113. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25114. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25115. LinearFilter: LinearFilter,
  25116. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25117. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25118. };
  25119. /**
  25120. * @author thespite / http://clicktorelease.com/
  25121. */
  25122. function ImageBitmapLoader(manager) {
  25123. if (typeof createImageBitmap === 'undefined') {
  25124. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25125. }
  25126. if (typeof fetch === 'undefined') {
  25127. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25128. }
  25129. Loader.call(this, manager);
  25130. this.options = undefined;
  25131. }
  25132. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25133. constructor: ImageBitmapLoader,
  25134. setOptions: function setOptions(options) {
  25135. this.options = options;
  25136. return this;
  25137. },
  25138. load: function (url, onLoad, onProgress, onError) {
  25139. if (url === undefined) url = '';
  25140. if (this.path !== undefined) url = this.path + url;
  25141. url = this.manager.resolveURL(url);
  25142. var scope = this;
  25143. var cached = Cache.get(url);
  25144. if (cached !== undefined) {
  25145. scope.manager.itemStart(url);
  25146. setTimeout(function () {
  25147. if (onLoad) onLoad(cached);
  25148. scope.manager.itemEnd(url);
  25149. }, 0);
  25150. return cached;
  25151. }
  25152. fetch(url).then(function (res) {
  25153. return res.blob();
  25154. }).then(function (blob) {
  25155. if (scope.options === undefined) {
  25156. // Workaround for FireFox. It causes an error if you pass options.
  25157. return createImageBitmap(blob);
  25158. } else {
  25159. return createImageBitmap(blob, scope.options);
  25160. }
  25161. }).then(function (imageBitmap) {
  25162. Cache.add(url, imageBitmap);
  25163. if (onLoad) onLoad(imageBitmap);
  25164. scope.manager.itemEnd(url);
  25165. }).catch(function (e) {
  25166. if (onError) onError(e);
  25167. scope.manager.itemError(url);
  25168. scope.manager.itemEnd(url);
  25169. });
  25170. scope.manager.itemStart(url);
  25171. }
  25172. });
  25173. /**
  25174. * @author zz85 / http://www.lab4games.net/zz85/blog
  25175. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  25176. **/
  25177. function ShapePath() {
  25178. this.type = 'ShapePath';
  25179. this.color = new Color();
  25180. this.subPaths = [];
  25181. this.currentPath = null;
  25182. }
  25183. Object.assign(ShapePath.prototype, {
  25184. moveTo: function (x, y) {
  25185. this.currentPath = new Path();
  25186. this.subPaths.push(this.currentPath);
  25187. this.currentPath.moveTo(x, y);
  25188. },
  25189. lineTo: function (x, y) {
  25190. this.currentPath.lineTo(x, y);
  25191. },
  25192. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  25193. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  25194. },
  25195. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  25196. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  25197. },
  25198. splineThru: function (pts) {
  25199. this.currentPath.splineThru(pts);
  25200. },
  25201. toShapes: function (isCCW, noHoles) {
  25202. function toShapesNoHoles(inSubpaths) {
  25203. var shapes = [];
  25204. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  25205. var tmpPath = inSubpaths[i];
  25206. var tmpShape = new Shape();
  25207. tmpShape.curves = tmpPath.curves;
  25208. shapes.push(tmpShape);
  25209. }
  25210. return shapes;
  25211. }
  25212. function isPointInsidePolygon(inPt, inPolygon) {
  25213. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  25214. // toggling of inside/outside at every single! intersection point of an edge
  25215. // with the horizontal line through inPt, left of inPt
  25216. // not counting lowerY endpoints of edges and whole edges on that line
  25217. var inside = false;
  25218. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  25219. var edgeLowPt = inPolygon[p];
  25220. var edgeHighPt = inPolygon[q];
  25221. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  25222. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  25223. if (Math.abs(edgeDy) > Number.EPSILON) {
  25224. // not parallel
  25225. if (edgeDy < 0) {
  25226. edgeLowPt = inPolygon[q];
  25227. edgeDx = -edgeDx;
  25228. edgeHighPt = inPolygon[p];
  25229. edgeDy = -edgeDy;
  25230. }
  25231. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  25232. if (inPt.y === edgeLowPt.y) {
  25233. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  25234. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25235. } else {
  25236. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  25237. if (perpEdge === 0) return true; // inPt is on contour ?
  25238. if (perpEdge < 0) continue;
  25239. inside = !inside; // true intersection left of inPt
  25240. }
  25241. } else {
  25242. // parallel or collinear
  25243. if (inPt.y !== edgeLowPt.y) continue; // parallel
  25244. // edge lies on the same horizontal line as inPt
  25245. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  25246. // continue;
  25247. }
  25248. }
  25249. return inside;
  25250. }
  25251. var isClockWise = ShapeUtils.isClockWise;
  25252. var subPaths = this.subPaths;
  25253. if (subPaths.length === 0) return [];
  25254. if (noHoles === true) return toShapesNoHoles(subPaths);
  25255. var solid,
  25256. tmpPath,
  25257. tmpShape,
  25258. shapes = [];
  25259. if (subPaths.length === 1) {
  25260. tmpPath = subPaths[0];
  25261. tmpShape = new Shape();
  25262. tmpShape.curves = tmpPath.curves;
  25263. shapes.push(tmpShape);
  25264. return shapes;
  25265. }
  25266. var holesFirst = !isClockWise(subPaths[0].getPoints());
  25267. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  25268. var betterShapeHoles = [];
  25269. var newShapes = [];
  25270. var newShapeHoles = [];
  25271. var mainIdx = 0;
  25272. var tmpPoints;
  25273. newShapes[mainIdx] = undefined;
  25274. newShapeHoles[mainIdx] = [];
  25275. for (var i = 0, l = subPaths.length; i < l; i++) {
  25276. tmpPath = subPaths[i];
  25277. tmpPoints = tmpPath.getPoints();
  25278. solid = isClockWise(tmpPoints);
  25279. solid = isCCW ? !solid : solid;
  25280. if (solid) {
  25281. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  25282. newShapes[mainIdx] = {
  25283. s: new Shape(),
  25284. p: tmpPoints
  25285. };
  25286. newShapes[mainIdx].s.curves = tmpPath.curves;
  25287. if (holesFirst) mainIdx++;
  25288. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  25289. } else {
  25290. newShapeHoles[mainIdx].push({
  25291. h: tmpPath,
  25292. p: tmpPoints[0]
  25293. }); //console.log('ccw', i);
  25294. }
  25295. } // only Holes? -> probably all Shapes with wrong orientation
  25296. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  25297. if (newShapes.length > 1) {
  25298. var ambiguous = false;
  25299. var toChange = [];
  25300. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25301. betterShapeHoles[sIdx] = [];
  25302. }
  25303. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25304. var sho = newShapeHoles[sIdx];
  25305. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  25306. var ho = sho[hIdx];
  25307. var hole_unassigned = true;
  25308. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  25309. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  25310. if (sIdx !== s2Idx) toChange.push({
  25311. froms: sIdx,
  25312. tos: s2Idx,
  25313. hole: hIdx
  25314. });
  25315. if (hole_unassigned) {
  25316. hole_unassigned = false;
  25317. betterShapeHoles[s2Idx].push(ho);
  25318. } else {
  25319. ambiguous = true;
  25320. }
  25321. }
  25322. }
  25323. if (hole_unassigned) {
  25324. betterShapeHoles[sIdx].push(ho);
  25325. }
  25326. }
  25327. } // console.log("ambiguous: ", ambiguous);
  25328. if (toChange.length > 0) {
  25329. // console.log("to change: ", toChange);
  25330. if (!ambiguous) newShapeHoles = betterShapeHoles;
  25331. }
  25332. }
  25333. var tmpHoles;
  25334. for (var i = 0, il = newShapes.length; i < il; i++) {
  25335. tmpShape = newShapes[i].s;
  25336. shapes.push(tmpShape);
  25337. tmpHoles = newShapeHoles[i];
  25338. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  25339. tmpShape.holes.push(tmpHoles[j].h);
  25340. }
  25341. } //console.log("shape", shapes);
  25342. return shapes;
  25343. }
  25344. });
  25345. /**
  25346. * @author zz85 / http://www.lab4games.net/zz85/blog
  25347. * @author mrdoob / http://mrdoob.com/
  25348. */
  25349. function Font(data) {
  25350. this.type = 'Font';
  25351. this.data = data;
  25352. }
  25353. Object.assign(Font.prototype, {
  25354. isFont: true,
  25355. generateShapes: function (text, size) {
  25356. if (size === undefined) size = 100;
  25357. var shapes = [];
  25358. var paths = createPaths(text, size, this.data);
  25359. for (var p = 0, pl = paths.length; p < pl; p++) {
  25360. Array.prototype.push.apply(shapes, paths[p].toShapes());
  25361. }
  25362. return shapes;
  25363. }
  25364. });
  25365. function createPaths(text, size, data) {
  25366. var chars = Array.from ? Array.from(text) : String(text).split(''); // see #13988
  25367. var scale = size / data.resolution;
  25368. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  25369. var paths = [];
  25370. var offsetX = 0,
  25371. offsetY = 0;
  25372. for (var i = 0; i < chars.length; i++) {
  25373. var char = chars[i];
  25374. if (char === '\n') {
  25375. offsetX = 0;
  25376. offsetY -= line_height;
  25377. } else {
  25378. var ret = createPath(char, scale, offsetX, offsetY, data);
  25379. offsetX += ret.offsetX;
  25380. paths.push(ret.path);
  25381. }
  25382. }
  25383. return paths;
  25384. }
  25385. function createPath(char, scale, offsetX, offsetY, data) {
  25386. var glyph = data.glyphs[char] || data.glyphs['?'];
  25387. if (!glyph) {
  25388. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  25389. return;
  25390. }
  25391. var path = new ShapePath();
  25392. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25393. if (glyph.o) {
  25394. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  25395. for (var i = 0, l = outline.length; i < l;) {
  25396. var action = outline[i++];
  25397. switch (action) {
  25398. case 'm':
  25399. // moveTo
  25400. x = outline[i++] * scale + offsetX;
  25401. y = outline[i++] * scale + offsetY;
  25402. path.moveTo(x, y);
  25403. break;
  25404. case 'l':
  25405. // lineTo
  25406. x = outline[i++] * scale + offsetX;
  25407. y = outline[i++] * scale + offsetY;
  25408. path.lineTo(x, y);
  25409. break;
  25410. case 'q':
  25411. // quadraticCurveTo
  25412. cpx = outline[i++] * scale + offsetX;
  25413. cpy = outline[i++] * scale + offsetY;
  25414. cpx1 = outline[i++] * scale + offsetX;
  25415. cpy1 = outline[i++] * scale + offsetY;
  25416. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  25417. break;
  25418. case 'b':
  25419. // bezierCurveTo
  25420. cpx = outline[i++] * scale + offsetX;
  25421. cpy = outline[i++] * scale + offsetY;
  25422. cpx1 = outline[i++] * scale + offsetX;
  25423. cpy1 = outline[i++] * scale + offsetY;
  25424. cpx2 = outline[i++] * scale + offsetX;
  25425. cpy2 = outline[i++] * scale + offsetY;
  25426. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  25427. break;
  25428. }
  25429. }
  25430. }
  25431. return {
  25432. offsetX: glyph.ha * scale,
  25433. path: path
  25434. };
  25435. }
  25436. /**
  25437. * @author mrdoob / http://mrdoob.com/
  25438. */
  25439. function FontLoader(manager) {
  25440. Loader.call(this, manager);
  25441. }
  25442. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25443. constructor: FontLoader,
  25444. load: function (url, onLoad, onProgress, onError) {
  25445. var scope = this;
  25446. var loader = new FileLoader(this.manager);
  25447. loader.setPath(this.path);
  25448. loader.load(url, function (text) {
  25449. var json;
  25450. try {
  25451. json = JSON.parse(text);
  25452. } catch (e) {
  25453. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  25454. json = JSON.parse(text.substring(65, text.length - 2));
  25455. }
  25456. var font = scope.parse(json);
  25457. if (onLoad) onLoad(font);
  25458. }, onProgress, onError);
  25459. },
  25460. parse: function (json) {
  25461. return new Font(json);
  25462. }
  25463. });
  25464. /**
  25465. * @author mrdoob / http://mrdoob.com/
  25466. */
  25467. var _context;
  25468. var AudioContext = {
  25469. getContext: function () {
  25470. if (_context === undefined) {
  25471. _context = new (window.AudioContext || window.webkitAudioContext)();
  25472. }
  25473. return _context;
  25474. },
  25475. setContext: function (value) {
  25476. _context = value;
  25477. }
  25478. };
  25479. /**
  25480. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25481. */
  25482. exports.AudioContext = AudioContext;
  25483. function AudioLoader(manager) {
  25484. Loader.call(this, manager);
  25485. }
  25486. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25487. constructor: AudioLoader,
  25488. load: function (url, onLoad, onProgress, onError) {
  25489. var loader = new FileLoader(this.manager);
  25490. loader.setResponseType('arraybuffer');
  25491. loader.setPath(this.path);
  25492. loader.load(url, function (buffer) {
  25493. // Create a copy of the buffer. The `decodeAudioData` method
  25494. // detaches the buffer when complete, preventing reuse.
  25495. var bufferCopy = buffer.slice(0);
  25496. var context = AudioContext.getContext();
  25497. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25498. onLoad(audioBuffer);
  25499. });
  25500. }, onProgress, onError);
  25501. }
  25502. });
  25503. /**
  25504. * @author bhouston / http://clara.io
  25505. * @author WestLangley / http://github.com/WestLangley
  25506. *
  25507. * Primary reference:
  25508. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25509. *
  25510. * Secondary reference:
  25511. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25512. */
  25513. // 3-band SH defined by 9 coefficients
  25514. function SphericalHarmonics3() {
  25515. this.coefficients = [];
  25516. for (var i = 0; i < 9; i++) {
  25517. this.coefficients.push(new Vector3());
  25518. }
  25519. }
  25520. Object.assign(SphericalHarmonics3.prototype, {
  25521. isSphericalHarmonics3: true,
  25522. set: function (coefficients) {
  25523. for (var i = 0; i < 9; i++) {
  25524. this.coefficients[i].copy(coefficients[i]);
  25525. }
  25526. return this;
  25527. },
  25528. zero: function () {
  25529. for (var i = 0; i < 9; i++) {
  25530. this.coefficients[i].set(0, 0, 0);
  25531. }
  25532. return this;
  25533. },
  25534. // get the radiance in the direction of the normal
  25535. // target is a Vector3
  25536. getAt: function (normal, target) {
  25537. // normal is assumed to be unit length
  25538. var x = normal.x,
  25539. y = normal.y,
  25540. z = normal.z;
  25541. var coeff = this.coefficients; // band 0
  25542. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  25543. target.addScale(coeff[1], 0.488603 * y);
  25544. target.addScale(coeff[2], 0.488603 * z);
  25545. target.addScale(coeff[3], 0.488603 * x); // band 2
  25546. target.addScale(coeff[4], 1.092548 * (x * y));
  25547. target.addScale(coeff[5], 1.092548 * (y * z));
  25548. target.addScale(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  25549. target.addScale(coeff[7], 1.092548 * (x * z));
  25550. target.addScale(coeff[8], 0.546274 * (x * x - y * y));
  25551. return target;
  25552. },
  25553. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25554. // target is a Vector3
  25555. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25556. getIrradianceAt: function (normal, target) {
  25557. // normal is assumed to be unit length
  25558. var x = normal.x,
  25559. y = normal.y,
  25560. z = normal.z;
  25561. var coeff = this.coefficients; // band 0
  25562. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  25563. // band 1
  25564. target.addScale(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  25565. target.addScale(coeff[2], 2.0 * 0.511664 * z);
  25566. target.addScale(coeff[3], 2.0 * 0.511664 * x); // band 2
  25567. target.addScale(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  25568. target.addScale(coeff[5], 2.0 * 0.429043 * y * z);
  25569. target.addScale(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  25570. target.addScale(coeff[7], 2.0 * 0.429043 * x * z);
  25571. target.addScale(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  25572. return target;
  25573. },
  25574. add: function (sh) {
  25575. for (var i = 0; i < 9; i++) {
  25576. this.coefficients[i].add(sh.coefficients[i]);
  25577. }
  25578. return this;
  25579. },
  25580. scale: function (s) {
  25581. for (var i = 0; i < 9; i++) {
  25582. this.coefficients[i].multiplyScalar(s);
  25583. }
  25584. return this;
  25585. },
  25586. lerp: function (sh, alpha) {
  25587. for (var i = 0; i < 9; i++) {
  25588. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  25589. }
  25590. return this;
  25591. },
  25592. equals: function (sh) {
  25593. for (var i = 0; i < 9; i++) {
  25594. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  25595. return false;
  25596. }
  25597. }
  25598. return true;
  25599. },
  25600. copy: function (sh) {
  25601. return this.set(sh.coefficients);
  25602. },
  25603. clone: function () {
  25604. return new this.constructor().copy(this);
  25605. },
  25606. fromArray: function (array, offset) {
  25607. if (offset === undefined) offset = 0;
  25608. var coefficients = this.coefficients;
  25609. for (var i = 0; i < 9; i++) {
  25610. coefficients[i].fromArray(array, offset + i * 3);
  25611. }
  25612. return this;
  25613. },
  25614. toArray: function (array, offset) {
  25615. if (array === undefined) array = [];
  25616. if (offset === undefined) offset = 0;
  25617. var coefficients = this.coefficients;
  25618. for (var i = 0; i < 9; i++) {
  25619. coefficients[i].toArray(array, offset + i * 3);
  25620. }
  25621. return array;
  25622. }
  25623. });
  25624. Object.assign(SphericalHarmonics3, {
  25625. // evaluate the basis functions
  25626. // shBasis is an Array[ 9 ]
  25627. getBasisAt: function (normal, shBasis) {
  25628. // normal is assumed to be unit length
  25629. var x = normal.x,
  25630. y = normal.y,
  25631. z = normal.z; // band 0
  25632. shBasis[0] = 0.282095; // band 1
  25633. shBasis[1] = 0.488603 * y;
  25634. shBasis[2] = 0.488603 * z;
  25635. shBasis[3] = 0.488603 * x; // band 2
  25636. shBasis[4] = 1.092548 * x * y;
  25637. shBasis[5] = 1.092548 * y * z;
  25638. shBasis[6] = 0.315392 * (3 * z * z - 1);
  25639. shBasis[7] = 1.092548 * x * z;
  25640. shBasis[8] = 0.546274 * (x * x - y * y);
  25641. }
  25642. });
  25643. /**
  25644. * @author WestLangley / http://github.com/WestLangley
  25645. *
  25646. * A LightProbe is a source of indirect-diffuse light
  25647. */
  25648. function LightProbe(sh, intensity) {
  25649. Light.call(this, undefined, intensity);
  25650. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  25651. }
  25652. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  25653. constructor: LightProbe,
  25654. isLightProbe: true,
  25655. copy: function (source) {
  25656. Light.prototype.copy.call(this, source);
  25657. this.sh.copy(source.sh);
  25658. this.intensity = source.intensity;
  25659. return this;
  25660. },
  25661. toJSON: function (meta) {
  25662. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25663. return data;
  25664. }
  25665. });
  25666. /**
  25667. * @author WestLangley / http://github.com/WestLangley
  25668. */
  25669. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  25670. LightProbe.call(this, undefined, intensity);
  25671. var color1 = new Color().set(skyColor);
  25672. var color2 = new Color().set(groundColor);
  25673. var sky = new Vector3(color1.r, color1.g, color1.b);
  25674. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25675. var c0 = Math.sqrt(Math.PI);
  25676. var c1 = c0 * Math.sqrt(0.75);
  25677. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25678. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25679. }
  25680. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25681. constructor: HemisphereLightProbe,
  25682. isHemisphereLightProbe: true,
  25683. copy: function (source) {
  25684. // modifying colors not currently supported
  25685. LightProbe.prototype.copy.call(this, source);
  25686. return this;
  25687. },
  25688. toJSON: function (meta) {
  25689. var data = LightProbe.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 AmbientLightProbe(color, intensity) {
  25697. LightProbe.call(this, undefined, intensity);
  25698. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25699. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25700. }
  25701. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25702. constructor: AmbientLightProbe,
  25703. isAmbientLightProbe: true,
  25704. copy: function (source) {
  25705. // modifying color not currently supported
  25706. LightProbe.prototype.copy.call(this, source);
  25707. return this;
  25708. },
  25709. toJSON: function (meta) {
  25710. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25711. return data;
  25712. }
  25713. });
  25714. var _eyeRight = new Matrix4();
  25715. var _eyeLeft = new Matrix4();
  25716. /**
  25717. * @author mrdoob / http://mrdoob.com/
  25718. */
  25719. function StereoCamera() {
  25720. this.type = 'StereoCamera';
  25721. this.aspect = 1;
  25722. this.eyeSep = 0.064;
  25723. this.cameraL = new PerspectiveCamera();
  25724. this.cameraL.layers.enable(1);
  25725. this.cameraL.matrixAutoUpdate = false;
  25726. this.cameraR = new PerspectiveCamera();
  25727. this.cameraR.layers.enable(2);
  25728. this.cameraR.matrixAutoUpdate = false;
  25729. this._cache = {
  25730. focus: null,
  25731. fov: null,
  25732. aspect: null,
  25733. near: null,
  25734. far: null,
  25735. zoom: null,
  25736. eyeSep: null
  25737. };
  25738. }
  25739. Object.assign(StereoCamera.prototype, {
  25740. update: function (camera) {
  25741. var cache = this._cache;
  25742. 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;
  25743. if (needsUpdate) {
  25744. cache.focus = camera.focus;
  25745. cache.fov = camera.fov;
  25746. cache.aspect = camera.aspect * this.aspect;
  25747. cache.near = camera.near;
  25748. cache.far = camera.far;
  25749. cache.zoom = camera.zoom;
  25750. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25751. // http://paulbourke.net/stereographics/stereorender/
  25752. var projectionMatrix = camera.projectionMatrix.clone();
  25753. var eyeSepHalf = cache.eyeSep / 2;
  25754. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25755. var ymax = cache.near * Math.tan(_Math.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25756. var xmin, xmax; // translate xOffset
  25757. _eyeLeft.elements[12] = -eyeSepHalf;
  25758. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25759. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25760. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25761. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25762. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25763. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25764. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25765. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25766. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25767. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25768. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25769. }
  25770. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25771. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25772. }
  25773. });
  25774. /**
  25775. * @author alteredq / http://alteredqualia.com/
  25776. */
  25777. function Clock(autoStart) {
  25778. this.autoStart = autoStart !== undefined ? autoStart : true;
  25779. this.startTime = 0;
  25780. this.oldTime = 0;
  25781. this.elapsedTime = 0;
  25782. this.running = false;
  25783. }
  25784. Object.assign(Clock.prototype, {
  25785. start: function () {
  25786. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25787. this.oldTime = this.startTime;
  25788. this.elapsedTime = 0;
  25789. this.running = true;
  25790. },
  25791. stop: function () {
  25792. this.getElapsedTime();
  25793. this.running = false;
  25794. this.autoStart = false;
  25795. },
  25796. getElapsedTime: function () {
  25797. this.getDelta();
  25798. return this.elapsedTime;
  25799. },
  25800. getDelta: function () {
  25801. var diff = 0;
  25802. if (this.autoStart && !this.running) {
  25803. this.start();
  25804. return 0;
  25805. }
  25806. if (this.running) {
  25807. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  25808. diff = (newTime - this.oldTime) / 1000;
  25809. this.oldTime = newTime;
  25810. this.elapsedTime += diff;
  25811. }
  25812. return diff;
  25813. }
  25814. });
  25815. /**
  25816. * @author mrdoob / http://mrdoob.com/
  25817. */
  25818. var _position$2 = new Vector3();
  25819. var _quaternion$3 = new Quaternion();
  25820. var _scale$1 = new Vector3();
  25821. var _orientation = new Vector3();
  25822. function AudioListener() {
  25823. Object3D.call(this);
  25824. this.type = 'AudioListener';
  25825. this.context = AudioContext.getContext();
  25826. this.gain = this.context.createGain();
  25827. this.gain.connect(this.context.destination);
  25828. this.filter = null;
  25829. this.timeDelta = 0; // private
  25830. this._clock = new Clock();
  25831. }
  25832. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  25833. constructor: AudioListener,
  25834. getInput: function () {
  25835. return this.gain;
  25836. },
  25837. removeFilter: function () {
  25838. if (this.filter !== null) {
  25839. this.gain.disconnect(this.filter);
  25840. this.filter.disconnect(this.context.destination);
  25841. this.gain.connect(this.context.destination);
  25842. this.filter = null;
  25843. }
  25844. return this;
  25845. },
  25846. getFilter: function () {
  25847. return this.filter;
  25848. },
  25849. setFilter: function (value) {
  25850. if (this.filter !== null) {
  25851. this.gain.disconnect(this.filter);
  25852. this.filter.disconnect(this.context.destination);
  25853. } else {
  25854. this.gain.disconnect(this.context.destination);
  25855. }
  25856. this.filter = value;
  25857. this.gain.connect(this.filter);
  25858. this.filter.connect(this.context.destination);
  25859. return this;
  25860. },
  25861. getMasterVolume: function () {
  25862. return this.gain.gain.value;
  25863. },
  25864. setMasterVolume: function (value) {
  25865. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25866. return this;
  25867. },
  25868. updateMatrixWorld: function (force) {
  25869. Object3D.prototype.updateMatrixWorld.call(this, force);
  25870. var listener = this.context.listener;
  25871. var up = this.up;
  25872. this.timeDelta = this._clock.getDelta();
  25873. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25874. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25875. if (listener.positionX) {
  25876. // code path for Chrome (see #14393)
  25877. var endTime = this.context.currentTime + this.timeDelta;
  25878. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25879. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25880. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25881. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25882. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25883. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25884. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25885. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25886. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25887. } else {
  25888. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25889. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25890. }
  25891. }
  25892. });
  25893. /**
  25894. * @author mrdoob / http://mrdoob.com/
  25895. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25896. */
  25897. function Audio(listener) {
  25898. Object3D.call(this);
  25899. this.type = 'Audio';
  25900. this.listener = listener;
  25901. this.context = listener.context;
  25902. this.gain = this.context.createGain();
  25903. this.gain.connect(listener.getInput());
  25904. this.autoplay = false;
  25905. this.buffer = null;
  25906. this.detune = 0;
  25907. this.loop = false;
  25908. this.startTime = 0;
  25909. this.offset = 0;
  25910. this.duration = undefined;
  25911. this.playbackRate = 1;
  25912. this.isPlaying = false;
  25913. this.hasPlaybackControl = true;
  25914. this.sourceType = 'empty';
  25915. this.filters = [];
  25916. }
  25917. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  25918. constructor: Audio,
  25919. getOutput: function () {
  25920. return this.gain;
  25921. },
  25922. setNodeSource: function (audioNode) {
  25923. this.hasPlaybackControl = false;
  25924. this.sourceType = 'audioNode';
  25925. this.source = audioNode;
  25926. this.connect();
  25927. return this;
  25928. },
  25929. setMediaElementSource: function (mediaElement) {
  25930. this.hasPlaybackControl = false;
  25931. this.sourceType = 'mediaNode';
  25932. this.source = this.context.createMediaElementSource(mediaElement);
  25933. this.connect();
  25934. return this;
  25935. },
  25936. setMediaStreamSource: function (mediaStream) {
  25937. this.hasPlaybackControl = false;
  25938. this.sourceType = 'mediaStreamNode';
  25939. this.source = this.context.createMediaStreamSource(mediaStream);
  25940. this.connect();
  25941. return this;
  25942. },
  25943. setBuffer: function (audioBuffer) {
  25944. this.buffer = audioBuffer;
  25945. this.sourceType = 'buffer';
  25946. if (this.autoplay) this.play();
  25947. return this;
  25948. },
  25949. play: function () {
  25950. if (this.isPlaying === true) {
  25951. console.warn('THREE.Audio: Audio is already playing.');
  25952. return;
  25953. }
  25954. if (this.hasPlaybackControl === false) {
  25955. console.warn('THREE.Audio: this Audio has no playback control.');
  25956. return;
  25957. }
  25958. var source = this.context.createBufferSource();
  25959. source.buffer = this.buffer;
  25960. source.loop = this.loop;
  25961. source.onended = this.onEnded.bind(this);
  25962. this.startTime = this.context.currentTime;
  25963. source.start(this.startTime, this.offset, this.duration);
  25964. this.isPlaying = true;
  25965. this.source = source;
  25966. this.setDetune(this.detune);
  25967. this.setPlaybackRate(this.playbackRate);
  25968. return this.connect();
  25969. },
  25970. pause: function () {
  25971. if (this.hasPlaybackControl === false) {
  25972. console.warn('THREE.Audio: this Audio has no playback control.');
  25973. return;
  25974. }
  25975. if (this.isPlaying === true) {
  25976. this.source.stop();
  25977. this.source.onended = null;
  25978. this.offset += (this.context.currentTime - this.startTime) * this.playbackRate;
  25979. this.isPlaying = false;
  25980. }
  25981. return this;
  25982. },
  25983. stop: function () {
  25984. if (this.hasPlaybackControl === false) {
  25985. console.warn('THREE.Audio: this Audio has no playback control.');
  25986. return;
  25987. }
  25988. this.source.stop();
  25989. this.source.onended = null;
  25990. this.offset = 0;
  25991. this.isPlaying = false;
  25992. return this;
  25993. },
  25994. connect: function () {
  25995. if (this.filters.length > 0) {
  25996. this.source.connect(this.filters[0]);
  25997. for (var i = 1, l = this.filters.length; i < l; i++) {
  25998. this.filters[i - 1].connect(this.filters[i]);
  25999. }
  26000. this.filters[this.filters.length - 1].connect(this.getOutput());
  26001. } else {
  26002. this.source.connect(this.getOutput());
  26003. }
  26004. return this;
  26005. },
  26006. disconnect: function () {
  26007. if (this.filters.length > 0) {
  26008. this.source.disconnect(this.filters[0]);
  26009. for (var i = 1, l = this.filters.length; i < l; i++) {
  26010. this.filters[i - 1].disconnect(this.filters[i]);
  26011. }
  26012. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  26013. } else {
  26014. this.source.disconnect(this.getOutput());
  26015. }
  26016. return this;
  26017. },
  26018. getFilters: function () {
  26019. return this.filters;
  26020. },
  26021. setFilters: function (value) {
  26022. if (!value) value = [];
  26023. if (this.isPlaying === true) {
  26024. this.disconnect();
  26025. this.filters = value;
  26026. this.connect();
  26027. } else {
  26028. this.filters = value;
  26029. }
  26030. return this;
  26031. },
  26032. setDetune: function (value) {
  26033. this.detune = value;
  26034. if (this.source.detune === undefined) return; // only set detune when available
  26035. if (this.isPlaying === true) {
  26036. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  26037. }
  26038. return this;
  26039. },
  26040. getDetune: function () {
  26041. return this.detune;
  26042. },
  26043. getFilter: function () {
  26044. return this.getFilters()[0];
  26045. },
  26046. setFilter: function (filter) {
  26047. return this.setFilters(filter ? [filter] : []);
  26048. },
  26049. setPlaybackRate: function (value) {
  26050. if (this.hasPlaybackControl === false) {
  26051. console.warn('THREE.Audio: this Audio has no playback control.');
  26052. return;
  26053. }
  26054. this.playbackRate = value;
  26055. if (this.isPlaying === true) {
  26056. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  26057. }
  26058. return this;
  26059. },
  26060. getPlaybackRate: function () {
  26061. return this.playbackRate;
  26062. },
  26063. onEnded: function () {
  26064. this.isPlaying = false;
  26065. },
  26066. getLoop: function () {
  26067. if (this.hasPlaybackControl === false) {
  26068. console.warn('THREE.Audio: this Audio has no playback control.');
  26069. return false;
  26070. }
  26071. return this.loop;
  26072. },
  26073. setLoop: function (value) {
  26074. if (this.hasPlaybackControl === false) {
  26075. console.warn('THREE.Audio: this Audio has no playback control.');
  26076. return;
  26077. }
  26078. this.loop = value;
  26079. if (this.isPlaying === true) {
  26080. this.source.loop = this.loop;
  26081. }
  26082. return this;
  26083. },
  26084. getVolume: function () {
  26085. return this.gain.gain.value;
  26086. },
  26087. setVolume: function (value) {
  26088. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  26089. return this;
  26090. }
  26091. });
  26092. /**
  26093. * @author mrdoob / http://mrdoob.com/
  26094. */
  26095. var _position$3 = new Vector3();
  26096. var _quaternion$4 = new Quaternion();
  26097. var _scale$2 = new Vector3();
  26098. var _orientation$1 = new Vector3();
  26099. function PositionalAudio(listener) {
  26100. Audio.call(this, listener);
  26101. this.panner = this.context.createPanner();
  26102. this.panner.panningModel = 'HRTF';
  26103. this.panner.connect(this.gain);
  26104. }
  26105. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  26106. constructor: PositionalAudio,
  26107. getOutput: function () {
  26108. return this.panner;
  26109. },
  26110. getRefDistance: function () {
  26111. return this.panner.refDistance;
  26112. },
  26113. setRefDistance: function (value) {
  26114. this.panner.refDistance = value;
  26115. return this;
  26116. },
  26117. getRolloffFactor: function () {
  26118. return this.panner.rolloffFactor;
  26119. },
  26120. setRolloffFactor: function (value) {
  26121. this.panner.rolloffFactor = value;
  26122. return this;
  26123. },
  26124. getDistanceModel: function () {
  26125. return this.panner.distanceModel;
  26126. },
  26127. setDistanceModel: function (value) {
  26128. this.panner.distanceModel = value;
  26129. return this;
  26130. },
  26131. getMaxDistance: function () {
  26132. return this.panner.maxDistance;
  26133. },
  26134. setMaxDistance: function (value) {
  26135. this.panner.maxDistance = value;
  26136. return this;
  26137. },
  26138. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26139. this.panner.coneInnerAngle = coneInnerAngle;
  26140. this.panner.coneOuterAngle = coneOuterAngle;
  26141. this.panner.coneOuterGain = coneOuterGain;
  26142. return this;
  26143. },
  26144. updateMatrixWorld: function (force) {
  26145. Object3D.prototype.updateMatrixWorld.call(this, force);
  26146. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  26147. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  26148. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  26149. var panner = this.panner;
  26150. if (panner.positionX) {
  26151. // code path for Chrome and Firefox (see #14393)
  26152. var endTime = this.context.currentTime + this.listener.timeDelta;
  26153. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  26154. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  26155. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  26156. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  26157. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  26158. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  26159. } else {
  26160. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  26161. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  26162. }
  26163. }
  26164. });
  26165. /**
  26166. * @author mrdoob / http://mrdoob.com/
  26167. */
  26168. function AudioAnalyser(audio, fftSize) {
  26169. this.analyser = audio.context.createAnalyser();
  26170. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  26171. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  26172. audio.getOutput().connect(this.analyser);
  26173. }
  26174. Object.assign(AudioAnalyser.prototype, {
  26175. getFrequencyData: function () {
  26176. this.analyser.getByteFrequencyData(this.data);
  26177. return this.data;
  26178. },
  26179. getAverageFrequency: function () {
  26180. var value = 0,
  26181. data = this.getFrequencyData();
  26182. for (var i = 0; i < data.length; i++) {
  26183. value += data[i];
  26184. }
  26185. return value / data.length;
  26186. }
  26187. });
  26188. /**
  26189. *
  26190. * Buffered scene graph property that allows weighted accumulation.
  26191. *
  26192. *
  26193. * @author Ben Houston / http://clara.io/
  26194. * @author David Sarno / http://lighthaus.us/
  26195. * @author tschw
  26196. */
  26197. function PropertyMixer(binding, typeName, valueSize) {
  26198. this.binding = binding;
  26199. this.valueSize = valueSize;
  26200. var bufferType = Float64Array,
  26201. mixFunction;
  26202. switch (typeName) {
  26203. case 'quaternion':
  26204. mixFunction = this._slerp;
  26205. break;
  26206. case 'string':
  26207. case 'bool':
  26208. bufferType = Array;
  26209. mixFunction = this._select;
  26210. break;
  26211. default:
  26212. mixFunction = this._lerp;
  26213. }
  26214. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  26215. //
  26216. // interpolators can use .buffer as their .result
  26217. // the data then goes to 'incoming'
  26218. //
  26219. // 'accu0' and 'accu1' are used frame-interleaved for
  26220. // the cumulative result and are compared to detect
  26221. // changes
  26222. //
  26223. // 'orig' stores the original state of the property
  26224. this._mixBufferRegion = mixFunction;
  26225. this.cumulativeWeight = 0;
  26226. this.useCount = 0;
  26227. this.referenceCount = 0;
  26228. }
  26229. Object.assign(PropertyMixer.prototype, {
  26230. // accumulate data in the 'incoming' region into 'accu<i>'
  26231. accumulate: function (accuIndex, weight) {
  26232. // note: happily accumulating nothing when weight = 0, the caller knows
  26233. // the weight and shouldn't have made the call in the first place
  26234. var buffer = this.buffer,
  26235. stride = this.valueSize,
  26236. offset = accuIndex * stride + stride,
  26237. currentWeight = this.cumulativeWeight;
  26238. if (currentWeight === 0) {
  26239. // accuN := incoming * weight
  26240. for (var i = 0; i !== stride; ++i) {
  26241. buffer[offset + i] = buffer[i];
  26242. }
  26243. currentWeight = weight;
  26244. } else {
  26245. // accuN := accuN + incoming * weight
  26246. currentWeight += weight;
  26247. var mix = weight / currentWeight;
  26248. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26249. }
  26250. this.cumulativeWeight = currentWeight;
  26251. },
  26252. // apply the state of 'accu<i>' to the binding when accus differ
  26253. apply: function (accuIndex) {
  26254. var stride = this.valueSize,
  26255. buffer = this.buffer,
  26256. offset = accuIndex * stride + stride,
  26257. weight = this.cumulativeWeight,
  26258. binding = this.binding;
  26259. this.cumulativeWeight = 0;
  26260. if (weight < 1) {
  26261. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26262. var originalValueOffset = stride * 3;
  26263. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26264. }
  26265. for (var i = stride, e = stride + stride; i !== e; ++i) {
  26266. if (buffer[i] !== buffer[i + stride]) {
  26267. // value has changed -> update scene graph
  26268. binding.setValue(buffer, offset);
  26269. break;
  26270. }
  26271. }
  26272. },
  26273. // remember the state of the bound property and copy it to both accus
  26274. saveOriginalState: function () {
  26275. var binding = this.binding;
  26276. var buffer = this.buffer,
  26277. stride = this.valueSize,
  26278. originalValueOffset = stride * 3;
  26279. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  26280. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  26281. buffer[i] = buffer[originalValueOffset + i % stride];
  26282. }
  26283. this.cumulativeWeight = 0;
  26284. },
  26285. // apply the state previously taken via 'saveOriginalState' to the binding
  26286. restoreOriginalState: function () {
  26287. var originalValueOffset = this.valueSize * 3;
  26288. this.binding.setValue(this.buffer, originalValueOffset);
  26289. },
  26290. // mix functions
  26291. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  26292. if (t >= 0.5) {
  26293. for (var i = 0; i !== stride; ++i) {
  26294. buffer[dstOffset + i] = buffer[srcOffset + i];
  26295. }
  26296. }
  26297. },
  26298. _slerp: function (buffer, dstOffset, srcOffset, t) {
  26299. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26300. },
  26301. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  26302. var s = 1 - t;
  26303. for (var i = 0; i !== stride; ++i) {
  26304. var j = dstOffset + i;
  26305. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26306. }
  26307. }
  26308. });
  26309. /**
  26310. *
  26311. * A reference to a real property in the scene graph.
  26312. *
  26313. *
  26314. * @author Ben Houston / http://clara.io/
  26315. * @author David Sarno / http://lighthaus.us/
  26316. * @author tschw
  26317. */
  26318. // Characters [].:/ are reserved for track binding syntax.
  26319. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26320. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26321. // only latin characters, and the unicode \p{L} is not yet supported. So
  26322. // instead, we exclude reserved characters and match everything else.
  26323. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26324. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26325. // be matched to parse the rest of the track name.
  26326. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26327. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  26328. // characters. Accessor may contain any character except closing bracket.
  26329. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  26330. // contain any non-bracket characters.
  26331. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26332. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26333. var _supportedObjectNames = ['material', 'materials', 'bones'];
  26334. function Composite(targetGroup, path, optionalParsedPath) {
  26335. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26336. this._targetGroup = targetGroup;
  26337. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26338. }
  26339. Object.assign(Composite.prototype, {
  26340. getValue: function (array, offset) {
  26341. this.bind(); // bind all binding
  26342. var firstValidIndex = this._targetGroup.nCachedObjects_,
  26343. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  26344. if (binding !== undefined) binding.getValue(array, offset);
  26345. },
  26346. setValue: function (array, offset) {
  26347. var bindings = this._bindings;
  26348. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26349. bindings[i].setValue(array, offset);
  26350. }
  26351. },
  26352. bind: function () {
  26353. var bindings = this._bindings;
  26354. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26355. bindings[i].bind();
  26356. }
  26357. },
  26358. unbind: function () {
  26359. var bindings = this._bindings;
  26360. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26361. bindings[i].unbind();
  26362. }
  26363. }
  26364. });
  26365. function PropertyBinding(rootNode, path, parsedPath) {
  26366. this.path = path;
  26367. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26368. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26369. this.rootNode = rootNode;
  26370. }
  26371. Object.assign(PropertyBinding, {
  26372. Composite: Composite,
  26373. create: function (root, path, parsedPath) {
  26374. if (!(root && root.isAnimationObjectGroup)) {
  26375. return new PropertyBinding(root, path, parsedPath);
  26376. } else {
  26377. return new PropertyBinding.Composite(root, path, parsedPath);
  26378. }
  26379. },
  26380. /**
  26381. * Replaces spaces with underscores and removes unsupported characters from
  26382. * node names, to ensure compatibility with parseTrackName().
  26383. *
  26384. * @param {string} name Node name to be sanitized.
  26385. * @return {string}
  26386. */
  26387. sanitizeNodeName: function (name) {
  26388. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26389. },
  26390. parseTrackName: function (trackName) {
  26391. var matches = _trackRe.exec(trackName);
  26392. if (!matches) {
  26393. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26394. }
  26395. var results = {
  26396. // directoryName: matches[ 1 ], // (tschw) currently unused
  26397. nodeName: matches[2],
  26398. objectName: matches[3],
  26399. objectIndex: matches[4],
  26400. propertyName: matches[5],
  26401. // required
  26402. propertyIndex: matches[6]
  26403. };
  26404. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26405. if (lastDot !== undefined && lastDot !== -1) {
  26406. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  26407. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26408. // 'bar' could be the objectName, or part of a nodeName (which can
  26409. // include '.' characters).
  26410. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26411. results.nodeName = results.nodeName.substring(0, lastDot);
  26412. results.objectName = objectName;
  26413. }
  26414. }
  26415. if (results.propertyName === null || results.propertyName.length === 0) {
  26416. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26417. }
  26418. return results;
  26419. },
  26420. findNode: function (root, nodeName) {
  26421. if (!nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26422. return root;
  26423. } // search into skeleton bones.
  26424. if (root.skeleton) {
  26425. var bone = root.skeleton.getBoneByName(nodeName);
  26426. if (bone !== undefined) {
  26427. return bone;
  26428. }
  26429. } // search into node subtree.
  26430. if (root.children) {
  26431. var searchNodeSubtree = function (children) {
  26432. for (var i = 0; i < children.length; i++) {
  26433. var childNode = children[i];
  26434. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26435. return childNode;
  26436. }
  26437. var result = searchNodeSubtree(childNode.children);
  26438. if (result) return result;
  26439. }
  26440. return null;
  26441. };
  26442. var subTreeNode = searchNodeSubtree(root.children);
  26443. if (subTreeNode) {
  26444. return subTreeNode;
  26445. }
  26446. }
  26447. return null;
  26448. }
  26449. });
  26450. Object.assign(PropertyBinding.prototype, {
  26451. // prototype, continued
  26452. // these are used to "bind" a nonexistent property
  26453. _getValue_unavailable: function () {},
  26454. _setValue_unavailable: function () {},
  26455. BindingType: {
  26456. Direct: 0,
  26457. EntireArray: 1,
  26458. ArrayElement: 2,
  26459. HasFromToArray: 3
  26460. },
  26461. Versioning: {
  26462. None: 0,
  26463. NeedsUpdate: 1,
  26464. MatrixWorldNeedsUpdate: 2
  26465. },
  26466. GetterByBindingType: [function getValue_direct(buffer, offset) {
  26467. buffer[offset] = this.node[this.propertyName];
  26468. }, function getValue_array(buffer, offset) {
  26469. var source = this.resolvedProperty;
  26470. for (var i = 0, n = source.length; i !== n; ++i) {
  26471. buffer[offset++] = source[i];
  26472. }
  26473. }, function getValue_arrayElement(buffer, offset) {
  26474. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26475. }, function getValue_toArray(buffer, offset) {
  26476. this.resolvedProperty.toArray(buffer, offset);
  26477. }],
  26478. SetterByBindingTypeAndVersioning: [[// Direct
  26479. function setValue_direct(buffer, offset) {
  26480. this.targetObject[this.propertyName] = buffer[offset];
  26481. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  26482. this.targetObject[this.propertyName] = buffer[offset];
  26483. this.targetObject.needsUpdate = true;
  26484. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26485. this.targetObject[this.propertyName] = buffer[offset];
  26486. this.targetObject.matrixWorldNeedsUpdate = true;
  26487. }], [// EntireArray
  26488. function setValue_array(buffer, offset) {
  26489. var dest = this.resolvedProperty;
  26490. for (var i = 0, n = dest.length; i !== n; ++i) {
  26491. dest[i] = buffer[offset++];
  26492. }
  26493. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  26494. var dest = this.resolvedProperty;
  26495. for (var i = 0, n = dest.length; i !== n; ++i) {
  26496. dest[i] = buffer[offset++];
  26497. }
  26498. this.targetObject.needsUpdate = true;
  26499. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26500. var dest = this.resolvedProperty;
  26501. for (var i = 0, n = dest.length; i !== n; ++i) {
  26502. dest[i] = buffer[offset++];
  26503. }
  26504. this.targetObject.matrixWorldNeedsUpdate = true;
  26505. }], [// ArrayElement
  26506. function setValue_arrayElement(buffer, offset) {
  26507. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26508. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26509. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26510. this.targetObject.needsUpdate = true;
  26511. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26512. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26513. this.targetObject.matrixWorldNeedsUpdate = true;
  26514. }], [// HasToFromArray
  26515. function setValue_fromArray(buffer, offset) {
  26516. this.resolvedProperty.fromArray(buffer, offset);
  26517. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26518. this.resolvedProperty.fromArray(buffer, offset);
  26519. this.targetObject.needsUpdate = true;
  26520. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26521. this.resolvedProperty.fromArray(buffer, offset);
  26522. this.targetObject.matrixWorldNeedsUpdate = true;
  26523. }]],
  26524. getValue: function getValue_unbound(targetArray, offset) {
  26525. this.bind();
  26526. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  26527. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26528. // prototype version of these methods with one that represents
  26529. // the bound state. When the property is not found, the methods
  26530. // become no-ops.
  26531. },
  26532. setValue: function getValue_unbound(sourceArray, offset) {
  26533. this.bind();
  26534. this.setValue(sourceArray, offset);
  26535. },
  26536. // create getter / setter pair for a property in the scene graph
  26537. bind: function () {
  26538. var targetObject = this.node,
  26539. parsedPath = this.parsedPath,
  26540. objectName = parsedPath.objectName,
  26541. propertyName = parsedPath.propertyName,
  26542. propertyIndex = parsedPath.propertyIndex;
  26543. if (!targetObject) {
  26544. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26545. this.node = targetObject;
  26546. } // set fail state so we can just 'return' on error
  26547. this.getValue = this._getValue_unavailable;
  26548. this.setValue = this._setValue_unavailable; // ensure there is a value node
  26549. if (!targetObject) {
  26550. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26551. return;
  26552. }
  26553. if (objectName) {
  26554. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26555. switch (objectName) {
  26556. case 'materials':
  26557. if (!targetObject.material) {
  26558. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26559. return;
  26560. }
  26561. if (!targetObject.material.materials) {
  26562. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  26563. return;
  26564. }
  26565. targetObject = targetObject.material.materials;
  26566. break;
  26567. case 'bones':
  26568. if (!targetObject.skeleton) {
  26569. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  26570. return;
  26571. } // potential future optimization: skip this if propertyIndex is already an integer
  26572. // and convert the integer string to a true integer.
  26573. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  26574. for (var i = 0; i < targetObject.length; i++) {
  26575. if (targetObject[i].name === objectIndex) {
  26576. objectIndex = i;
  26577. break;
  26578. }
  26579. }
  26580. break;
  26581. default:
  26582. if (targetObject[objectName] === undefined) {
  26583. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26584. return;
  26585. }
  26586. targetObject = targetObject[objectName];
  26587. }
  26588. if (objectIndex !== undefined) {
  26589. if (targetObject[objectIndex] === undefined) {
  26590. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26591. return;
  26592. }
  26593. targetObject = targetObject[objectIndex];
  26594. }
  26595. } // resolve property
  26596. var nodeProperty = targetObject[propertyName];
  26597. if (nodeProperty === undefined) {
  26598. var nodeName = parsedPath.nodeName;
  26599. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26600. return;
  26601. } // determine versioning scheme
  26602. var versioning = this.Versioning.None;
  26603. this.targetObject = targetObject;
  26604. if (targetObject.needsUpdate !== undefined) {
  26605. // material
  26606. versioning = this.Versioning.NeedsUpdate;
  26607. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26608. // node transform
  26609. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26610. } // determine how the property gets bound
  26611. var bindingType = this.BindingType.Direct;
  26612. if (propertyIndex !== undefined) {
  26613. // access a sub element of the property array (only primitives are supported right now)
  26614. if (propertyName === "morphTargetInfluences") {
  26615. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26616. // support resolving morphTarget names into indices.
  26617. if (!targetObject.geometry) {
  26618. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26619. return;
  26620. }
  26621. if (targetObject.geometry.isBufferGeometry) {
  26622. if (!targetObject.geometry.morphAttributes) {
  26623. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26624. return;
  26625. }
  26626. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  26627. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  26628. propertyIndex = i;
  26629. break;
  26630. }
  26631. }
  26632. } else {
  26633. if (!targetObject.geometry.morphTargets) {
  26634. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  26635. return;
  26636. }
  26637. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  26638. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  26639. propertyIndex = i;
  26640. break;
  26641. }
  26642. }
  26643. }
  26644. }
  26645. bindingType = this.BindingType.ArrayElement;
  26646. this.resolvedProperty = nodeProperty;
  26647. this.propertyIndex = propertyIndex;
  26648. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26649. // must use copy for Object3D.Euler/Quaternion
  26650. bindingType = this.BindingType.HasFromToArray;
  26651. this.resolvedProperty = nodeProperty;
  26652. } else if (Array.isArray(nodeProperty)) {
  26653. bindingType = this.BindingType.EntireArray;
  26654. this.resolvedProperty = nodeProperty;
  26655. } else {
  26656. this.propertyName = propertyName;
  26657. } // select getter / setter
  26658. this.getValue = this.GetterByBindingType[bindingType];
  26659. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26660. },
  26661. unbind: function () {
  26662. this.node = null; // back to the prototype version of getValue / setValue
  26663. // note: avoiding to mutate the shape of 'this' via 'delete'
  26664. this.getValue = this._getValue_unbound;
  26665. this.setValue = this._setValue_unbound;
  26666. }
  26667. }); //!\ DECLARE ALIAS AFTER assign prototype !
  26668. Object.assign(PropertyBinding.prototype, {
  26669. // initial state of these methods that calls 'bind'
  26670. _getValue_unbound: PropertyBinding.prototype.getValue,
  26671. _setValue_unbound: PropertyBinding.prototype.setValue
  26672. });
  26673. /**
  26674. *
  26675. * A group of objects that receives a shared animation state.
  26676. *
  26677. * Usage:
  26678. *
  26679. * - Add objects you would otherwise pass as 'root' to the
  26680. * constructor or the .clipAction method of AnimationMixer.
  26681. *
  26682. * - Instead pass this object as 'root'.
  26683. *
  26684. * - You can also add and remove objects later when the mixer
  26685. * is running.
  26686. *
  26687. * Note:
  26688. *
  26689. * Objects of this class appear as one object to the mixer,
  26690. * so cache control of the individual objects must be done
  26691. * on the group.
  26692. *
  26693. * Limitation:
  26694. *
  26695. * - The animated properties must be compatible among the
  26696. * all objects in the group.
  26697. *
  26698. * - A single property can either be controlled through a
  26699. * target group or directly, but not both.
  26700. *
  26701. * @author tschw
  26702. */
  26703. function AnimationObjectGroup() {
  26704. this.uuid = _Math.generateUUID(); // cached objects followed by the active ones
  26705. this._objects = Array.prototype.slice.call(arguments);
  26706. this.nCachedObjects_ = 0; // threshold
  26707. // note: read by PropertyBinding.Composite
  26708. var indices = {};
  26709. this._indicesByUUID = indices; // for bookkeeping
  26710. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26711. indices[arguments[i].uuid] = i;
  26712. }
  26713. this._paths = []; // inside: string
  26714. this._parsedPaths = []; // inside: { we don't care, here }
  26715. this._bindings = []; // inside: Array< PropertyBinding >
  26716. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26717. var scope = this;
  26718. this.stats = {
  26719. objects: {
  26720. get total() {
  26721. return scope._objects.length;
  26722. },
  26723. get inUse() {
  26724. return this.total - scope.nCachedObjects_;
  26725. }
  26726. },
  26727. get bindingsPerObject() {
  26728. return scope._bindings.length;
  26729. }
  26730. };
  26731. }
  26732. Object.assign(AnimationObjectGroup.prototype, {
  26733. isAnimationObjectGroup: true,
  26734. add: function () {
  26735. var objects = this._objects,
  26736. nObjects = objects.length,
  26737. nCachedObjects = this.nCachedObjects_,
  26738. indicesByUUID = this._indicesByUUID,
  26739. paths = this._paths,
  26740. parsedPaths = this._parsedPaths,
  26741. bindings = this._bindings,
  26742. nBindings = bindings.length,
  26743. knownObject = undefined;
  26744. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26745. var object = arguments[i],
  26746. uuid = object.uuid,
  26747. index = indicesByUUID[uuid];
  26748. if (index === undefined) {
  26749. // unknown object -> add it to the ACTIVE region
  26750. index = nObjects++;
  26751. indicesByUUID[uuid] = index;
  26752. objects.push(object); // accounting is done, now do the same for all bindings
  26753. for (var j = 0, m = nBindings; j !== m; ++j) {
  26754. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26755. }
  26756. } else if (index < nCachedObjects) {
  26757. knownObject = objects[index]; // move existing object to the ACTIVE region
  26758. var firstActiveIndex = --nCachedObjects,
  26759. lastCachedObject = objects[firstActiveIndex];
  26760. indicesByUUID[lastCachedObject.uuid] = index;
  26761. objects[index] = lastCachedObject;
  26762. indicesByUUID[uuid] = firstActiveIndex;
  26763. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26764. for (var j = 0, m = nBindings; j !== m; ++j) {
  26765. var bindingsForPath = bindings[j],
  26766. lastCached = bindingsForPath[firstActiveIndex],
  26767. binding = bindingsForPath[index];
  26768. bindingsForPath[index] = lastCached;
  26769. if (binding === undefined) {
  26770. // since we do not bother to create new bindings
  26771. // for objects that are cached, the binding may
  26772. // or may not exist
  26773. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26774. }
  26775. bindingsForPath[firstActiveIndex] = binding;
  26776. }
  26777. } else if (objects[index] !== knownObject) {
  26778. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26779. } // else the object is already where we want it to be
  26780. } // for arguments
  26781. this.nCachedObjects_ = nCachedObjects;
  26782. },
  26783. remove: function () {
  26784. var objects = this._objects,
  26785. nCachedObjects = this.nCachedObjects_,
  26786. indicesByUUID = this._indicesByUUID,
  26787. bindings = this._bindings,
  26788. nBindings = bindings.length;
  26789. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26790. var object = arguments[i],
  26791. uuid = object.uuid,
  26792. index = indicesByUUID[uuid];
  26793. if (index !== undefined && index >= nCachedObjects) {
  26794. // move existing object into the CACHED region
  26795. var lastCachedIndex = nCachedObjects++,
  26796. firstActiveObject = objects[lastCachedIndex];
  26797. indicesByUUID[firstActiveObject.uuid] = index;
  26798. objects[index] = firstActiveObject;
  26799. indicesByUUID[uuid] = lastCachedIndex;
  26800. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26801. for (var j = 0, m = nBindings; j !== m; ++j) {
  26802. var bindingsForPath = bindings[j],
  26803. firstActive = bindingsForPath[lastCachedIndex],
  26804. binding = bindingsForPath[index];
  26805. bindingsForPath[index] = firstActive;
  26806. bindingsForPath[lastCachedIndex] = binding;
  26807. }
  26808. }
  26809. } // for arguments
  26810. this.nCachedObjects_ = nCachedObjects;
  26811. },
  26812. // remove & forget
  26813. uncache: function () {
  26814. var objects = this._objects,
  26815. nObjects = objects.length,
  26816. nCachedObjects = this.nCachedObjects_,
  26817. indicesByUUID = this._indicesByUUID,
  26818. bindings = this._bindings,
  26819. nBindings = bindings.length;
  26820. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26821. var object = arguments[i],
  26822. uuid = object.uuid,
  26823. index = indicesByUUID[uuid];
  26824. if (index !== undefined) {
  26825. delete indicesByUUID[uuid];
  26826. if (index < nCachedObjects) {
  26827. // object is cached, shrink the CACHED region
  26828. var firstActiveIndex = --nCachedObjects,
  26829. lastCachedObject = objects[firstActiveIndex],
  26830. lastIndex = --nObjects,
  26831. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26832. indicesByUUID[lastCachedObject.uuid] = index;
  26833. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26834. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26835. objects[firstActiveIndex] = lastObject;
  26836. objects.pop(); // accounting is done, now do the same for all bindings
  26837. for (var j = 0, m = nBindings; j !== m; ++j) {
  26838. var bindingsForPath = bindings[j],
  26839. lastCached = bindingsForPath[firstActiveIndex],
  26840. last = bindingsForPath[lastIndex];
  26841. bindingsForPath[index] = lastCached;
  26842. bindingsForPath[firstActiveIndex] = last;
  26843. bindingsForPath.pop();
  26844. }
  26845. } else {
  26846. // object is active, just swap with the last and pop
  26847. var lastIndex = --nObjects,
  26848. lastObject = objects[lastIndex];
  26849. indicesByUUID[lastObject.uuid] = index;
  26850. objects[index] = lastObject;
  26851. objects.pop(); // accounting is done, now do the same for all bindings
  26852. for (var j = 0, m = nBindings; j !== m; ++j) {
  26853. var bindingsForPath = bindings[j];
  26854. bindingsForPath[index] = bindingsForPath[lastIndex];
  26855. bindingsForPath.pop();
  26856. }
  26857. } // cached or active
  26858. } // if object is known
  26859. } // for arguments
  26860. this.nCachedObjects_ = nCachedObjects;
  26861. },
  26862. // Internal interface used by befriended PropertyBinding.Composite:
  26863. subscribe_: function (path, parsedPath) {
  26864. // returns an array of bindings for the given path that is changed
  26865. // according to the contained objects in the group
  26866. var indicesByPath = this._bindingsIndicesByPath,
  26867. index = indicesByPath[path],
  26868. bindings = this._bindings;
  26869. if (index !== undefined) return bindings[index];
  26870. var paths = this._paths,
  26871. parsedPaths = this._parsedPaths,
  26872. objects = this._objects,
  26873. nObjects = objects.length,
  26874. nCachedObjects = this.nCachedObjects_,
  26875. bindingsForPath = new Array(nObjects);
  26876. index = bindings.length;
  26877. indicesByPath[path] = index;
  26878. paths.push(path);
  26879. parsedPaths.push(parsedPath);
  26880. bindings.push(bindingsForPath);
  26881. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26882. var object = objects[i];
  26883. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26884. }
  26885. return bindingsForPath;
  26886. },
  26887. unsubscribe_: function (path) {
  26888. // tells the group to forget about a property path and no longer
  26889. // update the array previously obtained with 'subscribe_'
  26890. var indicesByPath = this._bindingsIndicesByPath,
  26891. index = indicesByPath[path];
  26892. if (index !== undefined) {
  26893. var paths = this._paths,
  26894. parsedPaths = this._parsedPaths,
  26895. bindings = this._bindings,
  26896. lastBindingsIndex = bindings.length - 1,
  26897. lastBindings = bindings[lastBindingsIndex],
  26898. lastBindingsPath = path[lastBindingsIndex];
  26899. indicesByPath[lastBindingsPath] = index;
  26900. bindings[index] = lastBindings;
  26901. bindings.pop();
  26902. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26903. parsedPaths.pop();
  26904. paths[index] = paths[lastBindingsIndex];
  26905. paths.pop();
  26906. }
  26907. }
  26908. });
  26909. /**
  26910. *
  26911. * Action provided by AnimationMixer for scheduling clip playback on specific
  26912. * objects.
  26913. *
  26914. * @author Ben Houston / http://clara.io/
  26915. * @author David Sarno / http://lighthaus.us/
  26916. * @author tschw
  26917. *
  26918. */
  26919. function AnimationAction(mixer, clip, localRoot) {
  26920. this._mixer = mixer;
  26921. this._clip = clip;
  26922. this._localRoot = localRoot || null;
  26923. var tracks = clip.tracks,
  26924. nTracks = tracks.length,
  26925. interpolants = new Array(nTracks);
  26926. var interpolantSettings = {
  26927. endingStart: ZeroCurvatureEnding,
  26928. endingEnd: ZeroCurvatureEnding
  26929. };
  26930. for (var i = 0; i !== nTracks; ++i) {
  26931. var interpolant = tracks[i].createInterpolant(null);
  26932. interpolants[i] = interpolant;
  26933. interpolant.settings = interpolantSettings;
  26934. }
  26935. this._interpolantSettings = interpolantSettings;
  26936. this._interpolants = interpolants; // bound by the mixer
  26937. // inside: PropertyMixer (managed by the mixer)
  26938. this._propertyBindings = new Array(nTracks);
  26939. this._cacheIndex = null; // for the memory manager
  26940. this._byClipCacheIndex = null; // for the memory manager
  26941. this._timeScaleInterpolant = null;
  26942. this._weightInterpolant = null;
  26943. this.loop = LoopRepeat;
  26944. this._loopCount = -1; // global mixer time when the action is to be started
  26945. // it's set back to 'null' upon start of the action
  26946. this._startTime = null; // scaled local time of the action
  26947. // gets clamped or wrapped to 0..clip.duration according to loop
  26948. this.time = 0;
  26949. this.timeScale = 1;
  26950. this._effectiveTimeScale = 1;
  26951. this.weight = 1;
  26952. this._effectiveWeight = 1;
  26953. this.repetitions = Infinity; // no. of repetitions when looping
  26954. this.paused = false; // true -> zero effective time scale
  26955. this.enabled = true; // false -> zero effective weight
  26956. this.clampWhenFinished = false; // keep feeding the last frame?
  26957. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26958. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26959. }
  26960. Object.assign(AnimationAction.prototype, {
  26961. // State & Scheduling
  26962. play: function () {
  26963. this._mixer._activateAction(this);
  26964. return this;
  26965. },
  26966. stop: function () {
  26967. this._mixer._deactivateAction(this);
  26968. return this.reset();
  26969. },
  26970. reset: function () {
  26971. this.paused = false;
  26972. this.enabled = true;
  26973. this.time = 0; // restart clip
  26974. this._loopCount = -1; // forget previous loops
  26975. this._startTime = null; // forget scheduling
  26976. return this.stopFading().stopWarping();
  26977. },
  26978. isRunning: function () {
  26979. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26980. },
  26981. // return true when play has been called
  26982. isScheduled: function () {
  26983. return this._mixer._isActiveAction(this);
  26984. },
  26985. startAt: function (time) {
  26986. this._startTime = time;
  26987. return this;
  26988. },
  26989. setLoop: function (mode, repetitions) {
  26990. this.loop = mode;
  26991. this.repetitions = repetitions;
  26992. return this;
  26993. },
  26994. // Weight
  26995. // set the weight stopping any scheduled fading
  26996. // although .enabled = false yields an effective weight of zero, this
  26997. // method does *not* change .enabled, because it would be confusing
  26998. setEffectiveWeight: function (weight) {
  26999. this.weight = weight; // note: same logic as when updated at runtime
  27000. this._effectiveWeight = this.enabled ? weight : 0;
  27001. return this.stopFading();
  27002. },
  27003. // return the weight considering fading and .enabled
  27004. getEffectiveWeight: function () {
  27005. return this._effectiveWeight;
  27006. },
  27007. fadeIn: function (duration) {
  27008. return this._scheduleFading(duration, 0, 1);
  27009. },
  27010. fadeOut: function (duration) {
  27011. return this._scheduleFading(duration, 1, 0);
  27012. },
  27013. crossFadeFrom: function (fadeOutAction, duration, warp) {
  27014. fadeOutAction.fadeOut(duration);
  27015. this.fadeIn(duration);
  27016. if (warp) {
  27017. var fadeInDuration = this._clip.duration,
  27018. fadeOutDuration = fadeOutAction._clip.duration,
  27019. startEndRatio = fadeOutDuration / fadeInDuration,
  27020. endStartRatio = fadeInDuration / fadeOutDuration;
  27021. fadeOutAction.warp(1.0, startEndRatio, duration);
  27022. this.warp(endStartRatio, 1.0, duration);
  27023. }
  27024. return this;
  27025. },
  27026. crossFadeTo: function (fadeInAction, duration, warp) {
  27027. return fadeInAction.crossFadeFrom(this, duration, warp);
  27028. },
  27029. stopFading: function () {
  27030. var weightInterpolant = this._weightInterpolant;
  27031. if (weightInterpolant !== null) {
  27032. this._weightInterpolant = null;
  27033. this._mixer._takeBackControlInterpolant(weightInterpolant);
  27034. }
  27035. return this;
  27036. },
  27037. // Time Scale Control
  27038. // set the time scale stopping any scheduled warping
  27039. // although .paused = true yields an effective time scale of zero, this
  27040. // method does *not* change .paused, because it would be confusing
  27041. setEffectiveTimeScale: function (timeScale) {
  27042. this.timeScale = timeScale;
  27043. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27044. return this.stopWarping();
  27045. },
  27046. // return the time scale considering warping and .paused
  27047. getEffectiveTimeScale: function () {
  27048. return this._effectiveTimeScale;
  27049. },
  27050. setDuration: function (duration) {
  27051. this.timeScale = this._clip.duration / duration;
  27052. return this.stopWarping();
  27053. },
  27054. syncWith: function (action) {
  27055. this.time = action.time;
  27056. this.timeScale = action.timeScale;
  27057. return this.stopWarping();
  27058. },
  27059. halt: function (duration) {
  27060. return this.warp(this._effectiveTimeScale, 0, duration);
  27061. },
  27062. warp: function (startTimeScale, endTimeScale, duration) {
  27063. var mixer = this._mixer,
  27064. now = mixer.time,
  27065. interpolant = this._timeScaleInterpolant,
  27066. timeScale = this.timeScale;
  27067. if (interpolant === null) {
  27068. interpolant = mixer._lendControlInterpolant();
  27069. this._timeScaleInterpolant = interpolant;
  27070. }
  27071. var times = interpolant.parameterPositions,
  27072. values = interpolant.sampleValues;
  27073. times[0] = now;
  27074. times[1] = now + duration;
  27075. values[0] = startTimeScale / timeScale;
  27076. values[1] = endTimeScale / timeScale;
  27077. return this;
  27078. },
  27079. stopWarping: function () {
  27080. var timeScaleInterpolant = this._timeScaleInterpolant;
  27081. if (timeScaleInterpolant !== null) {
  27082. this._timeScaleInterpolant = null;
  27083. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  27084. }
  27085. return this;
  27086. },
  27087. // Object Accessors
  27088. getMixer: function () {
  27089. return this._mixer;
  27090. },
  27091. getClip: function () {
  27092. return this._clip;
  27093. },
  27094. getRoot: function () {
  27095. return this._localRoot || this._mixer._root;
  27096. },
  27097. // Interna
  27098. _update: function (time, deltaTime, timeDirection, accuIndex) {
  27099. // called by the mixer
  27100. if (!this.enabled) {
  27101. // call ._updateWeight() to update ._effectiveWeight
  27102. this._updateWeight(time);
  27103. return;
  27104. }
  27105. var startTime = this._startTime;
  27106. if (startTime !== null) {
  27107. // check for scheduled start of action
  27108. var timeRunning = (time - startTime) * timeDirection;
  27109. if (timeRunning < 0 || timeDirection === 0) {
  27110. return; // yet to come / don't decide when delta = 0
  27111. } // start
  27112. this._startTime = null; // unschedule
  27113. deltaTime = timeDirection * timeRunning;
  27114. } // apply time scale and advance time
  27115. deltaTime *= this._updateTimeScale(time);
  27116. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  27117. // an effective weight of 0
  27118. var weight = this._updateWeight(time);
  27119. if (weight > 0) {
  27120. var interpolants = this._interpolants;
  27121. var propertyMixers = this._propertyBindings;
  27122. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  27123. interpolants[j].evaluate(clipTime);
  27124. propertyMixers[j].accumulate(accuIndex, weight);
  27125. }
  27126. }
  27127. },
  27128. _updateWeight: function (time) {
  27129. var weight = 0;
  27130. if (this.enabled) {
  27131. weight = this.weight;
  27132. var interpolant = this._weightInterpolant;
  27133. if (interpolant !== null) {
  27134. var interpolantValue = interpolant.evaluate(time)[0];
  27135. weight *= interpolantValue;
  27136. if (time > interpolant.parameterPositions[1]) {
  27137. this.stopFading();
  27138. if (interpolantValue === 0) {
  27139. // faded out, disable
  27140. this.enabled = false;
  27141. }
  27142. }
  27143. }
  27144. }
  27145. this._effectiveWeight = weight;
  27146. return weight;
  27147. },
  27148. _updateTimeScale: function (time) {
  27149. var timeScale = 0;
  27150. if (!this.paused) {
  27151. timeScale = this.timeScale;
  27152. var interpolant = this._timeScaleInterpolant;
  27153. if (interpolant !== null) {
  27154. var interpolantValue = interpolant.evaluate(time)[0];
  27155. timeScale *= interpolantValue;
  27156. if (time > interpolant.parameterPositions[1]) {
  27157. this.stopWarping();
  27158. if (timeScale === 0) {
  27159. // motion has halted, pause
  27160. this.paused = true;
  27161. } else {
  27162. // warp done - apply final time scale
  27163. this.timeScale = timeScale;
  27164. }
  27165. }
  27166. }
  27167. }
  27168. this._effectiveTimeScale = timeScale;
  27169. return timeScale;
  27170. },
  27171. _updateTime: function (deltaTime) {
  27172. var time = this.time + deltaTime;
  27173. var duration = this._clip.duration;
  27174. var loop = this.loop;
  27175. var loopCount = this._loopCount;
  27176. var pingPong = loop === LoopPingPong;
  27177. if (deltaTime === 0) {
  27178. if (loopCount === -1) return time;
  27179. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27180. }
  27181. if (loop === LoopOnce) {
  27182. if (loopCount === -1) {
  27183. // just started
  27184. this._loopCount = 0;
  27185. this._setEndings(true, true, false);
  27186. }
  27187. handle_stop: {
  27188. if (time >= duration) {
  27189. time = duration;
  27190. } else if (time < 0) {
  27191. time = 0;
  27192. } else {
  27193. this.time = time;
  27194. break handle_stop;
  27195. }
  27196. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27197. this.time = time;
  27198. this._mixer.dispatchEvent({
  27199. type: 'finished',
  27200. action: this,
  27201. direction: deltaTime < 0 ? -1 : 1
  27202. });
  27203. }
  27204. } else {
  27205. // repetitive Repeat or PingPong
  27206. if (loopCount === -1) {
  27207. // just started
  27208. if (deltaTime >= 0) {
  27209. loopCount = 0;
  27210. this._setEndings(true, this.repetitions === 0, pingPong);
  27211. } else {
  27212. // when looping in reverse direction, the initial
  27213. // transition through zero counts as a repetition,
  27214. // so leave loopCount at -1
  27215. this._setEndings(this.repetitions === 0, true, pingPong);
  27216. }
  27217. }
  27218. if (time >= duration || time < 0) {
  27219. // wrap around
  27220. var loopDelta = Math.floor(time / duration); // signed
  27221. time -= duration * loopDelta;
  27222. loopCount += Math.abs(loopDelta);
  27223. var pending = this.repetitions - loopCount;
  27224. if (pending <= 0) {
  27225. // have to stop (switch state, clamp time, fire event)
  27226. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27227. time = deltaTime > 0 ? duration : 0;
  27228. this.time = time;
  27229. this._mixer.dispatchEvent({
  27230. type: 'finished',
  27231. action: this,
  27232. direction: deltaTime > 0 ? 1 : -1
  27233. });
  27234. } else {
  27235. // keep running
  27236. if (pending === 1) {
  27237. // entering the last round
  27238. var atStart = deltaTime < 0;
  27239. this._setEndings(atStart, !atStart, pingPong);
  27240. } else {
  27241. this._setEndings(false, false, pingPong);
  27242. }
  27243. this._loopCount = loopCount;
  27244. this.time = time;
  27245. this._mixer.dispatchEvent({
  27246. type: 'loop',
  27247. action: this,
  27248. loopDelta: loopDelta
  27249. });
  27250. }
  27251. } else {
  27252. this.time = time;
  27253. }
  27254. if (pingPong && (loopCount & 1) === 1) {
  27255. // invert time for the "pong round"
  27256. return duration - time;
  27257. }
  27258. }
  27259. return time;
  27260. },
  27261. _setEndings: function (atStart, atEnd, pingPong) {
  27262. var settings = this._interpolantSettings;
  27263. if (pingPong) {
  27264. settings.endingStart = ZeroSlopeEnding;
  27265. settings.endingEnd = ZeroSlopeEnding;
  27266. } else {
  27267. // assuming for LoopOnce atStart == atEnd == true
  27268. if (atStart) {
  27269. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27270. } else {
  27271. settings.endingStart = WrapAroundEnding;
  27272. }
  27273. if (atEnd) {
  27274. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27275. } else {
  27276. settings.endingEnd = WrapAroundEnding;
  27277. }
  27278. }
  27279. },
  27280. _scheduleFading: function (duration, weightNow, weightThen) {
  27281. var mixer = this._mixer,
  27282. now = mixer.time,
  27283. interpolant = this._weightInterpolant;
  27284. if (interpolant === null) {
  27285. interpolant = mixer._lendControlInterpolant();
  27286. this._weightInterpolant = interpolant;
  27287. }
  27288. var times = interpolant.parameterPositions,
  27289. values = interpolant.sampleValues;
  27290. times[0] = now;
  27291. values[0] = weightNow;
  27292. times[1] = now + duration;
  27293. values[1] = weightThen;
  27294. return this;
  27295. }
  27296. });
  27297. /**
  27298. *
  27299. * Player for AnimationClips.
  27300. *
  27301. *
  27302. * @author Ben Houston / http://clara.io/
  27303. * @author David Sarno / http://lighthaus.us/
  27304. * @author tschw
  27305. */
  27306. function AnimationMixer(root) {
  27307. this._root = root;
  27308. this._initMemoryManager();
  27309. this._accuIndex = 0;
  27310. this.time = 0;
  27311. this.timeScale = 1.0;
  27312. }
  27313. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  27314. constructor: AnimationMixer,
  27315. _bindAction: function (action, prototypeAction) {
  27316. var root = action._localRoot || this._root,
  27317. tracks = action._clip.tracks,
  27318. nTracks = tracks.length,
  27319. bindings = action._propertyBindings,
  27320. interpolants = action._interpolants,
  27321. rootUuid = root.uuid,
  27322. bindingsByRoot = this._bindingsByRootAndName,
  27323. bindingsByName = bindingsByRoot[rootUuid];
  27324. if (bindingsByName === undefined) {
  27325. bindingsByName = {};
  27326. bindingsByRoot[rootUuid] = bindingsByName;
  27327. }
  27328. for (var i = 0; i !== nTracks; ++i) {
  27329. var track = tracks[i],
  27330. trackName = track.name,
  27331. binding = bindingsByName[trackName];
  27332. if (binding !== undefined) {
  27333. bindings[i] = binding;
  27334. } else {
  27335. binding = bindings[i];
  27336. if (binding !== undefined) {
  27337. // existing binding, make sure the cache knows
  27338. if (binding._cacheIndex === null) {
  27339. ++binding.referenceCount;
  27340. this._addInactiveBinding(binding, rootUuid, trackName);
  27341. }
  27342. continue;
  27343. }
  27344. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27345. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27346. ++binding.referenceCount;
  27347. this._addInactiveBinding(binding, rootUuid, trackName);
  27348. bindings[i] = binding;
  27349. }
  27350. interpolants[i].resultBuffer = binding.buffer;
  27351. }
  27352. },
  27353. _activateAction: function (action) {
  27354. if (!this._isActiveAction(action)) {
  27355. if (action._cacheIndex === null) {
  27356. // this action has been forgotten by the cache, but the user
  27357. // appears to be still using it -> rebind
  27358. var rootUuid = (action._localRoot || this._root).uuid,
  27359. clipUuid = action._clip.uuid,
  27360. actionsForClip = this._actionsByClip[clipUuid];
  27361. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27362. this._addInactiveAction(action, clipUuid, rootUuid);
  27363. }
  27364. var bindings = action._propertyBindings; // increment reference counts / sort out state
  27365. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27366. var binding = bindings[i];
  27367. if (binding.useCount++ === 0) {
  27368. this._lendBinding(binding);
  27369. binding.saveOriginalState();
  27370. }
  27371. }
  27372. this._lendAction(action);
  27373. }
  27374. },
  27375. _deactivateAction: function (action) {
  27376. if (this._isActiveAction(action)) {
  27377. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  27378. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27379. var binding = bindings[i];
  27380. if (--binding.useCount === 0) {
  27381. binding.restoreOriginalState();
  27382. this._takeBackBinding(binding);
  27383. }
  27384. }
  27385. this._takeBackAction(action);
  27386. }
  27387. },
  27388. // Memory manager
  27389. _initMemoryManager: function () {
  27390. this._actions = []; // 'nActiveActions' followed by inactive ones
  27391. this._nActiveActions = 0;
  27392. this._actionsByClip = {}; // inside:
  27393. // {
  27394. // knownActions: Array< AnimationAction > - used as prototypes
  27395. // actionByRoot: AnimationAction - lookup
  27396. // }
  27397. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27398. this._nActiveBindings = 0;
  27399. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27400. this._controlInterpolants = []; // same game as above
  27401. this._nActiveControlInterpolants = 0;
  27402. var scope = this;
  27403. this.stats = {
  27404. actions: {
  27405. get total() {
  27406. return scope._actions.length;
  27407. },
  27408. get inUse() {
  27409. return scope._nActiveActions;
  27410. }
  27411. },
  27412. bindings: {
  27413. get total() {
  27414. return scope._bindings.length;
  27415. },
  27416. get inUse() {
  27417. return scope._nActiveBindings;
  27418. }
  27419. },
  27420. controlInterpolants: {
  27421. get total() {
  27422. return scope._controlInterpolants.length;
  27423. },
  27424. get inUse() {
  27425. return scope._nActiveControlInterpolants;
  27426. }
  27427. }
  27428. };
  27429. },
  27430. // Memory management for AnimationAction objects
  27431. _isActiveAction: function (action) {
  27432. var index = action._cacheIndex;
  27433. return index !== null && index < this._nActiveActions;
  27434. },
  27435. _addInactiveAction: function (action, clipUuid, rootUuid) {
  27436. var actions = this._actions,
  27437. actionsByClip = this._actionsByClip,
  27438. actionsForClip = actionsByClip[clipUuid];
  27439. if (actionsForClip === undefined) {
  27440. actionsForClip = {
  27441. knownActions: [action],
  27442. actionByRoot: {}
  27443. };
  27444. action._byClipCacheIndex = 0;
  27445. actionsByClip[clipUuid] = actionsForClip;
  27446. } else {
  27447. var knownActions = actionsForClip.knownActions;
  27448. action._byClipCacheIndex = knownActions.length;
  27449. knownActions.push(action);
  27450. }
  27451. action._cacheIndex = actions.length;
  27452. actions.push(action);
  27453. actionsForClip.actionByRoot[rootUuid] = action;
  27454. },
  27455. _removeInactiveAction: function (action) {
  27456. var actions = this._actions,
  27457. lastInactiveAction = actions[actions.length - 1],
  27458. cacheIndex = action._cacheIndex;
  27459. lastInactiveAction._cacheIndex = cacheIndex;
  27460. actions[cacheIndex] = lastInactiveAction;
  27461. actions.pop();
  27462. action._cacheIndex = null;
  27463. var clipUuid = action._clip.uuid,
  27464. actionsByClip = this._actionsByClip,
  27465. actionsForClip = actionsByClip[clipUuid],
  27466. knownActionsForClip = actionsForClip.knownActions,
  27467. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27468. byClipCacheIndex = action._byClipCacheIndex;
  27469. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27470. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27471. knownActionsForClip.pop();
  27472. action._byClipCacheIndex = null;
  27473. var actionByRoot = actionsForClip.actionByRoot,
  27474. rootUuid = (action._localRoot || this._root).uuid;
  27475. delete actionByRoot[rootUuid];
  27476. if (knownActionsForClip.length === 0) {
  27477. delete actionsByClip[clipUuid];
  27478. }
  27479. this._removeInactiveBindingsForAction(action);
  27480. },
  27481. _removeInactiveBindingsForAction: function (action) {
  27482. var bindings = action._propertyBindings;
  27483. for (var i = 0, n = bindings.length; i !== n; ++i) {
  27484. var binding = bindings[i];
  27485. if (--binding.referenceCount === 0) {
  27486. this._removeInactiveBinding(binding);
  27487. }
  27488. }
  27489. },
  27490. _lendAction: function (action) {
  27491. // [ active actions | inactive actions ]
  27492. // [ active actions >| inactive actions ]
  27493. // s a
  27494. // <-swap->
  27495. // a s
  27496. var actions = this._actions,
  27497. prevIndex = action._cacheIndex,
  27498. lastActiveIndex = this._nActiveActions++,
  27499. firstInactiveAction = actions[lastActiveIndex];
  27500. action._cacheIndex = lastActiveIndex;
  27501. actions[lastActiveIndex] = action;
  27502. firstInactiveAction._cacheIndex = prevIndex;
  27503. actions[prevIndex] = firstInactiveAction;
  27504. },
  27505. _takeBackAction: function (action) {
  27506. // [ active actions | inactive actions ]
  27507. // [ active actions |< inactive actions ]
  27508. // a s
  27509. // <-swap->
  27510. // s a
  27511. var actions = this._actions,
  27512. prevIndex = action._cacheIndex,
  27513. firstInactiveIndex = --this._nActiveActions,
  27514. lastActiveAction = actions[firstInactiveIndex];
  27515. action._cacheIndex = firstInactiveIndex;
  27516. actions[firstInactiveIndex] = action;
  27517. lastActiveAction._cacheIndex = prevIndex;
  27518. actions[prevIndex] = lastActiveAction;
  27519. },
  27520. // Memory management for PropertyMixer objects
  27521. _addInactiveBinding: function (binding, rootUuid, trackName) {
  27522. var bindingsByRoot = this._bindingsByRootAndName,
  27523. bindingByName = bindingsByRoot[rootUuid],
  27524. bindings = this._bindings;
  27525. if (bindingByName === undefined) {
  27526. bindingByName = {};
  27527. bindingsByRoot[rootUuid] = bindingByName;
  27528. }
  27529. bindingByName[trackName] = binding;
  27530. binding._cacheIndex = bindings.length;
  27531. bindings.push(binding);
  27532. },
  27533. _removeInactiveBinding: function (binding) {
  27534. var bindings = this._bindings,
  27535. propBinding = binding.binding,
  27536. rootUuid = propBinding.rootNode.uuid,
  27537. trackName = propBinding.path,
  27538. bindingsByRoot = this._bindingsByRootAndName,
  27539. bindingByName = bindingsByRoot[rootUuid],
  27540. lastInactiveBinding = bindings[bindings.length - 1],
  27541. cacheIndex = binding._cacheIndex;
  27542. lastInactiveBinding._cacheIndex = cacheIndex;
  27543. bindings[cacheIndex] = lastInactiveBinding;
  27544. bindings.pop();
  27545. delete bindingByName[trackName];
  27546. if (Object.keys(bindingByName).length === 0) {
  27547. delete bindingsByRoot[rootUuid];
  27548. }
  27549. },
  27550. _lendBinding: function (binding) {
  27551. var bindings = this._bindings,
  27552. prevIndex = binding._cacheIndex,
  27553. lastActiveIndex = this._nActiveBindings++,
  27554. firstInactiveBinding = bindings[lastActiveIndex];
  27555. binding._cacheIndex = lastActiveIndex;
  27556. bindings[lastActiveIndex] = binding;
  27557. firstInactiveBinding._cacheIndex = prevIndex;
  27558. bindings[prevIndex] = firstInactiveBinding;
  27559. },
  27560. _takeBackBinding: function (binding) {
  27561. var bindings = this._bindings,
  27562. prevIndex = binding._cacheIndex,
  27563. firstInactiveIndex = --this._nActiveBindings,
  27564. lastActiveBinding = bindings[firstInactiveIndex];
  27565. binding._cacheIndex = firstInactiveIndex;
  27566. bindings[firstInactiveIndex] = binding;
  27567. lastActiveBinding._cacheIndex = prevIndex;
  27568. bindings[prevIndex] = lastActiveBinding;
  27569. },
  27570. // Memory management of Interpolants for weight and time scale
  27571. _lendControlInterpolant: function () {
  27572. var interpolants = this._controlInterpolants,
  27573. lastActiveIndex = this._nActiveControlInterpolants++,
  27574. interpolant = interpolants[lastActiveIndex];
  27575. if (interpolant === undefined) {
  27576. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  27577. interpolant.__cacheIndex = lastActiveIndex;
  27578. interpolants[lastActiveIndex] = interpolant;
  27579. }
  27580. return interpolant;
  27581. },
  27582. _takeBackControlInterpolant: function (interpolant) {
  27583. var interpolants = this._controlInterpolants,
  27584. prevIndex = interpolant.__cacheIndex,
  27585. firstInactiveIndex = --this._nActiveControlInterpolants,
  27586. lastActiveInterpolant = interpolants[firstInactiveIndex];
  27587. interpolant.__cacheIndex = firstInactiveIndex;
  27588. interpolants[firstInactiveIndex] = interpolant;
  27589. lastActiveInterpolant.__cacheIndex = prevIndex;
  27590. interpolants[prevIndex] = lastActiveInterpolant;
  27591. },
  27592. _controlInterpolantsResultBuffer: new Float32Array(1),
  27593. // return an action for a clip optionally using a custom root target
  27594. // object (this method allocates a lot of dynamic memory in case a
  27595. // previously unknown clip/root combination is specified)
  27596. clipAction: function (clip, optionalRoot) {
  27597. var root = optionalRoot || this._root,
  27598. rootUuid = root.uuid,
  27599. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27600. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  27601. actionsForClip = this._actionsByClip[clipUuid],
  27602. prototypeAction = null;
  27603. if (actionsForClip !== undefined) {
  27604. var existingAction = actionsForClip.actionByRoot[rootUuid];
  27605. if (existingAction !== undefined) {
  27606. return existingAction;
  27607. } // we know the clip, so we don't have to parse all
  27608. // the bindings again but can just copy
  27609. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27610. if (clipObject === null) clipObject = prototypeAction._clip;
  27611. } // clip must be known when specified via string
  27612. if (clipObject === null) return null; // allocate all resources required to run it
  27613. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  27614. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27615. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27616. return newAction;
  27617. },
  27618. // get an existing action
  27619. existingAction: function (clip, optionalRoot) {
  27620. var root = optionalRoot || this._root,
  27621. rootUuid = root.uuid,
  27622. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27623. clipUuid = clipObject ? clipObject.uuid : clip,
  27624. actionsForClip = this._actionsByClip[clipUuid];
  27625. if (actionsForClip !== undefined) {
  27626. return actionsForClip.actionByRoot[rootUuid] || null;
  27627. }
  27628. return null;
  27629. },
  27630. // deactivates all previously scheduled actions
  27631. stopAllAction: function () {
  27632. var actions = this._actions,
  27633. nActions = this._nActiveActions,
  27634. bindings = this._bindings,
  27635. nBindings = this._nActiveBindings;
  27636. this._nActiveActions = 0;
  27637. this._nActiveBindings = 0;
  27638. for (var i = 0; i !== nActions; ++i) {
  27639. actions[i].reset();
  27640. }
  27641. for (var i = 0; i !== nBindings; ++i) {
  27642. bindings[i].useCount = 0;
  27643. }
  27644. return this;
  27645. },
  27646. // advance the time and update apply the animation
  27647. update: function (deltaTime) {
  27648. deltaTime *= this.timeScale;
  27649. var actions = this._actions,
  27650. nActions = this._nActiveActions,
  27651. time = this.time += deltaTime,
  27652. timeDirection = Math.sign(deltaTime),
  27653. accuIndex = this._accuIndex ^= 1; // run active actions
  27654. for (var i = 0; i !== nActions; ++i) {
  27655. var action = actions[i];
  27656. action._update(time, deltaTime, timeDirection, accuIndex);
  27657. } // update scene graph
  27658. var bindings = this._bindings,
  27659. nBindings = this._nActiveBindings;
  27660. for (var i = 0; i !== nBindings; ++i) {
  27661. bindings[i].apply(accuIndex);
  27662. }
  27663. return this;
  27664. },
  27665. // Allows you to seek to a specific time in an animation.
  27666. setTime: function (timeInSeconds) {
  27667. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27668. for (var i = 0; i < this._actions.length; i++) {
  27669. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27670. }
  27671. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27672. },
  27673. // return this mixer's root target object
  27674. getRoot: function () {
  27675. return this._root;
  27676. },
  27677. // free all resources specific to a particular clip
  27678. uncacheClip: function (clip) {
  27679. var actions = this._actions,
  27680. clipUuid = clip.uuid,
  27681. actionsByClip = this._actionsByClip,
  27682. actionsForClip = actionsByClip[clipUuid];
  27683. if (actionsForClip !== undefined) {
  27684. // note: just calling _removeInactiveAction would mess up the
  27685. // iteration state and also require updating the state we can
  27686. // just throw away
  27687. var actionsToRemove = actionsForClip.knownActions;
  27688. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27689. var action = actionsToRemove[i];
  27690. this._deactivateAction(action);
  27691. var cacheIndex = action._cacheIndex,
  27692. lastInactiveAction = actions[actions.length - 1];
  27693. action._cacheIndex = null;
  27694. action._byClipCacheIndex = null;
  27695. lastInactiveAction._cacheIndex = cacheIndex;
  27696. actions[cacheIndex] = lastInactiveAction;
  27697. actions.pop();
  27698. this._removeInactiveBindingsForAction(action);
  27699. }
  27700. delete actionsByClip[clipUuid];
  27701. }
  27702. },
  27703. // free all resources specific to a particular root target object
  27704. uncacheRoot: function (root) {
  27705. var rootUuid = root.uuid,
  27706. actionsByClip = this._actionsByClip;
  27707. for (var clipUuid in actionsByClip) {
  27708. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27709. action = actionByRoot[rootUuid];
  27710. if (action !== undefined) {
  27711. this._deactivateAction(action);
  27712. this._removeInactiveAction(action);
  27713. }
  27714. }
  27715. var bindingsByRoot = this._bindingsByRootAndName,
  27716. bindingByName = bindingsByRoot[rootUuid];
  27717. if (bindingByName !== undefined) {
  27718. for (var trackName in bindingByName) {
  27719. var binding = bindingByName[trackName];
  27720. binding.restoreOriginalState();
  27721. this._removeInactiveBinding(binding);
  27722. }
  27723. }
  27724. },
  27725. // remove a targeted clip from the cache
  27726. uncacheAction: function (clip, optionalRoot) {
  27727. var action = this.existingAction(clip, optionalRoot);
  27728. if (action !== null) {
  27729. this._deactivateAction(action);
  27730. this._removeInactiveAction(action);
  27731. }
  27732. }
  27733. });
  27734. /**
  27735. * @author mrdoob / http://mrdoob.com/
  27736. */
  27737. function Uniform(value) {
  27738. if (typeof value === 'string') {
  27739. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27740. value = arguments[1];
  27741. }
  27742. this.value = value;
  27743. }
  27744. Uniform.prototype.clone = function () {
  27745. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27746. };
  27747. /**
  27748. * @author benaadams / https://twitter.com/ben_a_adams
  27749. */
  27750. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27751. InterleavedBuffer.call(this, array, stride);
  27752. this.meshPerAttribute = meshPerAttribute || 1;
  27753. }
  27754. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27755. constructor: InstancedInterleavedBuffer,
  27756. isInstancedInterleavedBuffer: true,
  27757. copy: function (source) {
  27758. InterleavedBuffer.prototype.copy.call(this, source);
  27759. this.meshPerAttribute = source.meshPerAttribute;
  27760. return this;
  27761. }
  27762. });
  27763. /**
  27764. * @author mrdoob / http://mrdoob.com/
  27765. * @author bhouston / http://clara.io/
  27766. * @author stephomi / http://stephaneginier.com/
  27767. */
  27768. function Raycaster(origin, direction, near, far) {
  27769. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27770. this.near = near || 0;
  27771. this.far = far || Infinity;
  27772. this.camera = null;
  27773. this.params = {
  27774. Mesh: {},
  27775. Line: {},
  27776. LOD: {},
  27777. Points: {
  27778. threshold: 1
  27779. },
  27780. Sprite: {}
  27781. };
  27782. Object.defineProperties(this.params, {
  27783. PointCloud: {
  27784. get: function () {
  27785. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27786. return this.Points;
  27787. }
  27788. }
  27789. });
  27790. }
  27791. function ascSort(a, b) {
  27792. return a.distance - b.distance;
  27793. }
  27794. function intersectObject(object, raycaster, intersects, recursive) {
  27795. if (object.visible === false) return;
  27796. object.raycast(raycaster, intersects);
  27797. if (recursive === true) {
  27798. var children = object.children;
  27799. for (var i = 0, l = children.length; i < l; i++) {
  27800. intersectObject(children[i], raycaster, intersects, true);
  27801. }
  27802. }
  27803. }
  27804. Object.assign(Raycaster.prototype, {
  27805. linePrecision: 1,
  27806. set: function (origin, direction) {
  27807. // direction is assumed to be normalized (for accurate distance calculations)
  27808. this.ray.set(origin, direction);
  27809. },
  27810. setFromCamera: function (coords, camera) {
  27811. if (camera && camera.isPerspectiveCamera) {
  27812. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27813. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27814. this.camera = camera;
  27815. } else if (camera && camera.isOrthographicCamera) {
  27816. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27817. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27818. this.camera = camera;
  27819. } else {
  27820. console.error('THREE.Raycaster: Unsupported camera type.');
  27821. }
  27822. },
  27823. intersectObject: function (object, recursive, optionalTarget) {
  27824. var intersects = optionalTarget || [];
  27825. intersectObject(object, this, intersects, recursive);
  27826. intersects.sort(ascSort);
  27827. return intersects;
  27828. },
  27829. intersectObjects: function (objects, recursive, optionalTarget) {
  27830. var intersects = optionalTarget || [];
  27831. if (Array.isArray(objects) === false) {
  27832. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27833. return intersects;
  27834. }
  27835. for (var i = 0, l = objects.length; i < l; i++) {
  27836. intersectObject(objects[i], this, intersects, recursive);
  27837. }
  27838. intersects.sort(ascSort);
  27839. return intersects;
  27840. }
  27841. });
  27842. /**
  27843. * @author bhouston / http://clara.io
  27844. * @author WestLangley / http://github.com/WestLangley
  27845. *
  27846. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27847. *
  27848. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27849. * The azimuthal angle (theta) is measured from the positive z-axiz.
  27850. */
  27851. function Spherical(radius, phi, theta) {
  27852. this.radius = radius !== undefined ? radius : 1.0;
  27853. this.phi = phi !== undefined ? phi : 0; // polar angle
  27854. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  27855. return this;
  27856. }
  27857. Object.assign(Spherical.prototype, {
  27858. set: function (radius, phi, theta) {
  27859. this.radius = radius;
  27860. this.phi = phi;
  27861. this.theta = theta;
  27862. return this;
  27863. },
  27864. clone: function () {
  27865. return new this.constructor().copy(this);
  27866. },
  27867. copy: function (other) {
  27868. this.radius = other.radius;
  27869. this.phi = other.phi;
  27870. this.theta = other.theta;
  27871. return this;
  27872. },
  27873. // restrict phi to be betwee EPS and PI-EPS
  27874. makeSafe: function () {
  27875. var EPS = 0.000001;
  27876. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27877. return this;
  27878. },
  27879. setFromVector3: function (v) {
  27880. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27881. },
  27882. setFromCartesianCoords: function (x, y, z) {
  27883. this.radius = Math.sqrt(x * x + y * y + z * z);
  27884. if (this.radius === 0) {
  27885. this.theta = 0;
  27886. this.phi = 0;
  27887. } else {
  27888. this.theta = Math.atan2(x, z);
  27889. this.phi = Math.acos(_Math.clamp(y / this.radius, -1, 1));
  27890. }
  27891. return this;
  27892. }
  27893. });
  27894. /**
  27895. * @author Mugen87 / https://github.com/Mugen87
  27896. *
  27897. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27898. *
  27899. */
  27900. function Cylindrical(radius, theta, y) {
  27901. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27902. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27903. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27904. return this;
  27905. }
  27906. Object.assign(Cylindrical.prototype, {
  27907. set: function (radius, theta, y) {
  27908. this.radius = radius;
  27909. this.theta = theta;
  27910. this.y = y;
  27911. return this;
  27912. },
  27913. clone: function () {
  27914. return new this.constructor().copy(this);
  27915. },
  27916. copy: function (other) {
  27917. this.radius = other.radius;
  27918. this.theta = other.theta;
  27919. this.y = other.y;
  27920. return this;
  27921. },
  27922. setFromVector3: function (v) {
  27923. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27924. },
  27925. setFromCartesianCoords: function (x, y, z) {
  27926. this.radius = Math.sqrt(x * x + z * z);
  27927. this.theta = Math.atan2(x, z);
  27928. this.y = y;
  27929. return this;
  27930. }
  27931. });
  27932. /**
  27933. * @author bhouston / http://clara.io
  27934. */
  27935. var _vector$6 = new Vector2();
  27936. function Box2(min, max) {
  27937. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27938. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27939. }
  27940. Object.assign(Box2.prototype, {
  27941. set: function (min, max) {
  27942. this.min.copy(min);
  27943. this.max.copy(max);
  27944. return this;
  27945. },
  27946. setFromPoints: function (points) {
  27947. this.makeEmpty();
  27948. for (var i = 0, il = points.length; i < il; i++) {
  27949. this.expandByPoint(points[i]);
  27950. }
  27951. return this;
  27952. },
  27953. setFromCenterAndSize: function (center, size) {
  27954. var halfSize = _vector$6.copy(size).multiplyScalar(0.5);
  27955. this.min.copy(center).sub(halfSize);
  27956. this.max.copy(center).add(halfSize);
  27957. return this;
  27958. },
  27959. clone: function () {
  27960. return new this.constructor().copy(this);
  27961. },
  27962. copy: function (box) {
  27963. this.min.copy(box.min);
  27964. this.max.copy(box.max);
  27965. return this;
  27966. },
  27967. makeEmpty: function () {
  27968. this.min.x = this.min.y = +Infinity;
  27969. this.max.x = this.max.y = -Infinity;
  27970. return this;
  27971. },
  27972. isEmpty: function () {
  27973. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27974. return this.max.x < this.min.x || this.max.y < this.min.y;
  27975. },
  27976. getCenter: function (target) {
  27977. if (target === undefined) {
  27978. console.warn('THREE.Box2: .getCenter() target is now required');
  27979. target = new Vector2();
  27980. }
  27981. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27982. },
  27983. getSize: function (target) {
  27984. if (target === undefined) {
  27985. console.warn('THREE.Box2: .getSize() target is now required');
  27986. target = new Vector2();
  27987. }
  27988. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27989. },
  27990. expandByPoint: function (point) {
  27991. this.min.min(point);
  27992. this.max.max(point);
  27993. return this;
  27994. },
  27995. expandByVector: function (vector) {
  27996. this.min.sub(vector);
  27997. this.max.add(vector);
  27998. return this;
  27999. },
  28000. expandByScalar: function (scalar) {
  28001. this.min.addScalar(-scalar);
  28002. this.max.addScalar(scalar);
  28003. return this;
  28004. },
  28005. containsPoint: function (point) {
  28006. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  28007. },
  28008. containsBox: function (box) {
  28009. 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;
  28010. },
  28011. getParameter: function (point, target) {
  28012. // This can potentially have a divide by zero if the box
  28013. // has a size dimension of 0.
  28014. if (target === undefined) {
  28015. console.warn('THREE.Box2: .getParameter() target is now required');
  28016. target = new Vector2();
  28017. }
  28018. 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));
  28019. },
  28020. intersectsBox: function (box) {
  28021. // using 4 splitting planes to rule out intersections
  28022. 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;
  28023. },
  28024. clampPoint: function (point, target) {
  28025. if (target === undefined) {
  28026. console.warn('THREE.Box2: .clampPoint() target is now required');
  28027. target = new Vector2();
  28028. }
  28029. return target.copy(point).clamp(this.min, this.max);
  28030. },
  28031. distanceToPoint: function (point) {
  28032. var clampedPoint = _vector$6.copy(point).clamp(this.min, this.max);
  28033. return clampedPoint.sub(point).length();
  28034. },
  28035. intersect: function (box) {
  28036. this.min.max(box.min);
  28037. this.max.min(box.max);
  28038. return this;
  28039. },
  28040. union: function (box) {
  28041. this.min.min(box.min);
  28042. this.max.max(box.max);
  28043. return this;
  28044. },
  28045. translate: function (offset) {
  28046. this.min.add(offset);
  28047. this.max.add(offset);
  28048. return this;
  28049. },
  28050. equals: function (box) {
  28051. return box.min.equals(this.min) && box.max.equals(this.max);
  28052. }
  28053. });
  28054. /**
  28055. * @author bhouston / http://clara.io
  28056. */
  28057. var _startP = new Vector3();
  28058. var _startEnd = new Vector3();
  28059. function Line3(start, end) {
  28060. this.start = start !== undefined ? start : new Vector3();
  28061. this.end = end !== undefined ? end : new Vector3();
  28062. }
  28063. Object.assign(Line3.prototype, {
  28064. set: function (start, end) {
  28065. this.start.copy(start);
  28066. this.end.copy(end);
  28067. return this;
  28068. },
  28069. clone: function () {
  28070. return new this.constructor().copy(this);
  28071. },
  28072. copy: function (line) {
  28073. this.start.copy(line.start);
  28074. this.end.copy(line.end);
  28075. return this;
  28076. },
  28077. getCenter: function (target) {
  28078. if (target === undefined) {
  28079. console.warn('THREE.Line3: .getCenter() target is now required');
  28080. target = new Vector3();
  28081. }
  28082. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  28083. },
  28084. delta: function (target) {
  28085. if (target === undefined) {
  28086. console.warn('THREE.Line3: .delta() target is now required');
  28087. target = new Vector3();
  28088. }
  28089. return target.subVectors(this.end, this.start);
  28090. },
  28091. distanceSq: function () {
  28092. return this.start.distanceToSquared(this.end);
  28093. },
  28094. distance: function () {
  28095. return this.start.distanceTo(this.end);
  28096. },
  28097. at: function (t, target) {
  28098. if (target === undefined) {
  28099. console.warn('THREE.Line3: .at() target is now required');
  28100. target = new Vector3();
  28101. }
  28102. return this.delta(target).multiplyScalar(t).add(this.start);
  28103. },
  28104. closestPointToPointParameter: function (point, clampToLine) {
  28105. _startP.subVectors(point, this.start);
  28106. _startEnd.subVectors(this.end, this.start);
  28107. var startEnd2 = _startEnd.dot(_startEnd);
  28108. var startEnd_startP = _startEnd.dot(_startP);
  28109. var t = startEnd_startP / startEnd2;
  28110. if (clampToLine) {
  28111. t = _Math.clamp(t, 0, 1);
  28112. }
  28113. return t;
  28114. },
  28115. closestPointToPoint: function (point, clampToLine, target) {
  28116. var t = this.closestPointToPointParameter(point, clampToLine);
  28117. if (target === undefined) {
  28118. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  28119. target = new Vector3();
  28120. }
  28121. return this.delta(target).multiplyScalar(t).add(this.start);
  28122. },
  28123. applyMatrix4: function (matrix) {
  28124. this.start.applyMatrix4(matrix);
  28125. this.end.applyMatrix4(matrix);
  28126. return this;
  28127. },
  28128. equals: function (line) {
  28129. return line.start.equals(this.start) && line.end.equals(this.end);
  28130. }
  28131. });
  28132. /**
  28133. * @author alteredq / http://alteredqualia.com/
  28134. */
  28135. function ImmediateRenderObject(material) {
  28136. Object3D.call(this);
  28137. this.material = material;
  28138. this.render = function ()
  28139. /* renderCallback */
  28140. {};
  28141. }
  28142. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  28143. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28144. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28145. /**
  28146. * @author mrdoob / http://mrdoob.com/
  28147. * @author WestLangley / http://github.com/WestLangley
  28148. */
  28149. var _v1$5 = new Vector3();
  28150. var _v2$3 = new Vector3();
  28151. var _normalMatrix$1 = new Matrix3();
  28152. var _keys = ['a', 'b', 'c'];
  28153. function VertexNormalsHelper(object, size, hex, linewidth) {
  28154. this.object = object;
  28155. this.size = size !== undefined ? size : 1;
  28156. var color = hex !== undefined ? hex : 0xff0000;
  28157. var width = linewidth !== undefined ? linewidth : 1; //
  28158. var nNormals = 0;
  28159. var objGeometry = this.object.geometry;
  28160. if (objGeometry && objGeometry.isGeometry) {
  28161. nNormals = objGeometry.faces.length * 3;
  28162. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28163. nNormals = objGeometry.attributes.normal.count;
  28164. } //
  28165. var geometry = new BufferGeometry();
  28166. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28167. geometry.addAttribute('position', positions);
  28168. LineSegments.call(this, geometry, new LineBasicMaterial({
  28169. color: color,
  28170. linewidth: width
  28171. })); //
  28172. this.matrixAutoUpdate = false;
  28173. this.update();
  28174. }
  28175. VertexNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28176. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  28177. VertexNormalsHelper.prototype.update = function () {
  28178. this.object.updateMatrixWorld(true);
  28179. _normalMatrix$1.getNormalMatrix(this.object.matrixWorld);
  28180. var matrixWorld = this.object.matrixWorld;
  28181. var position = this.geometry.attributes.position; //
  28182. var objGeometry = this.object.geometry;
  28183. if (objGeometry && objGeometry.isGeometry) {
  28184. var vertices = objGeometry.vertices;
  28185. var faces = objGeometry.faces;
  28186. var idx = 0;
  28187. for (var i = 0, l = faces.length; i < l; i++) {
  28188. var face = faces[i];
  28189. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  28190. var vertex = vertices[face[_keys[j]]];
  28191. var normal = face.vertexNormals[j];
  28192. _v1$5.copy(vertex).applyMatrix4(matrixWorld);
  28193. _v2$3.copy(normal).applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28194. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28195. idx = idx + 1;
  28196. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28197. idx = idx + 1;
  28198. }
  28199. }
  28200. } else if (objGeometry && objGeometry.isBufferGeometry) {
  28201. var objPos = objGeometry.attributes.position;
  28202. var objNorm = objGeometry.attributes.normal;
  28203. var idx = 0; // for simplicity, ignore index and drawcalls, and render every normal
  28204. for (var j = 0, jl = objPos.count; j < jl; j++) {
  28205. _v1$5.set(objPos.getX(j), objPos.getY(j), objPos.getZ(j)).applyMatrix4(matrixWorld);
  28206. _v2$3.set(objNorm.getX(j), objNorm.getY(j), objNorm.getZ(j));
  28207. _v2$3.applyMatrix3(_normalMatrix$1).normalize().multiplyScalar(this.size).add(_v1$5);
  28208. position.setXYZ(idx, _v1$5.x, _v1$5.y, _v1$5.z);
  28209. idx = idx + 1;
  28210. position.setXYZ(idx, _v2$3.x, _v2$3.y, _v2$3.z);
  28211. idx = idx + 1;
  28212. }
  28213. }
  28214. position.needsUpdate = true;
  28215. };
  28216. /**
  28217. * @author alteredq / http://alteredqualia.com/
  28218. * @author mrdoob / http://mrdoob.com/
  28219. * @author WestLangley / http://github.com/WestLangley
  28220. */
  28221. var _vector$7 = new Vector3();
  28222. function SpotLightHelper(light, color) {
  28223. Object3D.call(this);
  28224. this.light = light;
  28225. this.light.updateMatrixWorld();
  28226. this.matrix = light.matrixWorld;
  28227. this.matrixAutoUpdate = false;
  28228. this.color = color;
  28229. var geometry = new BufferGeometry();
  28230. 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];
  28231. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  28232. var p1 = i / l * Math.PI * 2;
  28233. var p2 = j / l * Math.PI * 2;
  28234. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28235. }
  28236. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28237. var material = new LineBasicMaterial({
  28238. fog: false
  28239. });
  28240. this.cone = new LineSegments(geometry, material);
  28241. this.add(this.cone);
  28242. this.update();
  28243. }
  28244. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  28245. SpotLightHelper.prototype.constructor = SpotLightHelper;
  28246. SpotLightHelper.prototype.dispose = function () {
  28247. this.cone.geometry.dispose();
  28248. this.cone.material.dispose();
  28249. };
  28250. SpotLightHelper.prototype.update = function () {
  28251. this.light.updateMatrixWorld();
  28252. var coneLength = this.light.distance ? this.light.distance : 1000;
  28253. var coneWidth = coneLength * Math.tan(this.light.angle);
  28254. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28255. _vector$7.setFromMatrixPosition(this.light.target.matrixWorld);
  28256. this.cone.lookAt(_vector$7);
  28257. if (this.color !== undefined) {
  28258. this.cone.material.color.set(this.color);
  28259. } else {
  28260. this.cone.material.color.copy(this.light.color);
  28261. }
  28262. };
  28263. /**
  28264. * @author Sean Griffin / http://twitter.com/sgrif
  28265. * @author Michael Guerrero / http://realitymeltdown.com
  28266. * @author mrdoob / http://mrdoob.com/
  28267. * @author ikerr / http://verold.com
  28268. * @author Mugen87 / https://github.com/Mugen87
  28269. */
  28270. var _vector$8 = new Vector3();
  28271. var _boneMatrix = new Matrix4();
  28272. var _matrixWorldInv = new Matrix4();
  28273. function getBoneList(object) {
  28274. var boneList = [];
  28275. if (object && object.isBone) {
  28276. boneList.push(object);
  28277. }
  28278. for (var i = 0; i < object.children.length; i++) {
  28279. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28280. }
  28281. return boneList;
  28282. }
  28283. function SkeletonHelper(object) {
  28284. var bones = getBoneList(object);
  28285. var geometry = new BufferGeometry();
  28286. var vertices = [];
  28287. var colors = [];
  28288. var color1 = new Color(0, 0, 1);
  28289. var color2 = new Color(0, 1, 0);
  28290. for (var i = 0; i < bones.length; i++) {
  28291. var bone = bones[i];
  28292. if (bone.parent && bone.parent.isBone) {
  28293. vertices.push(0, 0, 0);
  28294. vertices.push(0, 0, 0);
  28295. colors.push(color1.r, color1.g, color1.b);
  28296. colors.push(color2.r, color2.g, color2.b);
  28297. }
  28298. }
  28299. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28300. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28301. var material = new LineBasicMaterial({
  28302. vertexColors: VertexColors,
  28303. depthTest: false,
  28304. depthWrite: false,
  28305. transparent: true
  28306. });
  28307. LineSegments.call(this, geometry, material);
  28308. this.root = object;
  28309. this.bones = bones;
  28310. this.matrix = object.matrixWorld;
  28311. this.matrixAutoUpdate = false;
  28312. }
  28313. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  28314. SkeletonHelper.prototype.constructor = SkeletonHelper;
  28315. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  28316. var bones = this.bones;
  28317. var geometry = this.geometry;
  28318. var position = geometry.getAttribute('position');
  28319. _matrixWorldInv.getInverse(this.root.matrixWorld);
  28320. for (var i = 0, j = 0; i < bones.length; i++) {
  28321. var bone = bones[i];
  28322. if (bone.parent && bone.parent.isBone) {
  28323. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28324. _vector$8.setFromMatrixPosition(_boneMatrix);
  28325. position.setXYZ(j, _vector$8.x, _vector$8.y, _vector$8.z);
  28326. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28327. _vector$8.setFromMatrixPosition(_boneMatrix);
  28328. position.setXYZ(j + 1, _vector$8.x, _vector$8.y, _vector$8.z);
  28329. j += 2;
  28330. }
  28331. }
  28332. geometry.getAttribute('position').needsUpdate = true;
  28333. Object3D.prototype.updateMatrixWorld.call(this, force);
  28334. };
  28335. /**
  28336. * @author alteredq / http://alteredqualia.com/
  28337. * @author mrdoob / http://mrdoob.com/
  28338. */
  28339. function PointLightHelper(light, sphereSize, color) {
  28340. this.light = light;
  28341. this.light.updateMatrixWorld();
  28342. this.color = color;
  28343. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  28344. var material = new MeshBasicMaterial({
  28345. wireframe: true,
  28346. fog: false
  28347. });
  28348. Mesh.call(this, geometry, material);
  28349. this.matrix = this.light.matrixWorld;
  28350. this.matrixAutoUpdate = false;
  28351. this.update();
  28352. /*
  28353. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28354. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28355. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28356. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28357. var d = light.distance;
  28358. if ( d === 0.0 ) {
  28359. this.lightDistance.visible = false;
  28360. } else {
  28361. this.lightDistance.scale.set( d, d, d );
  28362. }
  28363. this.add( this.lightDistance );
  28364. */
  28365. }
  28366. PointLightHelper.prototype = Object.create(Mesh.prototype);
  28367. PointLightHelper.prototype.constructor = PointLightHelper;
  28368. PointLightHelper.prototype.dispose = function () {
  28369. this.geometry.dispose();
  28370. this.material.dispose();
  28371. };
  28372. PointLightHelper.prototype.update = function () {
  28373. if (this.color !== undefined) {
  28374. this.material.color.set(this.color);
  28375. } else {
  28376. this.material.color.copy(this.light.color);
  28377. }
  28378. /*
  28379. var d = this.light.distance;
  28380. if ( d === 0.0 ) {
  28381. this.lightDistance.visible = false;
  28382. } else {
  28383. this.lightDistance.visible = true;
  28384. this.lightDistance.scale.set( d, d, d );
  28385. }
  28386. */
  28387. };
  28388. /**
  28389. * @author abelnation / http://github.com/abelnation
  28390. * @author Mugen87 / http://github.com/Mugen87
  28391. * @author WestLangley / http://github.com/WestLangley
  28392. *
  28393. * This helper must be added as a child of the light
  28394. */
  28395. function RectAreaLightHelper(light, color) {
  28396. this.type = 'RectAreaLightHelper';
  28397. this.light = light;
  28398. this.color = color; // optional hardwired color for the helper
  28399. var positions = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
  28400. var geometry = new BufferGeometry();
  28401. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  28402. geometry.computeBoundingSphere();
  28403. var material = new LineBasicMaterial({
  28404. fog: false
  28405. });
  28406. Line.call(this, geometry, material); //
  28407. var positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  28408. var geometry2 = new BufferGeometry();
  28409. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  28410. geometry2.computeBoundingSphere();
  28411. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28412. side: BackSide,
  28413. fog: false
  28414. })));
  28415. this.update();
  28416. }
  28417. RectAreaLightHelper.prototype = Object.create(Line.prototype);
  28418. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  28419. RectAreaLightHelper.prototype.update = function () {
  28420. this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);
  28421. if (this.color !== undefined) {
  28422. this.material.color.set(this.color);
  28423. this.children[0].material.color.set(this.color);
  28424. } else {
  28425. this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity); // prevent hue shift
  28426. var c = this.material.color;
  28427. var max = Math.max(c.r, c.g, c.b);
  28428. if (max > 1) c.multiplyScalar(1 / max);
  28429. this.children[0].material.color.copy(this.material.color);
  28430. }
  28431. };
  28432. RectAreaLightHelper.prototype.dispose = function () {
  28433. this.geometry.dispose();
  28434. this.material.dispose();
  28435. this.children[0].geometry.dispose();
  28436. this.children[0].material.dispose();
  28437. };
  28438. /**
  28439. * @author alteredq / http://alteredqualia.com/
  28440. * @author mrdoob / http://mrdoob.com/
  28441. * @author Mugen87 / https://github.com/Mugen87
  28442. */
  28443. var _vector$9 = new Vector3();
  28444. var _color1 = new Color();
  28445. var _color2 = new Color();
  28446. function HemisphereLightHelper(light, size, color) {
  28447. Object3D.call(this);
  28448. this.light = light;
  28449. this.light.updateMatrixWorld();
  28450. this.matrix = light.matrixWorld;
  28451. this.matrixAutoUpdate = false;
  28452. this.color = color;
  28453. var geometry = new OctahedronBufferGeometry(size);
  28454. geometry.rotateY(Math.PI * 0.5);
  28455. this.material = new MeshBasicMaterial({
  28456. wireframe: true,
  28457. fog: false
  28458. });
  28459. if (this.color === undefined) this.material.vertexColors = VertexColors;
  28460. var position = geometry.getAttribute('position');
  28461. var colors = new Float32Array(position.count * 3);
  28462. geometry.addAttribute('color', new BufferAttribute(colors, 3));
  28463. this.add(new Mesh(geometry, this.material));
  28464. this.update();
  28465. }
  28466. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  28467. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  28468. HemisphereLightHelper.prototype.dispose = function () {
  28469. this.children[0].geometry.dispose();
  28470. this.children[0].material.dispose();
  28471. };
  28472. HemisphereLightHelper.prototype.update = function () {
  28473. var mesh = this.children[0];
  28474. if (this.color !== undefined) {
  28475. this.material.color.set(this.color);
  28476. } else {
  28477. var colors = mesh.geometry.getAttribute('color');
  28478. _color1.copy(this.light.color);
  28479. _color2.copy(this.light.groundColor);
  28480. for (var i = 0, l = colors.count; i < l; i++) {
  28481. var color = i < l / 2 ? _color1 : _color2;
  28482. colors.setXYZ(i, color.r, color.g, color.b);
  28483. }
  28484. colors.needsUpdate = true;
  28485. }
  28486. mesh.lookAt(_vector$9.setFromMatrixPosition(this.light.matrixWorld).negate());
  28487. };
  28488. /**
  28489. * @author WestLangley / http://github.com/WestLangley
  28490. */
  28491. function LightProbeHelper(lightProbe, size) {
  28492. this.lightProbe = lightProbe;
  28493. this.size = size;
  28494. var defines = {};
  28495. defines['GAMMA_OUTPUT'] = ""; // material
  28496. var material = new ShaderMaterial({
  28497. defines: defines,
  28498. uniforms: {
  28499. sh: {
  28500. value: this.lightProbe.sh.coefficients
  28501. },
  28502. // by reference
  28503. intensity: {
  28504. value: this.lightProbe.intensity
  28505. }
  28506. },
  28507. vertexShader: ['varying vec3 vNormal;', 'void main() {', ' vNormal = normalize( normalMatrix * normal );', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'),
  28508. 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')
  28509. });
  28510. var geometry = new SphereBufferGeometry(1, 32, 16);
  28511. Mesh.call(this, geometry, material);
  28512. this.onBeforeRender();
  28513. }
  28514. LightProbeHelper.prototype = Object.create(Mesh.prototype);
  28515. LightProbeHelper.prototype.constructor = LightProbeHelper;
  28516. LightProbeHelper.prototype.dispose = function () {
  28517. this.geometry.dispose();
  28518. this.material.dispose();
  28519. };
  28520. LightProbeHelper.prototype.onBeforeRender = function () {
  28521. this.position.copy(this.lightProbe.position);
  28522. this.scale.set(1, 1, 1).multiplyScalar(this.size);
  28523. this.material.uniforms.intensity.value = this.lightProbe.intensity;
  28524. };
  28525. /**
  28526. * @author mrdoob / http://mrdoob.com/
  28527. */
  28528. function GridHelper(size, divisions, color1, color2) {
  28529. size = size || 10;
  28530. divisions = divisions || 10;
  28531. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28532. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28533. var center = divisions / 2;
  28534. var step = size / divisions;
  28535. var halfSize = size / 2;
  28536. var vertices = [],
  28537. colors = [];
  28538. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28539. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28540. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28541. var color = i === center ? color1 : color2;
  28542. color.toArray(colors, j);
  28543. j += 3;
  28544. color.toArray(colors, j);
  28545. j += 3;
  28546. color.toArray(colors, j);
  28547. j += 3;
  28548. color.toArray(colors, j);
  28549. j += 3;
  28550. }
  28551. var geometry = new BufferGeometry();
  28552. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28553. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28554. var material = new LineBasicMaterial({
  28555. vertexColors: VertexColors
  28556. });
  28557. LineSegments.call(this, geometry, material);
  28558. }
  28559. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  28560. constructor: GridHelper,
  28561. copy: function (source) {
  28562. LineSegments.prototype.copy.call(this, source);
  28563. this.geometry.copy(source.geometry);
  28564. this.material.copy(source.material);
  28565. return this;
  28566. },
  28567. clone: function () {
  28568. return new this.constructor().copy(this);
  28569. }
  28570. });
  28571. /**
  28572. * @author mrdoob / http://mrdoob.com/
  28573. * @author Mugen87 / http://github.com/Mugen87
  28574. * @author Hectate / http://www.github.com/Hectate
  28575. */
  28576. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  28577. radius = radius || 10;
  28578. radials = radials || 16;
  28579. circles = circles || 8;
  28580. divisions = divisions || 64;
  28581. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  28582. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  28583. var vertices = [];
  28584. var colors = [];
  28585. var x, z;
  28586. var v, i, j, r, color; // create the radials
  28587. for (i = 0; i <= radials; i++) {
  28588. v = i / radials * (Math.PI * 2);
  28589. x = Math.sin(v) * radius;
  28590. z = Math.cos(v) * radius;
  28591. vertices.push(0, 0, 0);
  28592. vertices.push(x, 0, z);
  28593. color = i & 1 ? color1 : color2;
  28594. colors.push(color.r, color.g, color.b);
  28595. colors.push(color.r, color.g, color.b);
  28596. } // create the circles
  28597. for (i = 0; i <= circles; i++) {
  28598. color = i & 1 ? color1 : color2;
  28599. r = radius - radius / circles * i;
  28600. for (j = 0; j < divisions; j++) {
  28601. // first vertex
  28602. v = j / divisions * (Math.PI * 2);
  28603. x = Math.sin(v) * r;
  28604. z = Math.cos(v) * r;
  28605. vertices.push(x, 0, z);
  28606. colors.push(color.r, color.g, color.b); // second vertex
  28607. v = (j + 1) / divisions * (Math.PI * 2);
  28608. x = Math.sin(v) * r;
  28609. z = Math.cos(v) * r;
  28610. vertices.push(x, 0, z);
  28611. colors.push(color.r, color.g, color.b);
  28612. }
  28613. }
  28614. var geometry = new BufferGeometry();
  28615. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28616. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28617. var material = new LineBasicMaterial({
  28618. vertexColors: VertexColors
  28619. });
  28620. LineSegments.call(this, geometry, material);
  28621. }
  28622. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  28623. PolarGridHelper.prototype.constructor = PolarGridHelper;
  28624. /**
  28625. * @author Mugen87 / http://github.com/Mugen87
  28626. */
  28627. function PositionalAudioHelper(audio, range, divisionsInnerAngle, divisionsOuterAngle) {
  28628. this.audio = audio;
  28629. this.range = range || 1;
  28630. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  28631. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  28632. var geometry = new BufferGeometry();
  28633. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  28634. var positions = new Float32Array((divisions * 3 + 3) * 3);
  28635. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28636. var materialInnerAngle = new LineBasicMaterial({
  28637. color: 0x00ff00
  28638. });
  28639. var materialOuterAngle = new LineBasicMaterial({
  28640. color: 0xffff00
  28641. });
  28642. Line.call(this, geometry, [materialOuterAngle, materialInnerAngle]);
  28643. this.update();
  28644. }
  28645. PositionalAudioHelper.prototype = Object.create(Line.prototype);
  28646. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  28647. PositionalAudioHelper.prototype.update = function () {
  28648. var audio = this.audio;
  28649. var range = this.range;
  28650. var divisionsInnerAngle = this.divisionsInnerAngle;
  28651. var divisionsOuterAngle = this.divisionsOuterAngle;
  28652. var coneInnerAngle = _Math.degToRad(audio.panner.coneInnerAngle);
  28653. var coneOuterAngle = _Math.degToRad(audio.panner.coneOuterAngle);
  28654. var halfConeInnerAngle = coneInnerAngle / 2;
  28655. var halfConeOuterAngle = coneOuterAngle / 2;
  28656. var start = 0;
  28657. var count = 0;
  28658. var i, stride;
  28659. var geometry = this.geometry;
  28660. var positionAttribute = geometry.attributes.position;
  28661. geometry.clearGroups(); //
  28662. function generateSegment(from, to, divisions, materialIndex) {
  28663. var step = (to - from) / divisions;
  28664. positionAttribute.setXYZ(start, 0, 0, 0);
  28665. count++;
  28666. for (i = from; i < to; i += step) {
  28667. stride = start + count;
  28668. positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range);
  28669. positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range);
  28670. positionAttribute.setXYZ(stride + 2, 0, 0, 0);
  28671. count += 3;
  28672. }
  28673. geometry.addGroup(start, count, materialIndex);
  28674. start += count;
  28675. count = 0;
  28676. } //
  28677. generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0);
  28678. generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1);
  28679. generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0); //
  28680. positionAttribute.needsUpdate = true;
  28681. if (coneInnerAngle === coneOuterAngle) this.material[0].visible = false;
  28682. };
  28683. PositionalAudioHelper.prototype.dispose = function () {
  28684. this.geometry.dispose();
  28685. this.material[0].dispose();
  28686. this.material[1].dispose();
  28687. };
  28688. /**
  28689. * @author mrdoob / http://mrdoob.com/
  28690. * @author WestLangley / http://github.com/WestLangley
  28691. */
  28692. var _v1$6 = new Vector3();
  28693. var _v2$4 = new Vector3();
  28694. var _normalMatrix$2 = new Matrix3();
  28695. function FaceNormalsHelper(object, size, hex, linewidth) {
  28696. // FaceNormalsHelper only supports THREE.Geometry
  28697. this.object = object;
  28698. this.size = size !== undefined ? size : 1;
  28699. var color = hex !== undefined ? hex : 0xffff00;
  28700. var width = linewidth !== undefined ? linewidth : 1; //
  28701. var nNormals = 0;
  28702. var objGeometry = this.object.geometry;
  28703. if (objGeometry && objGeometry.isGeometry) {
  28704. nNormals = objGeometry.faces.length;
  28705. } else {
  28706. console.warn('THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.');
  28707. } //
  28708. var geometry = new BufferGeometry();
  28709. var positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
  28710. geometry.addAttribute('position', positions);
  28711. LineSegments.call(this, geometry, new LineBasicMaterial({
  28712. color: color,
  28713. linewidth: width
  28714. })); //
  28715. this.matrixAutoUpdate = false;
  28716. this.update();
  28717. }
  28718. FaceNormalsHelper.prototype = Object.create(LineSegments.prototype);
  28719. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  28720. FaceNormalsHelper.prototype.update = function () {
  28721. this.object.updateMatrixWorld(true);
  28722. _normalMatrix$2.getNormalMatrix(this.object.matrixWorld);
  28723. var matrixWorld = this.object.matrixWorld;
  28724. var position = this.geometry.attributes.position; //
  28725. var objGeometry = this.object.geometry;
  28726. var vertices = objGeometry.vertices;
  28727. var faces = objGeometry.faces;
  28728. var idx = 0;
  28729. for (var i = 0, l = faces.length; i < l; i++) {
  28730. var face = faces[i];
  28731. var normal = face.normal;
  28732. _v1$6.copy(vertices[face.a]).add(vertices[face.b]).add(vertices[face.c]).divideScalar(3).applyMatrix4(matrixWorld);
  28733. _v2$4.copy(normal).applyMatrix3(_normalMatrix$2).normalize().multiplyScalar(this.size).add(_v1$6);
  28734. position.setXYZ(idx, _v1$6.x, _v1$6.y, _v1$6.z);
  28735. idx = idx + 1;
  28736. position.setXYZ(idx, _v2$4.x, _v2$4.y, _v2$4.z);
  28737. idx = idx + 1;
  28738. }
  28739. position.needsUpdate = true;
  28740. };
  28741. /**
  28742. * @author alteredq / http://alteredqualia.com/
  28743. * @author mrdoob / http://mrdoob.com/
  28744. * @author WestLangley / http://github.com/WestLangley
  28745. */
  28746. var _v1$7 = new Vector3();
  28747. var _v2$5 = new Vector3();
  28748. var _v3$1 = new Vector3();
  28749. function DirectionalLightHelper(light, size, color) {
  28750. Object3D.call(this);
  28751. this.light = light;
  28752. this.light.updateMatrixWorld();
  28753. this.matrix = light.matrixWorld;
  28754. this.matrixAutoUpdate = false;
  28755. this.color = color;
  28756. if (size === undefined) size = 1;
  28757. var geometry = new BufferGeometry();
  28758. geometry.addAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28759. var material = new LineBasicMaterial({
  28760. fog: false
  28761. });
  28762. this.lightPlane = new Line(geometry, material);
  28763. this.add(this.lightPlane);
  28764. geometry = new BufferGeometry();
  28765. geometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28766. this.targetLine = new Line(geometry, material);
  28767. this.add(this.targetLine);
  28768. this.update();
  28769. }
  28770. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  28771. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  28772. DirectionalLightHelper.prototype.dispose = function () {
  28773. this.lightPlane.geometry.dispose();
  28774. this.lightPlane.material.dispose();
  28775. this.targetLine.geometry.dispose();
  28776. this.targetLine.material.dispose();
  28777. };
  28778. DirectionalLightHelper.prototype.update = function () {
  28779. _v1$7.setFromMatrixPosition(this.light.matrixWorld);
  28780. _v2$5.setFromMatrixPosition(this.light.target.matrixWorld);
  28781. _v3$1.subVectors(_v2$5, _v1$7);
  28782. this.lightPlane.lookAt(_v2$5);
  28783. if (this.color !== undefined) {
  28784. this.lightPlane.material.color.set(this.color);
  28785. this.targetLine.material.color.set(this.color);
  28786. } else {
  28787. this.lightPlane.material.color.copy(this.light.color);
  28788. this.targetLine.material.color.copy(this.light.color);
  28789. }
  28790. this.targetLine.lookAt(_v2$5);
  28791. this.targetLine.scale.z = _v3$1.length();
  28792. };
  28793. /**
  28794. * @author alteredq / http://alteredqualia.com/
  28795. * @author Mugen87 / https://github.com/Mugen87
  28796. *
  28797. * - shows frustum, line of sight and up of the camera
  28798. * - suitable for fast updates
  28799. * - based on frustum visualization in lightgl.js shadowmap example
  28800. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28801. */
  28802. var _vector$a = new Vector3();
  28803. var _camera = new Camera();
  28804. function CameraHelper(camera) {
  28805. var geometry = new BufferGeometry();
  28806. var material = new LineBasicMaterial({
  28807. color: 0xffffff,
  28808. vertexColors: FaceColors
  28809. });
  28810. var vertices = [];
  28811. var colors = [];
  28812. var pointMap = {}; // colors
  28813. var colorFrustum = new Color(0xffaa00);
  28814. var colorCone = new Color(0xff0000);
  28815. var colorUp = new Color(0x00aaff);
  28816. var colorTarget = new Color(0xffffff);
  28817. var colorCross = new Color(0x333333); // near
  28818. addLine('n1', 'n2', colorFrustum);
  28819. addLine('n2', 'n4', colorFrustum);
  28820. addLine('n4', 'n3', colorFrustum);
  28821. addLine('n3', 'n1', colorFrustum); // far
  28822. addLine('f1', 'f2', colorFrustum);
  28823. addLine('f2', 'f4', colorFrustum);
  28824. addLine('f4', 'f3', colorFrustum);
  28825. addLine('f3', 'f1', colorFrustum); // sides
  28826. addLine('n1', 'f1', colorFrustum);
  28827. addLine('n2', 'f2', colorFrustum);
  28828. addLine('n3', 'f3', colorFrustum);
  28829. addLine('n4', 'f4', colorFrustum); // cone
  28830. addLine('p', 'n1', colorCone);
  28831. addLine('p', 'n2', colorCone);
  28832. addLine('p', 'n3', colorCone);
  28833. addLine('p', 'n4', colorCone); // up
  28834. addLine('u1', 'u2', colorUp);
  28835. addLine('u2', 'u3', colorUp);
  28836. addLine('u3', 'u1', colorUp); // target
  28837. addLine('c', 't', colorTarget);
  28838. addLine('p', 'c', colorCross); // cross
  28839. addLine('cn1', 'cn2', colorCross);
  28840. addLine('cn3', 'cn4', colorCross);
  28841. addLine('cf1', 'cf2', colorCross);
  28842. addLine('cf3', 'cf4', colorCross);
  28843. function addLine(a, b, color) {
  28844. addPoint(a, color);
  28845. addPoint(b, color);
  28846. }
  28847. function addPoint(id, color) {
  28848. vertices.push(0, 0, 0);
  28849. colors.push(color.r, color.g, color.b);
  28850. if (pointMap[id] === undefined) {
  28851. pointMap[id] = [];
  28852. }
  28853. pointMap[id].push(vertices.length / 3 - 1);
  28854. }
  28855. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  28856. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  28857. LineSegments.call(this, geometry, material);
  28858. this.camera = camera;
  28859. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  28860. this.matrix = camera.matrixWorld;
  28861. this.matrixAutoUpdate = false;
  28862. this.pointMap = pointMap;
  28863. this.update();
  28864. }
  28865. CameraHelper.prototype = Object.create(LineSegments.prototype);
  28866. CameraHelper.prototype.constructor = CameraHelper;
  28867. CameraHelper.prototype.update = function () {
  28868. var geometry = this.geometry;
  28869. var pointMap = this.pointMap;
  28870. var w = 1,
  28871. h = 1; // we need just camera projection matrix inverse
  28872. // world matrix must be identity
  28873. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28874. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28875. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28876. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28877. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28878. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28879. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28880. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28881. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28882. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28883. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28884. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28885. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28886. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28887. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28888. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28889. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28890. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28891. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28892. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28893. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28894. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28895. geometry.getAttribute('position').needsUpdate = true;
  28896. };
  28897. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28898. _vector$a.set(x, y, z).unproject(camera);
  28899. var points = pointMap[point];
  28900. if (points !== undefined) {
  28901. var position = geometry.getAttribute('position');
  28902. for (var i = 0, l = points.length; i < l; i++) {
  28903. position.setXYZ(points[i], _vector$a.x, _vector$a.y, _vector$a.z);
  28904. }
  28905. }
  28906. }
  28907. /**
  28908. * @author mrdoob / http://mrdoob.com/
  28909. * @author Mugen87 / http://github.com/Mugen87
  28910. */
  28911. var _box$2 = new Box3();
  28912. function BoxHelper(object, color) {
  28913. this.object = object;
  28914. if (color === undefined) color = 0xffff00;
  28915. 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]);
  28916. var positions = new Float32Array(8 * 3);
  28917. var geometry = new BufferGeometry();
  28918. geometry.setIndex(new BufferAttribute(indices, 1));
  28919. geometry.addAttribute('position', new BufferAttribute(positions, 3));
  28920. LineSegments.call(this, geometry, new LineBasicMaterial({
  28921. color: color
  28922. }));
  28923. this.matrixAutoUpdate = false;
  28924. this.update();
  28925. }
  28926. BoxHelper.prototype = Object.create(LineSegments.prototype);
  28927. BoxHelper.prototype.constructor = BoxHelper;
  28928. BoxHelper.prototype.update = function (object) {
  28929. if (object !== undefined) {
  28930. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28931. }
  28932. if (this.object !== undefined) {
  28933. _box$2.setFromObject(this.object);
  28934. }
  28935. if (_box$2.isEmpty()) return;
  28936. var min = _box$2.min;
  28937. var max = _box$2.max;
  28938. /*
  28939. 5____4
  28940. 1/___0/|
  28941. | 6__|_7
  28942. 2/___3/
  28943. 0: max.x, max.y, max.z
  28944. 1: min.x, max.y, max.z
  28945. 2: min.x, min.y, max.z
  28946. 3: max.x, min.y, max.z
  28947. 4: max.x, max.y, min.z
  28948. 5: min.x, max.y, min.z
  28949. 6: min.x, min.y, min.z
  28950. 7: max.x, min.y, min.z
  28951. */
  28952. var position = this.geometry.attributes.position;
  28953. var array = position.array;
  28954. array[0] = max.x;
  28955. array[1] = max.y;
  28956. array[2] = max.z;
  28957. array[3] = min.x;
  28958. array[4] = max.y;
  28959. array[5] = max.z;
  28960. array[6] = min.x;
  28961. array[7] = min.y;
  28962. array[8] = max.z;
  28963. array[9] = max.x;
  28964. array[10] = min.y;
  28965. array[11] = max.z;
  28966. array[12] = max.x;
  28967. array[13] = max.y;
  28968. array[14] = min.z;
  28969. array[15] = min.x;
  28970. array[16] = max.y;
  28971. array[17] = min.z;
  28972. array[18] = min.x;
  28973. array[19] = min.y;
  28974. array[20] = min.z;
  28975. array[21] = max.x;
  28976. array[22] = min.y;
  28977. array[23] = min.z;
  28978. position.needsUpdate = true;
  28979. this.geometry.computeBoundingSphere();
  28980. };
  28981. BoxHelper.prototype.setFromObject = function (object) {
  28982. this.object = object;
  28983. this.update();
  28984. return this;
  28985. };
  28986. BoxHelper.prototype.copy = function (source) {
  28987. LineSegments.prototype.copy.call(this, source);
  28988. this.object = source.object;
  28989. return this;
  28990. };
  28991. BoxHelper.prototype.clone = function () {
  28992. return new this.constructor().copy(this);
  28993. };
  28994. /**
  28995. * @author WestLangley / http://github.com/WestLangley
  28996. */
  28997. function Box3Helper(box, color) {
  28998. this.type = 'Box3Helper';
  28999. this.box = box;
  29000. color = color || 0xffff00;
  29001. 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]);
  29002. 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];
  29003. var geometry = new BufferGeometry();
  29004. geometry.setIndex(new BufferAttribute(indices, 1));
  29005. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29006. LineSegments.call(this, geometry, new LineBasicMaterial({
  29007. color: color
  29008. }));
  29009. this.geometry.computeBoundingSphere();
  29010. }
  29011. Box3Helper.prototype = Object.create(LineSegments.prototype);
  29012. Box3Helper.prototype.constructor = Box3Helper;
  29013. Box3Helper.prototype.updateMatrixWorld = function (force) {
  29014. var box = this.box;
  29015. if (box.isEmpty()) return;
  29016. box.getCenter(this.position);
  29017. box.getSize(this.scale);
  29018. this.scale.multiplyScalar(0.5);
  29019. Object3D.prototype.updateMatrixWorld.call(this, force);
  29020. };
  29021. /**
  29022. * @author WestLangley / http://github.com/WestLangley
  29023. */
  29024. function PlaneHelper(plane, size, hex) {
  29025. this.type = 'PlaneHelper';
  29026. this.plane = plane;
  29027. this.size = size === undefined ? 1 : size;
  29028. var color = hex !== undefined ? hex : 0xffff00;
  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, 0, 0, 1, 0, 0, 0];
  29030. var geometry = new BufferGeometry();
  29031. geometry.addAttribute('position', new Float32BufferAttribute(positions, 3));
  29032. geometry.computeBoundingSphere();
  29033. Line.call(this, geometry, new LineBasicMaterial({
  29034. color: color
  29035. })); //
  29036. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  29037. var geometry2 = new BufferGeometry();
  29038. geometry2.addAttribute('position', new Float32BufferAttribute(positions2, 3));
  29039. geometry2.computeBoundingSphere();
  29040. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  29041. color: color,
  29042. opacity: 0.2,
  29043. transparent: true,
  29044. depthWrite: false
  29045. })));
  29046. }
  29047. PlaneHelper.prototype = Object.create(Line.prototype);
  29048. PlaneHelper.prototype.constructor = PlaneHelper;
  29049. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  29050. var scale = -this.plane.constant;
  29051. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  29052. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  29053. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29054. this.lookAt(this.plane.normal);
  29055. Object3D.prototype.updateMatrixWorld.call(this, force);
  29056. };
  29057. /**
  29058. * @author WestLangley / http://github.com/WestLangley
  29059. * @author zz85 / http://github.com/zz85
  29060. * @author bhouston / http://clara.io
  29061. *
  29062. * Creates an arrow for visualizing directions
  29063. *
  29064. * Parameters:
  29065. * dir - Vector3
  29066. * origin - Vector3
  29067. * length - Number
  29068. * color - color in hex value
  29069. * headLength - Number
  29070. * headWidth - Number
  29071. */
  29072. var _axis = new Vector3();
  29073. var _lineGeometry, _coneGeometry;
  29074. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  29075. // dir is assumed to be normalized
  29076. Object3D.call(this);
  29077. if (dir === undefined) dir = new Vector3(0, 0, 1);
  29078. if (origin === undefined) origin = new Vector3(0, 0, 0);
  29079. if (length === undefined) length = 1;
  29080. if (color === undefined) color = 0xffff00;
  29081. if (headLength === undefined) headLength = 0.2 * length;
  29082. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29083. if (_lineGeometry === undefined) {
  29084. _lineGeometry = new BufferGeometry();
  29085. _lineGeometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  29086. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  29087. _coneGeometry.translate(0, -0.5, 0);
  29088. }
  29089. this.position.copy(origin);
  29090. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  29091. color: color
  29092. }));
  29093. this.line.matrixAutoUpdate = false;
  29094. this.add(this.line);
  29095. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  29096. color: color
  29097. }));
  29098. this.cone.matrixAutoUpdate = false;
  29099. this.add(this.cone);
  29100. this.setDirection(dir);
  29101. this.setLength(length, headLength, headWidth);
  29102. }
  29103. ArrowHelper.prototype = Object.create(Object3D.prototype);
  29104. ArrowHelper.prototype.constructor = ArrowHelper;
  29105. ArrowHelper.prototype.setDirection = function (dir) {
  29106. // dir is assumed to be normalized
  29107. if (dir.y > 0.99999) {
  29108. this.quaternion.set(0, 0, 0, 1);
  29109. } else if (dir.y < -0.99999) {
  29110. this.quaternion.set(1, 0, 0, 0);
  29111. } else {
  29112. _axis.set(dir.z, 0, -dir.x).normalize();
  29113. var radians = Math.acos(dir.y);
  29114. this.quaternion.setFromAxisAngle(_axis, radians);
  29115. }
  29116. };
  29117. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  29118. if (headLength === undefined) headLength = 0.2 * length;
  29119. if (headWidth === undefined) headWidth = 0.2 * headLength;
  29120. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  29121. this.line.updateMatrix();
  29122. this.cone.scale.set(headWidth, headLength, headWidth);
  29123. this.cone.position.y = length;
  29124. this.cone.updateMatrix();
  29125. };
  29126. ArrowHelper.prototype.setColor = function (color) {
  29127. this.line.material.color.set(color);
  29128. this.cone.material.color.set(color);
  29129. };
  29130. ArrowHelper.prototype.copy = function (source) {
  29131. Object3D.prototype.copy.call(this, source, false);
  29132. this.line.copy(source.line);
  29133. this.cone.copy(source.cone);
  29134. return this;
  29135. };
  29136. ArrowHelper.prototype.clone = function () {
  29137. return new this.constructor().copy(this);
  29138. };
  29139. /**
  29140. * @author sroucheray / http://sroucheray.org/
  29141. * @author mrdoob / http://mrdoob.com/
  29142. */
  29143. function AxesHelper(size) {
  29144. size = size || 1;
  29145. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  29146. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  29147. var geometry = new BufferGeometry();
  29148. geometry.addAttribute('position', new Float32BufferAttribute(vertices, 3));
  29149. geometry.addAttribute('color', new Float32BufferAttribute(colors, 3));
  29150. var material = new LineBasicMaterial({
  29151. vertexColors: VertexColors
  29152. });
  29153. LineSegments.call(this, geometry, material);
  29154. }
  29155. AxesHelper.prototype = Object.create(LineSegments.prototype);
  29156. AxesHelper.prototype.constructor = AxesHelper;
  29157. /**
  29158. * @author mrdoob / http://mrdoob.com/
  29159. */
  29160. function Face4(a, b, c, d, normal, color, materialIndex) {
  29161. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  29162. return new Face3(a, b, c, normal, color, materialIndex);
  29163. }
  29164. var LineStrip = 0;
  29165. exports.LineStrip = LineStrip;
  29166. var LinePieces = 1;
  29167. exports.LinePieces = LinePieces;
  29168. function MeshFaceMaterial(materials) {
  29169. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  29170. return materials;
  29171. }
  29172. function MultiMaterial(materials) {
  29173. if (materials === undefined) materials = [];
  29174. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  29175. materials.isMultiMaterial = true;
  29176. materials.materials = materials;
  29177. materials.clone = function () {
  29178. return materials.slice();
  29179. };
  29180. return materials;
  29181. }
  29182. function PointCloud(geometry, material) {
  29183. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  29184. return new Points(geometry, material);
  29185. }
  29186. function Particle(material) {
  29187. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  29188. return new Sprite(material);
  29189. }
  29190. function ParticleSystem(geometry, material) {
  29191. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  29192. return new Points(geometry, material);
  29193. }
  29194. function PointCloudMaterial(parameters) {
  29195. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  29196. return new PointsMaterial(parameters);
  29197. }
  29198. function ParticleBasicMaterial(parameters) {
  29199. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  29200. return new PointsMaterial(parameters);
  29201. }
  29202. function ParticleSystemMaterial(parameters) {
  29203. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  29204. return new PointsMaterial(parameters);
  29205. }
  29206. function Vertex(x, y, z) {
  29207. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  29208. return new Vector3(x, y, z);
  29209. } //
  29210. function DynamicBufferAttribute(array, itemSize) {
  29211. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.');
  29212. return new BufferAttribute(array, itemSize).setDynamic(true);
  29213. }
  29214. function Int8Attribute(array, itemSize) {
  29215. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  29216. return new Int8BufferAttribute(array, itemSize);
  29217. }
  29218. function Uint8Attribute(array, itemSize) {
  29219. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  29220. return new Uint8BufferAttribute(array, itemSize);
  29221. }
  29222. function Uint8ClampedAttribute(array, itemSize) {
  29223. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  29224. return new Uint8ClampedBufferAttribute(array, itemSize);
  29225. }
  29226. function Int16Attribute(array, itemSize) {
  29227. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  29228. return new Int16BufferAttribute(array, itemSize);
  29229. }
  29230. function Uint16Attribute(array, itemSize) {
  29231. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  29232. return new Uint16BufferAttribute(array, itemSize);
  29233. }
  29234. function Int32Attribute(array, itemSize) {
  29235. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  29236. return new Int32BufferAttribute(array, itemSize);
  29237. }
  29238. function Uint32Attribute(array, itemSize) {
  29239. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  29240. return new Uint32BufferAttribute(array, itemSize);
  29241. }
  29242. function Float32Attribute(array, itemSize) {
  29243. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  29244. return new Float32BufferAttribute(array, itemSize);
  29245. }
  29246. function Float64Attribute(array, itemSize) {
  29247. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  29248. return new Float64BufferAttribute(array, itemSize);
  29249. } //
  29250. Curve.create = function (construct, getPoint) {
  29251. console.log('THREE.Curve.create() has been deprecated');
  29252. construct.prototype = Object.create(Curve.prototype);
  29253. construct.prototype.constructor = construct;
  29254. construct.prototype.getPoint = getPoint;
  29255. return construct;
  29256. }; //
  29257. Object.assign(CurvePath.prototype, {
  29258. createPointsGeometry: function (divisions) {
  29259. 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)
  29260. var pts = this.getPoints(divisions);
  29261. return this.createGeometry(pts);
  29262. },
  29263. createSpacedPointsGeometry: function (divisions) {
  29264. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  29265. var pts = this.getSpacedPoints(divisions);
  29266. return this.createGeometry(pts);
  29267. },
  29268. createGeometry: function (points) {
  29269. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  29270. var geometry = new Geometry();
  29271. for (var i = 0, l = points.length; i < l; i++) {
  29272. var point = points[i];
  29273. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  29274. }
  29275. return geometry;
  29276. }
  29277. }); //
  29278. Object.assign(Path.prototype, {
  29279. fromPoints: function (points) {
  29280. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  29281. this.setFromPoints(points);
  29282. }
  29283. }); //
  29284. function ClosedSplineCurve3(points) {
  29285. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29286. CatmullRomCurve3.call(this, points);
  29287. this.type = 'catmullrom';
  29288. this.closed = true;
  29289. }
  29290. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29291. function SplineCurve3(points) {
  29292. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29293. CatmullRomCurve3.call(this, points);
  29294. this.type = 'catmullrom';
  29295. }
  29296. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29297. function Spline(points) {
  29298. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  29299. CatmullRomCurve3.call(this, points);
  29300. this.type = 'catmullrom';
  29301. }
  29302. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  29303. Object.assign(Spline.prototype, {
  29304. initFromArray: function ()
  29305. /* a */
  29306. {
  29307. console.error('THREE.Spline: .initFromArray() has been removed.');
  29308. },
  29309. getControlPointsArray: function ()
  29310. /* optionalTarget */
  29311. {
  29312. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  29313. },
  29314. reparametrizeByArcLength: function ()
  29315. /* samplingCoef */
  29316. {
  29317. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  29318. }
  29319. }); //
  29320. function AxisHelper(size) {
  29321. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  29322. return new AxesHelper(size);
  29323. }
  29324. function BoundingBoxHelper(object, color) {
  29325. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  29326. return new BoxHelper(object, color);
  29327. }
  29328. function EdgesHelper(object, hex) {
  29329. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29330. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29331. color: hex !== undefined ? hex : 0xffffff
  29332. }));
  29333. }
  29334. GridHelper.prototype.setColors = function () {
  29335. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29336. };
  29337. SkeletonHelper.prototype.update = function () {
  29338. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29339. };
  29340. function WireframeHelper(object, hex) {
  29341. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29342. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29343. color: hex !== undefined ? hex : 0xffffff
  29344. }));
  29345. } //
  29346. Object.assign(Loader.prototype, {
  29347. extractUrlBase: function (url) {
  29348. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29349. return LoaderUtils.extractUrlBase(url);
  29350. }
  29351. });
  29352. Loader.Handlers = {
  29353. add: function ()
  29354. /* regex, loader */
  29355. {
  29356. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29357. },
  29358. get: function ()
  29359. /* file */
  29360. {
  29361. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29362. }
  29363. };
  29364. function XHRLoader(manager) {
  29365. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29366. return new FileLoader(manager);
  29367. }
  29368. function BinaryTextureLoader(manager) {
  29369. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29370. return new DataTextureLoader(manager);
  29371. }
  29372. Object.assign(ObjectLoader.prototype, {
  29373. setTexturePath: function (value) {
  29374. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  29375. return this.setResourcePath(value);
  29376. }
  29377. }); //
  29378. Object.assign(Box2.prototype, {
  29379. center: function (optionalTarget) {
  29380. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29381. return this.getCenter(optionalTarget);
  29382. },
  29383. empty: function () {
  29384. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29385. return this.isEmpty();
  29386. },
  29387. isIntersectionBox: function (box) {
  29388. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29389. return this.intersectsBox(box);
  29390. },
  29391. size: function (optionalTarget) {
  29392. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29393. return this.getSize(optionalTarget);
  29394. }
  29395. });
  29396. Object.assign(Box3.prototype, {
  29397. center: function (optionalTarget) {
  29398. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29399. return this.getCenter(optionalTarget);
  29400. },
  29401. empty: function () {
  29402. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29403. return this.isEmpty();
  29404. },
  29405. isIntersectionBox: function (box) {
  29406. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29407. return this.intersectsBox(box);
  29408. },
  29409. isIntersectionSphere: function (sphere) {
  29410. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29411. return this.intersectsSphere(sphere);
  29412. },
  29413. size: function (optionalTarget) {
  29414. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29415. return this.getSize(optionalTarget);
  29416. }
  29417. });
  29418. Line3.prototype.center = function (optionalTarget) {
  29419. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29420. return this.getCenter(optionalTarget);
  29421. };
  29422. Object.assign(_Math, {
  29423. random16: function () {
  29424. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29425. return Math.random();
  29426. },
  29427. nearestPowerOfTwo: function (value) {
  29428. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29429. return _Math.floorPowerOfTwo(value);
  29430. },
  29431. nextPowerOfTwo: function (value) {
  29432. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29433. return _Math.ceilPowerOfTwo(value);
  29434. }
  29435. });
  29436. Object.assign(Matrix3.prototype, {
  29437. flattenToArrayOffset: function (array, offset) {
  29438. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29439. return this.toArray(array, offset);
  29440. },
  29441. multiplyVector3: function (vector) {
  29442. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29443. return vector.applyMatrix3(this);
  29444. },
  29445. multiplyVector3Array: function ()
  29446. /* a */
  29447. {
  29448. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29449. },
  29450. applyToBuffer: function (buffer
  29451. /*, offset, length */
  29452. ) {
  29453. console.warn('THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29454. return this.applyToBufferAttribute(buffer);
  29455. },
  29456. applyToVector3Array: function ()
  29457. /* array, offset, length */
  29458. {
  29459. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29460. }
  29461. });
  29462. Object.assign(Matrix4.prototype, {
  29463. extractPosition: function (m) {
  29464. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29465. return this.copyPosition(m);
  29466. },
  29467. flattenToArrayOffset: function (array, offset) {
  29468. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29469. return this.toArray(array, offset);
  29470. },
  29471. getPosition: function () {
  29472. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29473. return new Vector3().setFromMatrixColumn(this, 3);
  29474. },
  29475. setRotationFromQuaternion: function (q) {
  29476. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29477. return this.makeRotationFromQuaternion(q);
  29478. },
  29479. multiplyToArray: function () {
  29480. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29481. },
  29482. multiplyVector3: function (vector) {
  29483. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29484. return vector.applyMatrix4(this);
  29485. },
  29486. multiplyVector4: function (vector) {
  29487. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29488. return vector.applyMatrix4(this);
  29489. },
  29490. multiplyVector3Array: function ()
  29491. /* a */
  29492. {
  29493. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29494. },
  29495. rotateAxis: function (v) {
  29496. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29497. v.transformDirection(this);
  29498. },
  29499. crossVector: function (vector) {
  29500. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29501. return vector.applyMatrix4(this);
  29502. },
  29503. translate: function () {
  29504. console.error('THREE.Matrix4: .translate() has been removed.');
  29505. },
  29506. rotateX: function () {
  29507. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29508. },
  29509. rotateY: function () {
  29510. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29511. },
  29512. rotateZ: function () {
  29513. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29514. },
  29515. rotateByAxis: function () {
  29516. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29517. },
  29518. applyToBuffer: function (buffer
  29519. /*, offset, length */
  29520. ) {
  29521. console.warn('THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.');
  29522. return this.applyToBufferAttribute(buffer);
  29523. },
  29524. applyToVector3Array: function ()
  29525. /* array, offset, length */
  29526. {
  29527. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29528. },
  29529. makeFrustum: function (left, right, bottom, top, near, far) {
  29530. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29531. return this.makePerspective(left, right, top, bottom, near, far);
  29532. }
  29533. });
  29534. Plane.prototype.isIntersectionLine = function (line) {
  29535. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29536. return this.intersectsLine(line);
  29537. };
  29538. Quaternion.prototype.multiplyVector3 = function (vector) {
  29539. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29540. return vector.applyQuaternion(this);
  29541. };
  29542. Object.assign(Ray.prototype, {
  29543. isIntersectionBox: function (box) {
  29544. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29545. return this.intersectsBox(box);
  29546. },
  29547. isIntersectionPlane: function (plane) {
  29548. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29549. return this.intersectsPlane(plane);
  29550. },
  29551. isIntersectionSphere: function (sphere) {
  29552. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29553. return this.intersectsSphere(sphere);
  29554. }
  29555. });
  29556. Object.assign(Triangle.prototype, {
  29557. area: function () {
  29558. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29559. return this.getArea();
  29560. },
  29561. barycoordFromPoint: function (point, target) {
  29562. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29563. return this.getBarycoord(point, target);
  29564. },
  29565. midpoint: function (target) {
  29566. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29567. return this.getMidpoint(target);
  29568. },
  29569. normal: function (target) {
  29570. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29571. return this.getNormal(target);
  29572. },
  29573. plane: function (target) {
  29574. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29575. return this.getPlane(target);
  29576. }
  29577. });
  29578. Object.assign(Triangle, {
  29579. barycoordFromPoint: function (point, a, b, c, target) {
  29580. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29581. return Triangle.getBarycoord(point, a, b, c, target);
  29582. },
  29583. normal: function (a, b, c, target) {
  29584. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29585. return Triangle.getNormal(a, b, c, target);
  29586. }
  29587. });
  29588. Object.assign(Shape.prototype, {
  29589. extractAllPoints: function (divisions) {
  29590. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29591. return this.extractPoints(divisions);
  29592. },
  29593. extrude: function (options) {
  29594. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29595. return new ExtrudeGeometry(this, options);
  29596. },
  29597. makeGeometry: function (options) {
  29598. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29599. return new ShapeGeometry(this, options);
  29600. }
  29601. });
  29602. Object.assign(Vector2.prototype, {
  29603. fromAttribute: function (attribute, index, offset) {
  29604. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29605. return this.fromBufferAttribute(attribute, index, offset);
  29606. },
  29607. distanceToManhattan: function (v) {
  29608. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29609. return this.manhattanDistanceTo(v);
  29610. },
  29611. lengthManhattan: function () {
  29612. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29613. return this.manhattanLength();
  29614. }
  29615. });
  29616. Object.assign(Vector3.prototype, {
  29617. setEulerFromRotationMatrix: function () {
  29618. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29619. },
  29620. setEulerFromQuaternion: function () {
  29621. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29622. },
  29623. getPositionFromMatrix: function (m) {
  29624. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29625. return this.setFromMatrixPosition(m);
  29626. },
  29627. getScaleFromMatrix: function (m) {
  29628. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29629. return this.setFromMatrixScale(m);
  29630. },
  29631. getColumnFromMatrix: function (index, matrix) {
  29632. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29633. return this.setFromMatrixColumn(matrix, index);
  29634. },
  29635. applyProjection: function (m) {
  29636. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29637. return this.applyMatrix4(m);
  29638. },
  29639. fromAttribute: function (attribute, index, offset) {
  29640. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29641. return this.fromBufferAttribute(attribute, index, offset);
  29642. },
  29643. distanceToManhattan: function (v) {
  29644. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29645. return this.manhattanDistanceTo(v);
  29646. },
  29647. lengthManhattan: function () {
  29648. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29649. return this.manhattanLength();
  29650. }
  29651. });
  29652. Object.assign(Vector4.prototype, {
  29653. fromAttribute: function (attribute, index, offset) {
  29654. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29655. return this.fromBufferAttribute(attribute, index, offset);
  29656. },
  29657. lengthManhattan: function () {
  29658. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29659. return this.manhattanLength();
  29660. }
  29661. }); //
  29662. Object.assign(Geometry.prototype, {
  29663. computeTangents: function () {
  29664. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29665. },
  29666. computeLineDistances: function () {
  29667. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29668. }
  29669. });
  29670. Object.assign(Object3D.prototype, {
  29671. getChildByName: function (name) {
  29672. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29673. return this.getObjectByName(name);
  29674. },
  29675. renderDepth: function () {
  29676. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29677. },
  29678. translate: function (distance, axis) {
  29679. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29680. return this.translateOnAxis(axis, distance);
  29681. },
  29682. getWorldRotation: function () {
  29683. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29684. }
  29685. });
  29686. Object.defineProperties(Object3D.prototype, {
  29687. eulerOrder: {
  29688. get: function () {
  29689. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29690. return this.rotation.order;
  29691. },
  29692. set: function (value) {
  29693. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29694. this.rotation.order = value;
  29695. }
  29696. },
  29697. useQuaternion: {
  29698. get: function () {
  29699. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29700. },
  29701. set: function () {
  29702. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29703. }
  29704. }
  29705. });
  29706. Object.defineProperties(LOD.prototype, {
  29707. objects: {
  29708. get: function () {
  29709. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29710. return this.levels;
  29711. }
  29712. }
  29713. });
  29714. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  29715. get: function () {
  29716. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29717. },
  29718. set: function () {
  29719. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29720. }
  29721. });
  29722. SkinnedMesh.prototype.initBones = function () {
  29723. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  29724. };
  29725. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  29726. get: function () {
  29727. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29728. return this.arcLengthDivisions;
  29729. },
  29730. set: function (value) {
  29731. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29732. this.arcLengthDivisions = value;
  29733. }
  29734. }); //
  29735. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  29736. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  29737. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  29738. this.setFocalLength(focalLength);
  29739. }; //
  29740. Object.defineProperties(Light.prototype, {
  29741. onlyShadow: {
  29742. set: function () {
  29743. console.warn('THREE.Light: .onlyShadow has been removed.');
  29744. }
  29745. },
  29746. shadowCameraFov: {
  29747. set: function (value) {
  29748. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  29749. this.shadow.camera.fov = value;
  29750. }
  29751. },
  29752. shadowCameraLeft: {
  29753. set: function (value) {
  29754. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  29755. this.shadow.camera.left = value;
  29756. }
  29757. },
  29758. shadowCameraRight: {
  29759. set: function (value) {
  29760. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  29761. this.shadow.camera.right = value;
  29762. }
  29763. },
  29764. shadowCameraTop: {
  29765. set: function (value) {
  29766. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  29767. this.shadow.camera.top = value;
  29768. }
  29769. },
  29770. shadowCameraBottom: {
  29771. set: function (value) {
  29772. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  29773. this.shadow.camera.bottom = value;
  29774. }
  29775. },
  29776. shadowCameraNear: {
  29777. set: function (value) {
  29778. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  29779. this.shadow.camera.near = value;
  29780. }
  29781. },
  29782. shadowCameraFar: {
  29783. set: function (value) {
  29784. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  29785. this.shadow.camera.far = value;
  29786. }
  29787. },
  29788. shadowCameraVisible: {
  29789. set: function () {
  29790. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  29791. }
  29792. },
  29793. shadowBias: {
  29794. set: function (value) {
  29795. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  29796. this.shadow.bias = value;
  29797. }
  29798. },
  29799. shadowDarkness: {
  29800. set: function () {
  29801. console.warn('THREE.Light: .shadowDarkness has been removed.');
  29802. }
  29803. },
  29804. shadowMapWidth: {
  29805. set: function (value) {
  29806. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  29807. this.shadow.mapSize.width = value;
  29808. }
  29809. },
  29810. shadowMapHeight: {
  29811. set: function (value) {
  29812. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  29813. this.shadow.mapSize.height = value;
  29814. }
  29815. }
  29816. }); //
  29817. Object.defineProperties(BufferAttribute.prototype, {
  29818. length: {
  29819. get: function () {
  29820. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  29821. return this.array.length;
  29822. }
  29823. }
  29824. });
  29825. Object.assign(BufferAttribute.prototype, {
  29826. copyIndicesArray: function ()
  29827. /* indices */
  29828. {
  29829. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  29830. },
  29831. setArray: function (array) {
  29832. console.warn('THREE.BufferAttribute: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29833. this.count = array !== undefined ? array.length / this.itemSize : 0;
  29834. this.array = array;
  29835. return this;
  29836. }
  29837. });
  29838. Object.assign(BufferGeometry.prototype, {
  29839. addIndex: function (index) {
  29840. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  29841. this.setIndex(index);
  29842. },
  29843. addDrawCall: function (start, count, indexOffset) {
  29844. if (indexOffset !== undefined) {
  29845. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  29846. }
  29847. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  29848. this.addGroup(start, count);
  29849. },
  29850. clearDrawCalls: function () {
  29851. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  29852. this.clearGroups();
  29853. },
  29854. computeTangents: function () {
  29855. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  29856. },
  29857. computeOffsets: function () {
  29858. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  29859. }
  29860. });
  29861. Object.defineProperties(BufferGeometry.prototype, {
  29862. drawcalls: {
  29863. get: function () {
  29864. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  29865. return this.groups;
  29866. }
  29867. },
  29868. offsets: {
  29869. get: function () {
  29870. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  29871. return this.groups;
  29872. }
  29873. }
  29874. });
  29875. Object.assign(InterleavedBuffer.prototype, {
  29876. setArray: function (array) {
  29877. console.warn('THREE.InterleavedBuffer: .setArray has been deprecated. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29878. this.count = array !== undefined ? array.length / this.stride : 0;
  29879. this.array = array;
  29880. return this;
  29881. }
  29882. }); //
  29883. Object.assign(ExtrudeBufferGeometry.prototype, {
  29884. getArrays: function () {
  29885. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  29886. },
  29887. addShapeList: function () {
  29888. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  29889. },
  29890. addShape: function () {
  29891. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  29892. }
  29893. }); //
  29894. Object.defineProperties(Uniform.prototype, {
  29895. dynamic: {
  29896. set: function () {
  29897. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  29898. }
  29899. },
  29900. onUpdate: {
  29901. value: function () {
  29902. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  29903. return this;
  29904. }
  29905. }
  29906. }); //
  29907. Object.defineProperties(Material.prototype, {
  29908. wrapAround: {
  29909. get: function () {
  29910. console.warn('THREE.Material: .wrapAround has been removed.');
  29911. },
  29912. set: function () {
  29913. console.warn('THREE.Material: .wrapAround has been removed.');
  29914. }
  29915. },
  29916. overdraw: {
  29917. get: function () {
  29918. console.warn('THREE.Material: .overdraw has been removed.');
  29919. },
  29920. set: function () {
  29921. console.warn('THREE.Material: .overdraw has been removed.');
  29922. }
  29923. },
  29924. wrapRGB: {
  29925. get: function () {
  29926. console.warn('THREE.Material: .wrapRGB has been removed.');
  29927. return new Color();
  29928. }
  29929. },
  29930. shading: {
  29931. get: function () {
  29932. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29933. },
  29934. set: function (value) {
  29935. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29936. this.flatShading = value === FlatShading;
  29937. }
  29938. },
  29939. stencilMask: {
  29940. get: function () {
  29941. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29942. return this.stencilFuncMask;
  29943. },
  29944. set: function (value) {
  29945. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29946. this.stencilFuncMask = value;
  29947. }
  29948. }
  29949. });
  29950. Object.defineProperties(MeshPhongMaterial.prototype, {
  29951. metal: {
  29952. get: function () {
  29953. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  29954. return false;
  29955. },
  29956. set: function () {
  29957. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  29958. }
  29959. }
  29960. });
  29961. Object.defineProperties(ShaderMaterial.prototype, {
  29962. derivatives: {
  29963. get: function () {
  29964. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29965. return this.extensions.derivatives;
  29966. },
  29967. set: function (value) {
  29968. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29969. this.extensions.derivatives = value;
  29970. }
  29971. }
  29972. }); //
  29973. Object.assign(WebGLRenderer.prototype, {
  29974. clearTarget: function (renderTarget, color, depth, stencil) {
  29975. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  29976. this.setRenderTarget(renderTarget);
  29977. this.clear(color, depth, stencil);
  29978. },
  29979. animate: function (callback) {
  29980. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  29981. this.setAnimationLoop(callback);
  29982. },
  29983. getCurrentRenderTarget: function () {
  29984. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  29985. return this.getRenderTarget();
  29986. },
  29987. getMaxAnisotropy: function () {
  29988. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  29989. return this.capabilities.getMaxAnisotropy();
  29990. },
  29991. getPrecision: function () {
  29992. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  29993. return this.capabilities.precision;
  29994. },
  29995. resetGLState: function () {
  29996. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  29997. return this.state.reset();
  29998. },
  29999. supportsFloatTextures: function () {
  30000. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  30001. return this.extensions.get('OES_texture_float');
  30002. },
  30003. supportsHalfFloatTextures: function () {
  30004. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  30005. return this.extensions.get('OES_texture_half_float');
  30006. },
  30007. supportsStandardDerivatives: function () {
  30008. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  30009. return this.extensions.get('OES_standard_derivatives');
  30010. },
  30011. supportsCompressedTextureS3TC: function () {
  30012. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  30013. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  30014. },
  30015. supportsCompressedTexturePVRTC: function () {
  30016. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  30017. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  30018. },
  30019. supportsBlendMinMax: function () {
  30020. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  30021. return this.extensions.get('EXT_blend_minmax');
  30022. },
  30023. supportsVertexTextures: function () {
  30024. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  30025. return this.capabilities.vertexTextures;
  30026. },
  30027. supportsInstancedArrays: function () {
  30028. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  30029. return this.extensions.get('ANGLE_instanced_arrays');
  30030. },
  30031. enableScissorTest: function (boolean) {
  30032. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  30033. this.setScissorTest(boolean);
  30034. },
  30035. initMaterial: function () {
  30036. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  30037. },
  30038. addPrePlugin: function () {
  30039. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  30040. },
  30041. addPostPlugin: function () {
  30042. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  30043. },
  30044. updateShadowMap: function () {
  30045. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  30046. },
  30047. setFaceCulling: function () {
  30048. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  30049. },
  30050. allocTextureUnit: function () {
  30051. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  30052. },
  30053. setTexture: function () {
  30054. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  30055. },
  30056. setTexture2D: function () {
  30057. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  30058. },
  30059. setTextureCube: function () {
  30060. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  30061. },
  30062. getActiveMipMapLevel: function () {
  30063. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  30064. return this.getActiveMipmapLevel();
  30065. }
  30066. });
  30067. Object.defineProperties(WebGLRenderer.prototype, {
  30068. shadowMapEnabled: {
  30069. get: function () {
  30070. return this.shadowMap.enabled;
  30071. },
  30072. set: function (value) {
  30073. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  30074. this.shadowMap.enabled = value;
  30075. }
  30076. },
  30077. shadowMapType: {
  30078. get: function () {
  30079. return this.shadowMap.type;
  30080. },
  30081. set: function (value) {
  30082. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  30083. this.shadowMap.type = value;
  30084. }
  30085. },
  30086. shadowMapCullFace: {
  30087. get: function () {
  30088. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30089. return undefined;
  30090. },
  30091. set: function ()
  30092. /* value */
  30093. {
  30094. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30095. }
  30096. },
  30097. context: {
  30098. get: function () {
  30099. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  30100. return this.getContext();
  30101. }
  30102. }
  30103. });
  30104. Object.defineProperties(WebGLShadowMap.prototype, {
  30105. cullFace: {
  30106. get: function () {
  30107. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30108. return undefined;
  30109. },
  30110. set: function ()
  30111. /* cullFace */
  30112. {
  30113. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30114. }
  30115. },
  30116. renderReverseSided: {
  30117. get: function () {
  30118. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30119. return undefined;
  30120. },
  30121. set: function () {
  30122. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30123. }
  30124. },
  30125. renderSingleSided: {
  30126. get: function () {
  30127. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30128. return undefined;
  30129. },
  30130. set: function () {
  30131. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30132. }
  30133. }
  30134. }); //
  30135. Object.defineProperties(WebGLRenderTargetCube.prototype, {
  30136. activeCubeFace: {
  30137. set: function ()
  30138. /* value */
  30139. {
  30140. console.warn('THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().');
  30141. }
  30142. },
  30143. activeMipMapLevel: {
  30144. set: function ()
  30145. /* value */
  30146. {
  30147. console.warn('THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().');
  30148. }
  30149. }
  30150. }); //
  30151. Object.defineProperties(WebGLRenderTarget.prototype, {
  30152. wrapS: {
  30153. get: function () {
  30154. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30155. return this.texture.wrapS;
  30156. },
  30157. set: function (value) {
  30158. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30159. this.texture.wrapS = value;
  30160. }
  30161. },
  30162. wrapT: {
  30163. get: function () {
  30164. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30165. return this.texture.wrapT;
  30166. },
  30167. set: function (value) {
  30168. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30169. this.texture.wrapT = value;
  30170. }
  30171. },
  30172. magFilter: {
  30173. get: function () {
  30174. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30175. return this.texture.magFilter;
  30176. },
  30177. set: function (value) {
  30178. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30179. this.texture.magFilter = value;
  30180. }
  30181. },
  30182. minFilter: {
  30183. get: function () {
  30184. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30185. return this.texture.minFilter;
  30186. },
  30187. set: function (value) {
  30188. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30189. this.texture.minFilter = value;
  30190. }
  30191. },
  30192. anisotropy: {
  30193. get: function () {
  30194. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30195. return this.texture.anisotropy;
  30196. },
  30197. set: function (value) {
  30198. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30199. this.texture.anisotropy = value;
  30200. }
  30201. },
  30202. offset: {
  30203. get: function () {
  30204. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30205. return this.texture.offset;
  30206. },
  30207. set: function (value) {
  30208. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30209. this.texture.offset = value;
  30210. }
  30211. },
  30212. repeat: {
  30213. get: function () {
  30214. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30215. return this.texture.repeat;
  30216. },
  30217. set: function (value) {
  30218. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30219. this.texture.repeat = value;
  30220. }
  30221. },
  30222. format: {
  30223. get: function () {
  30224. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30225. return this.texture.format;
  30226. },
  30227. set: function (value) {
  30228. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30229. this.texture.format = value;
  30230. }
  30231. },
  30232. type: {
  30233. get: function () {
  30234. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30235. return this.texture.type;
  30236. },
  30237. set: function (value) {
  30238. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30239. this.texture.type = value;
  30240. }
  30241. },
  30242. generateMipmaps: {
  30243. get: function () {
  30244. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30245. return this.texture.generateMipmaps;
  30246. },
  30247. set: function (value) {
  30248. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30249. this.texture.generateMipmaps = value;
  30250. }
  30251. }
  30252. }); //
  30253. Object.defineProperties(WebVRManager.prototype, {
  30254. standing: {
  30255. set: function ()
  30256. /* value */
  30257. {
  30258. console.warn('THREE.WebVRManager: .standing has been removed.');
  30259. }
  30260. },
  30261. userHeight: {
  30262. set: function ()
  30263. /* value */
  30264. {
  30265. console.warn('THREE.WebVRManager: .userHeight has been removed.');
  30266. }
  30267. }
  30268. }); //
  30269. Audio.prototype.load = function (file) {
  30270. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30271. var scope = this;
  30272. var audioLoader = new AudioLoader();
  30273. audioLoader.load(file, function (buffer) {
  30274. scope.setBuffer(buffer);
  30275. });
  30276. return this;
  30277. };
  30278. AudioAnalyser.prototype.getData = function () {
  30279. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30280. return this.getFrequencyData();
  30281. }; //
  30282. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30283. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30284. return this.update(renderer, scene);
  30285. }; //
  30286. var GeometryUtils = {
  30287. merge: function (geometry1, geometry2, materialIndexOffset) {
  30288. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30289. var matrix;
  30290. if (geometry2.isMesh) {
  30291. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30292. matrix = geometry2.matrix;
  30293. geometry2 = geometry2.geometry;
  30294. }
  30295. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30296. },
  30297. center: function (geometry) {
  30298. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30299. return geometry.center();
  30300. }
  30301. };
  30302. exports.GeometryUtils = GeometryUtils;
  30303. ImageUtils.crossOrigin = undefined;
  30304. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30305. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30306. var loader = new TextureLoader();
  30307. loader.setCrossOrigin(this.crossOrigin);
  30308. var texture = loader.load(url, onLoad, undefined, onError);
  30309. if (mapping) texture.mapping = mapping;
  30310. return texture;
  30311. };
  30312. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30313. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30314. var loader = new CubeTextureLoader();
  30315. loader.setCrossOrigin(this.crossOrigin);
  30316. var texture = loader.load(urls, onLoad, undefined, onError);
  30317. if (mapping) texture.mapping = mapping;
  30318. return texture;
  30319. };
  30320. ImageUtils.loadCompressedTexture = function () {
  30321. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30322. };
  30323. ImageUtils.loadCompressedTextureCube = function () {
  30324. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30325. }; //
  30326. function CanvasRenderer() {
  30327. console.error('THREE.CanvasRenderer has been removed');
  30328. } //
  30329. function JSONLoader() {
  30330. console.error('THREE.JSONLoader has been removed.');
  30331. } //
  30332. var SceneUtils = {
  30333. createMultiMaterialObject: function ()
  30334. /* geometry, materials */
  30335. {
  30336. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30337. },
  30338. detach: function ()
  30339. /* child, parent, scene */
  30340. {
  30341. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30342. },
  30343. attach: function ()
  30344. /* child, scene, parent */
  30345. {
  30346. console.error('THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js');
  30347. }
  30348. }; //
  30349. exports.SceneUtils = SceneUtils;
  30350. function LensFlare() {
  30351. console.error('THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js');
  30352. }
  30353. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30354. /* eslint-disable no-undef */
  30355. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30356. detail: {
  30357. revision: REVISION
  30358. }
  30359. }));
  30360. /* eslint-enable no-undef */
  30361. }
  30362. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  30363. "use strict";
  30364. Object.defineProperty(exports, "__esModule", {
  30365. value: true
  30366. });
  30367. exports.GLTFLoader = void 0;
  30368. var _threeModule = require("../../../build/three.module.js");
  30369. /**
  30370. * @author Rich Tibbett / https://github.com/richtr
  30371. * @author mrdoob / http://mrdoob.com/
  30372. * @author Tony Parisi / http://www.tonyparisi.com/
  30373. * @author Takahiro / https://github.com/takahirox
  30374. * @author Don McCurdy / https://www.donmccurdy.com
  30375. */
  30376. var GLTFLoader = function () {
  30377. function GLTFLoader(manager) {
  30378. _threeModule.Loader.call(this, manager);
  30379. this.dracoLoader = null;
  30380. this.ddsLoader = null;
  30381. }
  30382. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  30383. constructor: GLTFLoader,
  30384. load: function (url, onLoad, onProgress, onError) {
  30385. var scope = this;
  30386. var resourcePath;
  30387. if (this.resourcePath !== '') {
  30388. resourcePath = this.resourcePath;
  30389. } else if (this.path !== '') {
  30390. resourcePath = this.path;
  30391. } else {
  30392. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  30393. } // Tells the LoadingManager to track an extra item, which resolves after
  30394. // the model is fully loaded. This means the count of items loaded will
  30395. // be incorrect, but ensures manager.onLoad() does not fire early.
  30396. scope.manager.itemStart(url);
  30397. var _onError = function (e) {
  30398. if (onError) {
  30399. onError(e);
  30400. } else {
  30401. console.error(e);
  30402. }
  30403. scope.manager.itemError(url);
  30404. scope.manager.itemEnd(url);
  30405. };
  30406. var loader = new _threeModule.FileLoader(scope.manager);
  30407. loader.setPath(this.path);
  30408. loader.setResponseType('arraybuffer');
  30409. if (scope.crossOrigin === 'use-credentials') {
  30410. loader.setWithCredentials(true);
  30411. }
  30412. loader.load(url, function (data) {
  30413. try {
  30414. scope.parse(data, resourcePath, function (gltf) {
  30415. onLoad(gltf);
  30416. scope.manager.itemEnd(url);
  30417. }, _onError);
  30418. } catch (e) {
  30419. _onError(e);
  30420. }
  30421. }, onProgress, _onError);
  30422. },
  30423. setDRACOLoader: function (dracoLoader) {
  30424. this.dracoLoader = dracoLoader;
  30425. return this;
  30426. },
  30427. setDDSLoader: function (ddsLoader) {
  30428. this.ddsLoader = ddsLoader;
  30429. return this;
  30430. },
  30431. parse: function (data, path, onLoad, onError) {
  30432. var content;
  30433. var extensions = {};
  30434. if (typeof data === 'string') {
  30435. content = data;
  30436. } else {
  30437. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  30438. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  30439. try {
  30440. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  30441. } catch (error) {
  30442. if (onError) onError(error);
  30443. return;
  30444. }
  30445. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  30446. } else {
  30447. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  30448. }
  30449. }
  30450. var json = JSON.parse(content);
  30451. if (json.asset === undefined || json.asset.version[0] < 2) {
  30452. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.'));
  30453. return;
  30454. }
  30455. if (json.extensionsUsed) {
  30456. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  30457. var extensionName = json.extensionsUsed[i];
  30458. var extensionsRequired = json.extensionsRequired || [];
  30459. switch (extensionName) {
  30460. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  30461. extensions[extensionName] = new GLTFLightsExtension(json);
  30462. break;
  30463. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  30464. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  30465. break;
  30466. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  30467. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  30468. break;
  30469. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  30470. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  30471. break;
  30472. case EXTENSIONS.MSFT_TEXTURE_DDS:
  30473. extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = new GLTFTextureDDSExtension(this.ddsLoader);
  30474. break;
  30475. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  30476. extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = new GLTFTextureTransformExtension();
  30477. break;
  30478. default:
  30479. if (extensionsRequired.indexOf(extensionName) >= 0) {
  30480. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  30481. }
  30482. }
  30483. }
  30484. }
  30485. var parser = new GLTFParser(json, extensions, {
  30486. path: path || this.resourcePath || '',
  30487. crossOrigin: this.crossOrigin,
  30488. manager: this.manager
  30489. });
  30490. parser.parse(onLoad, onError);
  30491. }
  30492. });
  30493. /* GLTFREGISTRY */
  30494. function GLTFRegistry() {
  30495. var objects = {};
  30496. return {
  30497. get: function (key) {
  30498. return objects[key];
  30499. },
  30500. add: function (key, object) {
  30501. objects[key] = object;
  30502. },
  30503. remove: function (key) {
  30504. delete objects[key];
  30505. },
  30506. removeAll: function () {
  30507. objects = {};
  30508. }
  30509. };
  30510. }
  30511. /*********************************/
  30512. /********** EXTENSIONS ***********/
  30513. /*********************************/
  30514. var EXTENSIONS = {
  30515. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  30516. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  30517. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  30518. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  30519. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  30520. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  30521. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  30522. };
  30523. /**
  30524. * DDS Texture Extension
  30525. *
  30526. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  30527. *
  30528. */
  30529. function GLTFTextureDDSExtension(ddsLoader) {
  30530. if (!ddsLoader) {
  30531. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  30532. }
  30533. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  30534. this.ddsLoader = ddsLoader;
  30535. }
  30536. /**
  30537. * Punctual Lights Extension
  30538. *
  30539. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  30540. */
  30541. function GLTFLightsExtension(json) {
  30542. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  30543. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  30544. this.lightDefs = extension.lights || [];
  30545. }
  30546. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  30547. var lightDef = this.lightDefs[lightIndex];
  30548. var lightNode;
  30549. var color = new _threeModule.Color(0xffffff);
  30550. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  30551. var range = lightDef.range !== undefined ? lightDef.range : 0;
  30552. switch (lightDef.type) {
  30553. case 'directional':
  30554. lightNode = new _threeModule.DirectionalLight(color);
  30555. lightNode.target.position.set(0, 0, -1);
  30556. lightNode.add(lightNode.target);
  30557. break;
  30558. case 'point':
  30559. lightNode = new _threeModule.PointLight(color);
  30560. lightNode.distance = range;
  30561. break;
  30562. case 'spot':
  30563. lightNode = new _threeModule.SpotLight(color);
  30564. lightNode.distance = range; // Handle spotlight properties.
  30565. lightDef.spot = lightDef.spot || {};
  30566. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  30567. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  30568. lightNode.angle = lightDef.spot.outerConeAngle;
  30569. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  30570. lightNode.target.position.set(0, 0, -1);
  30571. lightNode.add(lightNode.target);
  30572. break;
  30573. default:
  30574. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  30575. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  30576. // here, because node-level parsing will only override position if explicitly specified.
  30577. lightNode.position.set(0, 0, 0);
  30578. lightNode.decay = 2;
  30579. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  30580. lightNode.name = lightDef.name || 'light_' + lightIndex;
  30581. return Promise.resolve(lightNode);
  30582. };
  30583. /**
  30584. * Unlit Materials Extension
  30585. *
  30586. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  30587. */
  30588. function GLTFMaterialsUnlitExtension() {
  30589. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  30590. }
  30591. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  30592. return _threeModule.MeshBasicMaterial;
  30593. };
  30594. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  30595. var pending = [];
  30596. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30597. materialParams.opacity = 1.0;
  30598. var metallicRoughness = materialDef.pbrMetallicRoughness;
  30599. if (metallicRoughness) {
  30600. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  30601. var array = metallicRoughness.baseColorFactor;
  30602. materialParams.color.fromArray(array);
  30603. materialParams.opacity = array[3];
  30604. }
  30605. if (metallicRoughness.baseColorTexture !== undefined) {
  30606. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  30607. }
  30608. }
  30609. return Promise.all(pending);
  30610. };
  30611. /* BINARY EXTENSION */
  30612. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  30613. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  30614. var BINARY_EXTENSION_CHUNK_TYPES = {
  30615. JSON: 0x4E4F534A,
  30616. BIN: 0x004E4942
  30617. };
  30618. function GLTFBinaryExtension(data) {
  30619. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  30620. this.content = null;
  30621. this.body = null;
  30622. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  30623. this.header = {
  30624. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  30625. version: headerView.getUint32(4, true),
  30626. length: headerView.getUint32(8, true)
  30627. };
  30628. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  30629. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  30630. } else if (this.header.version < 2.0) {
  30631. throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.');
  30632. }
  30633. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  30634. var chunkIndex = 0;
  30635. while (chunkIndex < chunkView.byteLength) {
  30636. var chunkLength = chunkView.getUint32(chunkIndex, true);
  30637. chunkIndex += 4;
  30638. var chunkType = chunkView.getUint32(chunkIndex, true);
  30639. chunkIndex += 4;
  30640. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  30641. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  30642. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  30643. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  30644. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  30645. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  30646. } // Clients must ignore chunks with unknown types.
  30647. chunkIndex += chunkLength;
  30648. }
  30649. if (this.content === null) {
  30650. throw new Error('THREE.GLTFLoader: JSON content not found.');
  30651. }
  30652. }
  30653. /**
  30654. * DRACO Mesh Compression Extension
  30655. *
  30656. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  30657. */
  30658. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  30659. if (!dracoLoader) {
  30660. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  30661. }
  30662. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  30663. this.json = json;
  30664. this.dracoLoader = dracoLoader;
  30665. }
  30666. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  30667. var json = this.json;
  30668. var dracoLoader = this.dracoLoader;
  30669. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  30670. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  30671. var threeAttributeMap = {};
  30672. var attributeNormalizedMap = {};
  30673. var attributeTypeMap = {};
  30674. for (var attributeName in gltfAttributeMap) {
  30675. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30676. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  30677. }
  30678. for (attributeName in primitive.attributes) {
  30679. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  30680. if (gltfAttributeMap[attributeName] !== undefined) {
  30681. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  30682. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  30683. attributeTypeMap[threeAttributeName] = componentType;
  30684. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  30685. }
  30686. }
  30687. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  30688. return new Promise(function (resolve) {
  30689. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  30690. for (var attributeName in geometry.attributes) {
  30691. var attribute = geometry.attributes[attributeName];
  30692. var normalized = attributeNormalizedMap[attributeName];
  30693. if (normalized !== undefined) attribute.normalized = normalized;
  30694. }
  30695. resolve(geometry);
  30696. }, threeAttributeMap, attributeTypeMap);
  30697. });
  30698. });
  30699. };
  30700. /**
  30701. * Texture Transform Extension
  30702. *
  30703. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  30704. */
  30705. function GLTFTextureTransformExtension() {
  30706. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  30707. }
  30708. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  30709. texture = texture.clone();
  30710. if (transform.offset !== undefined) {
  30711. texture.offset.fromArray(transform.offset);
  30712. }
  30713. if (transform.rotation !== undefined) {
  30714. texture.rotation = transform.rotation;
  30715. }
  30716. if (transform.scale !== undefined) {
  30717. texture.repeat.fromArray(transform.scale);
  30718. }
  30719. if (transform.texCoord !== undefined) {
  30720. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  30721. }
  30722. texture.needsUpdate = true;
  30723. return texture;
  30724. };
  30725. /**
  30726. * Specular-Glossiness Extension
  30727. *
  30728. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  30729. */
  30730. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  30731. return {
  30732. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  30733. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  30734. getMaterialType: function () {
  30735. return _threeModule.ShaderMaterial;
  30736. },
  30737. extendParams: function (materialParams, materialDef, parser) {
  30738. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  30739. var shader = _threeModule.ShaderLib['standard'];
  30740. var uniforms = _threeModule.UniformsUtils.clone(shader.uniforms);
  30741. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  30742. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  30743. 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');
  30744. 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');
  30745. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n');
  30746. 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);
  30747. delete uniforms.roughness;
  30748. delete uniforms.metalness;
  30749. delete uniforms.roughnessMap;
  30750. delete uniforms.metalnessMap;
  30751. uniforms.specular = {
  30752. value: new _threeModule.Color().setHex(0x111111)
  30753. };
  30754. uniforms.glossiness = {
  30755. value: 0.5
  30756. };
  30757. uniforms.specularMap = {
  30758. value: null
  30759. };
  30760. uniforms.glossinessMap = {
  30761. value: null
  30762. };
  30763. materialParams.vertexShader = shader.vertexShader;
  30764. materialParams.fragmentShader = fragmentShader;
  30765. materialParams.uniforms = uniforms;
  30766. materialParams.defines = {
  30767. 'STANDARD': ''
  30768. };
  30769. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  30770. materialParams.opacity = 1.0;
  30771. var pending = [];
  30772. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  30773. var array = pbrSpecularGlossiness.diffuseFactor;
  30774. materialParams.color.fromArray(array);
  30775. materialParams.opacity = array[3];
  30776. }
  30777. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  30778. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  30779. }
  30780. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  30781. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  30782. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  30783. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  30784. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  30785. }
  30786. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  30787. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  30788. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  30789. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  30790. }
  30791. return Promise.all(pending);
  30792. },
  30793. createMaterial: function (params) {
  30794. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  30795. var material = new _threeModule.ShaderMaterial({
  30796. defines: params.defines,
  30797. vertexShader: params.vertexShader,
  30798. fragmentShader: params.fragmentShader,
  30799. uniforms: params.uniforms,
  30800. fog: true,
  30801. lights: true,
  30802. opacity: params.opacity,
  30803. transparent: params.transparent
  30804. });
  30805. material.isGLTFSpecularGlossinessMaterial = true;
  30806. material.color = params.color;
  30807. material.map = params.map === undefined ? null : params.map;
  30808. material.lightMap = null;
  30809. material.lightMapIntensity = 1.0;
  30810. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  30811. material.aoMapIntensity = 1.0;
  30812. material.emissive = params.emissive;
  30813. material.emissiveIntensity = 1.0;
  30814. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  30815. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  30816. material.bumpScale = 1;
  30817. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  30818. if (params.normalScale) material.normalScale = params.normalScale;
  30819. material.displacementMap = null;
  30820. material.displacementScale = 1;
  30821. material.displacementBias = 0;
  30822. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  30823. material.specular = params.specular;
  30824. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  30825. material.glossiness = params.glossiness;
  30826. material.alphaMap = null;
  30827. material.envMap = params.envMap === undefined ? null : params.envMap;
  30828. material.envMapIntensity = 1.0;
  30829. material.refractionRatio = 0.98;
  30830. material.extensions.derivatives = true;
  30831. return material;
  30832. },
  30833. /**
  30834. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  30835. * copy only properties it knows about or inherits, and misses many properties that would
  30836. * normally be defined by MeshStandardMaterial.
  30837. *
  30838. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  30839. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  30840. * AND also updating `.onBeforeRender` on the parent mesh.
  30841. *
  30842. * @param {ShaderMaterial} source
  30843. * @return {ShaderMaterial}
  30844. */
  30845. cloneMaterial: function (source) {
  30846. var target = source.clone();
  30847. target.isGLTFSpecularGlossinessMaterial = true;
  30848. var params = this.specularGlossinessParams;
  30849. for (var i = 0, il = params.length; i < il; i++) {
  30850. var value = source[params[i]];
  30851. target[params[i]] = value && value.isColor ? value.clone() : value;
  30852. }
  30853. return target;
  30854. },
  30855. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  30856. refreshUniforms: function (renderer, scene, camera, geometry, material) {
  30857. if (material.isGLTFSpecularGlossinessMaterial !== true) {
  30858. return;
  30859. }
  30860. var uniforms = material.uniforms;
  30861. var defines = material.defines;
  30862. uniforms.opacity.value = material.opacity;
  30863. uniforms.diffuse.value.copy(material.color);
  30864. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  30865. uniforms.map.value = material.map;
  30866. uniforms.specularMap.value = material.specularMap;
  30867. uniforms.alphaMap.value = material.alphaMap;
  30868. uniforms.lightMap.value = material.lightMap;
  30869. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  30870. uniforms.aoMap.value = material.aoMap;
  30871. uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities
  30872. // 1. color map
  30873. // 2. specular map
  30874. // 3. normal map
  30875. // 4. bump map
  30876. // 5. alpha map
  30877. // 6. emissive map
  30878. var uvScaleMap;
  30879. if (material.map) {
  30880. uvScaleMap = material.map;
  30881. } else if (material.specularMap) {
  30882. uvScaleMap = material.specularMap;
  30883. } else if (material.displacementMap) {
  30884. uvScaleMap = material.displacementMap;
  30885. } else if (material.normalMap) {
  30886. uvScaleMap = material.normalMap;
  30887. } else if (material.bumpMap) {
  30888. uvScaleMap = material.bumpMap;
  30889. } else if (material.glossinessMap) {
  30890. uvScaleMap = material.glossinessMap;
  30891. } else if (material.alphaMap) {
  30892. uvScaleMap = material.alphaMap;
  30893. } else if (material.emissiveMap) {
  30894. uvScaleMap = material.emissiveMap;
  30895. }
  30896. if (uvScaleMap !== undefined) {
  30897. // backwards compatibility
  30898. if (uvScaleMap.isWebGLRenderTarget) {
  30899. uvScaleMap = uvScaleMap.texture;
  30900. }
  30901. if (uvScaleMap.matrixAutoUpdate === true) {
  30902. uvScaleMap.updateMatrix();
  30903. }
  30904. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  30905. }
  30906. if (material.envMap) {
  30907. uniforms.envMap.value = material.envMap;
  30908. uniforms.envMapIntensity.value = material.envMapIntensity; // don't flip CubeTexture envMaps, flip everything else:
  30909. // WebGLRenderTargetCube will be flipped for backwards compatibility
  30910. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  30911. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  30912. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
  30913. uniforms.reflectivity.value = material.reflectivity;
  30914. uniforms.refractionRatio.value = material.refractionRatio;
  30915. uniforms.maxMipLevel.value = renderer.properties.get(material.envMap).__maxMipLevel;
  30916. }
  30917. uniforms.specular.value.copy(material.specular);
  30918. uniforms.glossiness.value = material.glossiness;
  30919. uniforms.glossinessMap.value = material.glossinessMap;
  30920. uniforms.emissiveMap.value = material.emissiveMap;
  30921. uniforms.bumpMap.value = material.bumpMap;
  30922. uniforms.normalMap.value = material.normalMap;
  30923. uniforms.displacementMap.value = material.displacementMap;
  30924. uniforms.displacementScale.value = material.displacementScale;
  30925. uniforms.displacementBias.value = material.displacementBias;
  30926. if (uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined) {
  30927. defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  30928. defines.USE_ROUGHNESSMAP = '';
  30929. }
  30930. if (uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined) {
  30931. delete defines.USE_GLOSSINESSMAP;
  30932. delete defines.USE_ROUGHNESSMAP;
  30933. }
  30934. }
  30935. };
  30936. }
  30937. /*********************************/
  30938. /********** INTERPOLATION ********/
  30939. /*********************************/
  30940. // Spline Interpolation
  30941. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  30942. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  30943. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  30944. }
  30945. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  30946. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  30947. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  30948. // Copies a sample value to the result buffer. See description of glTF
  30949. // CUBICSPLINE values layout in interpolate_() function below.
  30950. var result = this.resultBuffer,
  30951. values = this.sampleValues,
  30952. valueSize = this.valueSize,
  30953. offset = index * valueSize * 3 + valueSize;
  30954. for (var i = 0; i !== valueSize; i++) {
  30955. result[i] = values[offset + i];
  30956. }
  30957. return result;
  30958. };
  30959. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30960. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  30961. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  30962. var result = this.resultBuffer;
  30963. var values = this.sampleValues;
  30964. var stride = this.valueSize;
  30965. var stride2 = stride * 2;
  30966. var stride3 = stride * 3;
  30967. var td = t1 - t0;
  30968. var p = (t - t0) / td;
  30969. var pp = p * p;
  30970. var ppp = pp * p;
  30971. var offset1 = i1 * stride3;
  30972. var offset0 = offset1 - stride3;
  30973. var s2 = -2 * ppp + 3 * pp;
  30974. var s3 = ppp - pp;
  30975. var s0 = 1 - s2;
  30976. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  30977. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  30978. for (var i = 0; i !== stride; i++) {
  30979. var p0 = values[offset0 + i + stride]; // splineVertex_k
  30980. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  30981. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  30982. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  30983. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  30984. }
  30985. return result;
  30986. };
  30987. /*********************************/
  30988. /********** INTERNALS ************/
  30989. /*********************************/
  30990. /* CONSTANTS */
  30991. var WEBGL_CONSTANTS = {
  30992. FLOAT: 5126,
  30993. //FLOAT_MAT2: 35674,
  30994. FLOAT_MAT3: 35675,
  30995. FLOAT_MAT4: 35676,
  30996. FLOAT_VEC2: 35664,
  30997. FLOAT_VEC3: 35665,
  30998. FLOAT_VEC4: 35666,
  30999. LINEAR: 9729,
  31000. REPEAT: 10497,
  31001. SAMPLER_2D: 35678,
  31002. POINTS: 0,
  31003. LINES: 1,
  31004. LINE_LOOP: 2,
  31005. LINE_STRIP: 3,
  31006. TRIANGLES: 4,
  31007. TRIANGLE_STRIP: 5,
  31008. TRIANGLE_FAN: 6,
  31009. UNSIGNED_BYTE: 5121,
  31010. UNSIGNED_SHORT: 5123
  31011. };
  31012. var WEBGL_COMPONENT_TYPES = {
  31013. 5120: Int8Array,
  31014. 5121: Uint8Array,
  31015. 5122: Int16Array,
  31016. 5123: Uint16Array,
  31017. 5125: Uint32Array,
  31018. 5126: Float32Array
  31019. };
  31020. var WEBGL_FILTERS = {
  31021. 9728: _threeModule.NearestFilter,
  31022. 9729: _threeModule.LinearFilter,
  31023. 9984: _threeModule.NearestMipmapNearestFilter,
  31024. 9985: _threeModule.LinearMipmapNearestFilter,
  31025. 9986: _threeModule.NearestMipmapLinearFilter,
  31026. 9987: _threeModule.LinearMipmapLinearFilter
  31027. };
  31028. var WEBGL_WRAPPINGS = {
  31029. 33071: _threeModule.ClampToEdgeWrapping,
  31030. 33648: _threeModule.MirroredRepeatWrapping,
  31031. 10497: _threeModule.RepeatWrapping
  31032. };
  31033. var WEBGL_TYPE_SIZES = {
  31034. 'SCALAR': 1,
  31035. 'VEC2': 2,
  31036. 'VEC3': 3,
  31037. 'VEC4': 4,
  31038. 'MAT2': 4,
  31039. 'MAT3': 9,
  31040. 'MAT4': 16
  31041. };
  31042. var ATTRIBUTES = {
  31043. POSITION: 'position',
  31044. NORMAL: 'normal',
  31045. TANGENT: 'tangent',
  31046. TEXCOORD_0: 'uv',
  31047. TEXCOORD_1: 'uv2',
  31048. COLOR_0: 'color',
  31049. WEIGHTS_0: 'skinWeight',
  31050. JOINTS_0: 'skinIndex'
  31051. };
  31052. var PATH_PROPERTIES = {
  31053. scale: 'scale',
  31054. translation: 'position',
  31055. rotation: 'quaternion',
  31056. weights: 'morphTargetInfluences'
  31057. };
  31058. var INTERPOLATION = {
  31059. CUBICSPLINE: undefined,
  31060. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  31061. // keyframe track will be initialized with a default interpolation type, then modified.
  31062. LINEAR: _threeModule.InterpolateLinear,
  31063. STEP: _threeModule.InterpolateDiscrete
  31064. };
  31065. var ALPHA_MODES = {
  31066. OPAQUE: 'OPAQUE',
  31067. MASK: 'MASK',
  31068. BLEND: 'BLEND'
  31069. };
  31070. var MIME_TYPE_FORMATS = {
  31071. 'image/png': _threeModule.RGBAFormat,
  31072. 'image/jpeg': _threeModule.RGBFormat
  31073. };
  31074. /* UTILITY FUNCTIONS */
  31075. function resolveURL(url, path) {
  31076. // Invalid URL
  31077. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  31078. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  31079. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  31080. } // Absolute URL http://,https://,//
  31081. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  31082. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  31083. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  31084. return path + url;
  31085. }
  31086. var defaultMaterial;
  31087. /**
  31088. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  31089. */
  31090. function createDefaultMaterial() {
  31091. defaultMaterial = defaultMaterial || new _threeModule.MeshStandardMaterial({
  31092. color: 0xFFFFFF,
  31093. emissive: 0x000000,
  31094. metalness: 1,
  31095. roughness: 1,
  31096. transparent: false,
  31097. depthTest: true,
  31098. side: _threeModule.FrontSide
  31099. });
  31100. return defaultMaterial;
  31101. }
  31102. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  31103. // Add unknown glTF extensions to an object's userData.
  31104. for (var name in objectDef.extensions) {
  31105. if (knownExtensions[name] === undefined) {
  31106. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  31107. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  31108. }
  31109. }
  31110. }
  31111. /**
  31112. * @param {Object3D|Material|BufferGeometry} object
  31113. * @param {GLTF.definition} gltfDef
  31114. */
  31115. function assignExtrasToUserData(object, gltfDef) {
  31116. if (gltfDef.extras !== undefined) {
  31117. if (typeof gltfDef.extras === 'object') {
  31118. Object.assign(object.userData, gltfDef.extras);
  31119. } else {
  31120. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  31121. }
  31122. }
  31123. }
  31124. /**
  31125. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  31126. *
  31127. * @param {BufferGeometry} geometry
  31128. * @param {Array<GLTF.Target>} targets
  31129. * @param {GLTFParser} parser
  31130. * @return {Promise<BufferGeometry>}
  31131. */
  31132. function addMorphTargets(geometry, targets, parser) {
  31133. var hasMorphPosition = false;
  31134. var hasMorphNormal = false;
  31135. for (var i = 0, il = targets.length; i < il; i++) {
  31136. var target = targets[i];
  31137. if (target.POSITION !== undefined) hasMorphPosition = true;
  31138. if (target.NORMAL !== undefined) hasMorphNormal = true;
  31139. if (hasMorphPosition && hasMorphNormal) break;
  31140. }
  31141. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  31142. var pendingPositionAccessors = [];
  31143. var pendingNormalAccessors = [];
  31144. for (var i = 0, il = targets.length; i < il; i++) {
  31145. var target = targets[i];
  31146. if (hasMorphPosition) {
  31147. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  31148. pendingPositionAccessors.push(pendingAccessor);
  31149. }
  31150. if (hasMorphNormal) {
  31151. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  31152. pendingNormalAccessors.push(pendingAccessor);
  31153. }
  31154. }
  31155. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  31156. var morphPositions = accessors[0];
  31157. var morphNormals = accessors[1]; // Clone morph target accessors before modifying them.
  31158. for (var i = 0, il = morphPositions.length; i < il; i++) {
  31159. if (geometry.attributes.position === morphPositions[i]) continue;
  31160. morphPositions[i] = cloneBufferAttribute(morphPositions[i]);
  31161. }
  31162. for (var i = 0, il = morphNormals.length; i < il; i++) {
  31163. if (geometry.attributes.normal === morphNormals[i]) continue;
  31164. morphNormals[i] = cloneBufferAttribute(morphNormals[i]);
  31165. }
  31166. for (var i = 0, il = targets.length; i < il; i++) {
  31167. var target = targets[i];
  31168. var attributeName = 'morphTarget' + i;
  31169. if (hasMorphPosition) {
  31170. // Three.js morph position is absolute value. The formula is
  31171. // basePosition
  31172. // + weight0 * ( morphPosition0 - basePosition )
  31173. // + weight1 * ( morphPosition1 - basePosition )
  31174. // ...
  31175. // while the glTF one is relative
  31176. // basePosition
  31177. // + weight0 * glTFmorphPosition0
  31178. // + weight1 * glTFmorphPosition1
  31179. // ...
  31180. // then we need to convert from relative to absolute here.
  31181. if (target.POSITION !== undefined) {
  31182. var positionAttribute = morphPositions[i];
  31183. positionAttribute.name = attributeName;
  31184. var position = geometry.attributes.position;
  31185. for (var j = 0, jl = positionAttribute.count; j < jl; j++) {
  31186. positionAttribute.setXYZ(j, positionAttribute.getX(j) + position.getX(j), positionAttribute.getY(j) + position.getY(j), positionAttribute.getZ(j) + position.getZ(j));
  31187. }
  31188. }
  31189. }
  31190. if (hasMorphNormal) {
  31191. // see target.POSITION's comment
  31192. if (target.NORMAL !== undefined) {
  31193. var normalAttribute = morphNormals[i];
  31194. normalAttribute.name = attributeName;
  31195. var normal = geometry.attributes.normal;
  31196. for (var j = 0, jl = normalAttribute.count; j < jl; j++) {
  31197. normalAttribute.setXYZ(j, normalAttribute.getX(j) + normal.getX(j), normalAttribute.getY(j) + normal.getY(j), normalAttribute.getZ(j) + normal.getZ(j));
  31198. }
  31199. }
  31200. }
  31201. }
  31202. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  31203. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  31204. return geometry;
  31205. });
  31206. }
  31207. /**
  31208. * @param {Mesh} mesh
  31209. * @param {GLTF.Mesh} meshDef
  31210. */
  31211. function updateMorphTargets(mesh, meshDef) {
  31212. mesh.updateMorphTargets();
  31213. if (meshDef.weights !== undefined) {
  31214. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  31215. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  31216. }
  31217. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  31218. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  31219. var targetNames = meshDef.extras.targetNames;
  31220. if (mesh.morphTargetInfluences.length === targetNames.length) {
  31221. mesh.morphTargetDictionary = {};
  31222. for (var i = 0, il = targetNames.length; i < il; i++) {
  31223. mesh.morphTargetDictionary[targetNames[i]] = i;
  31224. }
  31225. } else {
  31226. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  31227. }
  31228. }
  31229. }
  31230. function createPrimitiveKey(primitiveDef) {
  31231. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  31232. var geometryKey;
  31233. if (dracoExtension) {
  31234. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  31235. } else {
  31236. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  31237. }
  31238. return geometryKey;
  31239. }
  31240. function createAttributesKey(attributes) {
  31241. var attributesKey = '';
  31242. var keys = Object.keys(attributes).sort();
  31243. for (var i = 0, il = keys.length; i < il; i++) {
  31244. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  31245. }
  31246. return attributesKey;
  31247. }
  31248. function cloneBufferAttribute(attribute) {
  31249. if (attribute.isInterleavedBufferAttribute) {
  31250. var count = attribute.count;
  31251. var itemSize = attribute.itemSize;
  31252. var array = attribute.array.slice(0, count * itemSize);
  31253. for (var i = 0, j = 0; i < count; ++i) {
  31254. array[j++] = attribute.getX(i);
  31255. if (itemSize >= 2) array[j++] = attribute.getY(i);
  31256. if (itemSize >= 3) array[j++] = attribute.getZ(i);
  31257. if (itemSize >= 4) array[j++] = attribute.getW(i);
  31258. }
  31259. return new _threeModule.BufferAttribute(array, itemSize, attribute.normalized);
  31260. }
  31261. return attribute.clone();
  31262. }
  31263. /* GLTF PARSER */
  31264. function GLTFParser(json, extensions, options) {
  31265. this.json = json || {};
  31266. this.extensions = extensions || {};
  31267. this.options = options || {}; // loader object cache
  31268. this.cache = new GLTFRegistry(); // BufferGeometry caching
  31269. this.primitiveCache = {};
  31270. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  31271. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  31272. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  31273. this.fileLoader.setResponseType('arraybuffer');
  31274. if (this.options.crossOrigin === 'use-credentials') {
  31275. this.fileLoader.setWithCredentials(true);
  31276. }
  31277. }
  31278. GLTFParser.prototype.parse = function (onLoad, onError) {
  31279. var parser = this;
  31280. var json = this.json;
  31281. var extensions = this.extensions; // Clear the loader cache
  31282. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  31283. this.markDefs();
  31284. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  31285. var result = {
  31286. scene: dependencies[0][json.scene || 0],
  31287. scenes: dependencies[0],
  31288. animations: dependencies[1],
  31289. cameras: dependencies[2],
  31290. asset: json.asset,
  31291. parser: parser,
  31292. userData: {}
  31293. };
  31294. addUnknownExtensionsToUserData(extensions, result, json);
  31295. assignExtrasToUserData(result, json);
  31296. onLoad(result);
  31297. }).catch(onError);
  31298. };
  31299. /**
  31300. * Marks the special nodes/meshes in json for efficient parse.
  31301. */
  31302. GLTFParser.prototype.markDefs = function () {
  31303. var nodeDefs = this.json.nodes || [];
  31304. var skinDefs = this.json.skins || [];
  31305. var meshDefs = this.json.meshes || [];
  31306. var meshReferences = {};
  31307. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  31308. // Object3D. Use the skins' joint references to mark bones.
  31309. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  31310. var joints = skinDefs[skinIndex].joints;
  31311. for (var i = 0, il = joints.length; i < il; i++) {
  31312. nodeDefs[joints[i]].isBone = true;
  31313. }
  31314. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  31315. // avoid having more than one Mesh with the same name, count
  31316. // references and rename instances below.
  31317. //
  31318. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  31319. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  31320. var nodeDef = nodeDefs[nodeIndex];
  31321. if (nodeDef.mesh !== undefined) {
  31322. if (meshReferences[nodeDef.mesh] === undefined) {
  31323. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  31324. }
  31325. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  31326. // a SkinnedMesh or Mesh. Use the node's mesh reference
  31327. // to mark SkinnedMesh if node has skin.
  31328. if (nodeDef.skin !== undefined) {
  31329. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  31330. }
  31331. }
  31332. }
  31333. this.json.meshReferences = meshReferences;
  31334. this.json.meshUses = meshUses;
  31335. };
  31336. /**
  31337. * Requests the specified dependency asynchronously, with caching.
  31338. * @param {string} type
  31339. * @param {number} index
  31340. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  31341. */
  31342. GLTFParser.prototype.getDependency = function (type, index) {
  31343. var cacheKey = type + ':' + index;
  31344. var dependency = this.cache.get(cacheKey);
  31345. if (!dependency) {
  31346. switch (type) {
  31347. case 'scene':
  31348. dependency = this.loadScene(index);
  31349. break;
  31350. case 'node':
  31351. dependency = this.loadNode(index);
  31352. break;
  31353. case 'mesh':
  31354. dependency = this.loadMesh(index);
  31355. break;
  31356. case 'accessor':
  31357. dependency = this.loadAccessor(index);
  31358. break;
  31359. case 'bufferView':
  31360. dependency = this.loadBufferView(index);
  31361. break;
  31362. case 'buffer':
  31363. dependency = this.loadBuffer(index);
  31364. break;
  31365. case 'material':
  31366. dependency = this.loadMaterial(index);
  31367. break;
  31368. case 'texture':
  31369. dependency = this.loadTexture(index);
  31370. break;
  31371. case 'skin':
  31372. dependency = this.loadSkin(index);
  31373. break;
  31374. case 'animation':
  31375. dependency = this.loadAnimation(index);
  31376. break;
  31377. case 'camera':
  31378. dependency = this.loadCamera(index);
  31379. break;
  31380. case 'light':
  31381. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  31382. break;
  31383. default:
  31384. throw new Error('Unknown type: ' + type);
  31385. }
  31386. this.cache.add(cacheKey, dependency);
  31387. }
  31388. return dependency;
  31389. };
  31390. /**
  31391. * Requests all dependencies of the specified type asynchronously, with caching.
  31392. * @param {string} type
  31393. * @return {Promise<Array<Object>>}
  31394. */
  31395. GLTFParser.prototype.getDependencies = function (type) {
  31396. var dependencies = this.cache.get(type);
  31397. if (!dependencies) {
  31398. var parser = this;
  31399. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  31400. dependencies = Promise.all(defs.map(function (def, index) {
  31401. return parser.getDependency(type, index);
  31402. }));
  31403. this.cache.add(type, dependencies);
  31404. }
  31405. return dependencies;
  31406. };
  31407. /**
  31408. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31409. * @param {number} bufferIndex
  31410. * @return {Promise<ArrayBuffer>}
  31411. */
  31412. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  31413. var bufferDef = this.json.buffers[bufferIndex];
  31414. var loader = this.fileLoader;
  31415. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  31416. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  31417. } // If present, GLB container is required to be the first buffer.
  31418. if (bufferDef.uri === undefined && bufferIndex === 0) {
  31419. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  31420. }
  31421. var options = this.options;
  31422. return new Promise(function (resolve, reject) {
  31423. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  31424. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  31425. });
  31426. });
  31427. };
  31428. /**
  31429. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  31430. * @param {number} bufferViewIndex
  31431. * @return {Promise<ArrayBuffer>}
  31432. */
  31433. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  31434. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  31435. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  31436. var byteLength = bufferViewDef.byteLength || 0;
  31437. var byteOffset = bufferViewDef.byteOffset || 0;
  31438. return buffer.slice(byteOffset, byteOffset + byteLength);
  31439. });
  31440. };
  31441. /**
  31442. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  31443. * @param {number} accessorIndex
  31444. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  31445. */
  31446. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  31447. var parser = this;
  31448. var json = this.json;
  31449. var accessorDef = this.json.accessors[accessorIndex];
  31450. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  31451. // Ignore empty accessors, which may be used to declare runtime
  31452. // information about attributes coming from another source (e.g. Draco
  31453. // compression extension).
  31454. return Promise.resolve(null);
  31455. }
  31456. var pendingBufferViews = [];
  31457. if (accessorDef.bufferView !== undefined) {
  31458. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  31459. } else {
  31460. pendingBufferViews.push(null);
  31461. }
  31462. if (accessorDef.sparse !== undefined) {
  31463. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  31464. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  31465. }
  31466. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  31467. var bufferView = bufferViews[0];
  31468. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  31469. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  31470. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  31471. var itemBytes = elementBytes * itemSize;
  31472. var byteOffset = accessorDef.byteOffset || 0;
  31473. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  31474. var normalized = accessorDef.normalized === true;
  31475. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  31476. if (byteStride && byteStride !== itemBytes) {
  31477. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  31478. // This makes sure that IBA.count reflects accessor.count properly
  31479. var ibSlice = Math.floor(byteOffset / byteStride);
  31480. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  31481. var ib = parser.cache.get(ibCacheKey);
  31482. if (!ib) {
  31483. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  31484. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  31485. parser.cache.add(ibCacheKey, ib);
  31486. }
  31487. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  31488. } else {
  31489. if (bufferView === null) {
  31490. array = new TypedArray(accessorDef.count * itemSize);
  31491. } else {
  31492. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  31493. }
  31494. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  31495. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  31496. if (accessorDef.sparse !== undefined) {
  31497. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  31498. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  31499. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  31500. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  31501. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  31502. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  31503. if (bufferView !== null) {
  31504. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  31505. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  31506. }
  31507. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  31508. var index = sparseIndices[i];
  31509. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  31510. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  31511. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  31512. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  31513. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  31514. }
  31515. }
  31516. return bufferAttribute;
  31517. });
  31518. };
  31519. /**
  31520. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  31521. * @param {number} textureIndex
  31522. * @return {Promise<THREE.Texture>}
  31523. */
  31524. GLTFParser.prototype.loadTexture = function (textureIndex) {
  31525. var parser = this;
  31526. var json = this.json;
  31527. var options = this.options;
  31528. var textureLoader = this.textureLoader;
  31529. var URL = window.URL || window.webkitURL;
  31530. var textureDef = json.textures[textureIndex];
  31531. var textureExtensions = textureDef.extensions || {};
  31532. var source;
  31533. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  31534. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  31535. } else {
  31536. source = json.images[textureDef.source];
  31537. }
  31538. var sourceURI = source.uri;
  31539. var isObjectURL = false;
  31540. if (source.bufferView !== undefined) {
  31541. // Load binary image data from bufferView, if provided.
  31542. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  31543. isObjectURL = true;
  31544. var blob = new Blob([bufferView], {
  31545. type: source.mimeType
  31546. });
  31547. sourceURI = URL.createObjectURL(blob);
  31548. return sourceURI;
  31549. });
  31550. }
  31551. return Promise.resolve(sourceURI).then(function (sourceURI) {
  31552. // Load Texture resource.
  31553. var loader = options.manager.getHandler(sourceURI);
  31554. if (!loader) {
  31555. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  31556. }
  31557. return new Promise(function (resolve, reject) {
  31558. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  31559. });
  31560. }).then(function (texture) {
  31561. // Clean up resources and configure Texture.
  31562. if (isObjectURL === true) {
  31563. URL.revokeObjectURL(sourceURI);
  31564. }
  31565. texture.flipY = false;
  31566. if (textureDef.name !== undefined) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  31567. if (source.mimeType in MIME_TYPE_FORMATS) {
  31568. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  31569. }
  31570. var samplers = json.samplers || {};
  31571. var sampler = samplers[textureDef.sampler] || {};
  31572. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  31573. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  31574. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  31575. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  31576. return texture;
  31577. });
  31578. };
  31579. /**
  31580. * Asynchronously assigns a texture to the given material parameters.
  31581. * @param {Object} materialParams
  31582. * @param {string} mapName
  31583. * @param {Object} mapDef
  31584. * @return {Promise}
  31585. */
  31586. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  31587. var parser = this;
  31588. return this.getDependency('texture', mapDef.index).then(function (texture) {
  31589. if (!texture.isCompressedTexture) {
  31590. switch (mapName) {
  31591. case 'aoMap':
  31592. case 'emissiveMap':
  31593. case 'metalnessMap':
  31594. case 'normalMap':
  31595. case 'roughnessMap':
  31596. texture.format = _threeModule.RGBFormat;
  31597. break;
  31598. }
  31599. }
  31600. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  31601. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  31602. if (transform) {
  31603. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  31604. }
  31605. }
  31606. materialParams[mapName] = texture;
  31607. });
  31608. };
  31609. /**
  31610. * Assigns final material to a Mesh, Line, or Points instance. The instance
  31611. * already has a material (generated from the glTF material options alone)
  31612. * but reuse of the same glTF material may require multiple threejs materials
  31613. * to accomodate different primitive types, defines, etc. New materials will
  31614. * be created if necessary, and reused from a cache.
  31615. * @param {Object3D} mesh Mesh, Line, or Points instance.
  31616. */
  31617. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  31618. var geometry = mesh.geometry;
  31619. var material = mesh.material;
  31620. var extensions = this.extensions;
  31621. var useVertexTangents = geometry.attributes.tangent !== undefined;
  31622. var useVertexColors = geometry.attributes.color !== undefined;
  31623. var useFlatShading = geometry.attributes.normal === undefined;
  31624. var useSkinning = mesh.isSkinnedMesh === true;
  31625. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  31626. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  31627. if (mesh.isPoints) {
  31628. var cacheKey = 'PointsMaterial:' + material.uuid;
  31629. var pointsMaterial = this.cache.get(cacheKey);
  31630. if (!pointsMaterial) {
  31631. pointsMaterial = new _threeModule.PointsMaterial();
  31632. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  31633. pointsMaterial.color.copy(material.color);
  31634. pointsMaterial.map = material.map;
  31635. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  31636. this.cache.add(cacheKey, pointsMaterial);
  31637. }
  31638. material = pointsMaterial;
  31639. } else if (mesh.isLine) {
  31640. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  31641. var lineMaterial = this.cache.get(cacheKey);
  31642. if (!lineMaterial) {
  31643. lineMaterial = new _threeModule.LineBasicMaterial();
  31644. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  31645. lineMaterial.color.copy(material.color);
  31646. this.cache.add(cacheKey, lineMaterial);
  31647. }
  31648. material = lineMaterial;
  31649. } // Clone the material if it will be modified
  31650. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  31651. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  31652. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  31653. if (useSkinning) cacheKey += 'skinning:';
  31654. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  31655. if (useVertexColors) cacheKey += 'vertex-colors:';
  31656. if (useFlatShading) cacheKey += 'flat-shading:';
  31657. if (useMorphTargets) cacheKey += 'morph-targets:';
  31658. if (useMorphNormals) cacheKey += 'morph-normals:';
  31659. var cachedMaterial = this.cache.get(cacheKey);
  31660. if (!cachedMaterial) {
  31661. cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].cloneMaterial(material) : material.clone();
  31662. if (useSkinning) cachedMaterial.skinning = true;
  31663. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  31664. if (useVertexColors) cachedMaterial.vertexColors = _threeModule.VertexColors;
  31665. if (useFlatShading) cachedMaterial.flatShading = true;
  31666. if (useMorphTargets) cachedMaterial.morphTargets = true;
  31667. if (useMorphNormals) cachedMaterial.morphNormals = true;
  31668. this.cache.add(cacheKey, cachedMaterial);
  31669. }
  31670. material = cachedMaterial;
  31671. } // workarounds for mesh and geometry
  31672. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  31673. console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.');
  31674. geometry.addAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  31675. }
  31676. if (material.isGLTFSpecularGlossinessMaterial) {
  31677. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  31678. mesh.onBeforeRender = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].refreshUniforms;
  31679. }
  31680. mesh.material = material;
  31681. };
  31682. /**
  31683. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  31684. * @param {number} materialIndex
  31685. * @return {Promise<Material>}
  31686. */
  31687. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  31688. var parser = this;
  31689. var json = this.json;
  31690. var extensions = this.extensions;
  31691. var materialDef = json.materials[materialIndex];
  31692. var materialType;
  31693. var materialParams = {};
  31694. var materialExtensions = materialDef.extensions || {};
  31695. var pending = [];
  31696. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  31697. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  31698. materialType = sgExtension.getMaterialType();
  31699. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  31700. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  31701. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  31702. materialType = kmuExtension.getMaterialType();
  31703. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  31704. } else {
  31705. // Specification:
  31706. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  31707. materialType = _threeModule.MeshStandardMaterial;
  31708. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  31709. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31710. materialParams.opacity = 1.0;
  31711. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31712. var array = metallicRoughness.baseColorFactor;
  31713. materialParams.color.fromArray(array);
  31714. materialParams.opacity = array[3];
  31715. }
  31716. if (metallicRoughness.baseColorTexture !== undefined) {
  31717. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31718. }
  31719. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  31720. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  31721. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  31722. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  31723. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  31724. }
  31725. }
  31726. if (materialDef.doubleSided === true) {
  31727. materialParams.side = _threeModule.DoubleSide;
  31728. }
  31729. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  31730. if (alphaMode === ALPHA_MODES.BLEND) {
  31731. materialParams.transparent = true;
  31732. } else {
  31733. materialParams.transparent = false;
  31734. if (alphaMode === ALPHA_MODES.MASK) {
  31735. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  31736. }
  31737. }
  31738. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31739. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  31740. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  31741. if (materialDef.normalTexture.scale !== undefined) {
  31742. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  31743. }
  31744. }
  31745. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31746. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  31747. if (materialDef.occlusionTexture.strength !== undefined) {
  31748. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  31749. }
  31750. }
  31751. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31752. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  31753. }
  31754. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  31755. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  31756. }
  31757. return Promise.all(pending).then(function () {
  31758. var material;
  31759. if (materialType === _threeModule.ShaderMaterial) {
  31760. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  31761. } else {
  31762. material = new materialType(materialParams);
  31763. }
  31764. if (materialDef.name !== undefined) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  31765. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  31766. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  31767. if (material.specularMap) material.specularMap.encoding = _threeModule.sRGBEncoding;
  31768. assignExtrasToUserData(material, materialDef);
  31769. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  31770. return material;
  31771. });
  31772. };
  31773. /**
  31774. * @param {BufferGeometry} geometry
  31775. * @param {GLTF.Primitive} primitiveDef
  31776. * @param {GLTFParser} parser
  31777. * @return {Promise<BufferGeometry>}
  31778. */
  31779. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  31780. var attributes = primitiveDef.attributes;
  31781. var pending = [];
  31782. function assignAttributeAccessor(accessorIndex, attributeName) {
  31783. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  31784. geometry.addAttribute(attributeName, accessor);
  31785. });
  31786. }
  31787. for (var gltfAttributeName in attributes) {
  31788. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  31789. if (threeAttributeName in geometry.attributes) continue;
  31790. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  31791. }
  31792. if (primitiveDef.indices !== undefined && !geometry.index) {
  31793. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  31794. geometry.setIndex(accessor);
  31795. });
  31796. pending.push(accessor);
  31797. }
  31798. assignExtrasToUserData(geometry, primitiveDef);
  31799. return Promise.all(pending).then(function () {
  31800. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  31801. });
  31802. }
  31803. /**
  31804. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  31805. *
  31806. * Creates BufferGeometries from primitives.
  31807. *
  31808. * @param {Array<GLTF.Primitive>} primitives
  31809. * @return {Promise<Array<BufferGeometry>>}
  31810. */
  31811. GLTFParser.prototype.loadGeometries = function (primitives) {
  31812. var parser = this;
  31813. var extensions = this.extensions;
  31814. var cache = this.primitiveCache;
  31815. function createDracoPrimitive(primitive) {
  31816. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  31817. return addPrimitiveAttributes(geometry, primitive, parser);
  31818. });
  31819. }
  31820. var pending = [];
  31821. for (var i = 0, il = primitives.length; i < il; i++) {
  31822. var primitive = primitives[i];
  31823. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  31824. var cached = cache[cacheKey];
  31825. if (cached) {
  31826. // Use the cached geometry if it exists
  31827. pending.push(cached.promise);
  31828. } else {
  31829. var geometryPromise;
  31830. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  31831. // Use DRACO geometry if available
  31832. geometryPromise = createDracoPrimitive(primitive);
  31833. } else {
  31834. // Otherwise create a new geometry
  31835. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  31836. } // Cache this geometry
  31837. cache[cacheKey] = {
  31838. primitive: primitive,
  31839. promise: geometryPromise
  31840. };
  31841. pending.push(geometryPromise);
  31842. }
  31843. }
  31844. return Promise.all(pending);
  31845. };
  31846. /**
  31847. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  31848. * @param {number} meshIndex
  31849. * @return {Promise<Group|Mesh|SkinnedMesh>}
  31850. */
  31851. GLTFParser.prototype.loadMesh = function (meshIndex) {
  31852. var parser = this;
  31853. var json = this.json;
  31854. var meshDef = json.meshes[meshIndex];
  31855. var primitives = meshDef.primitives;
  31856. var pending = [];
  31857. for (var i = 0, il = primitives.length; i < il; i++) {
  31858. var material = primitives[i].material === undefined ? createDefaultMaterial() : this.getDependency('material', primitives[i].material);
  31859. pending.push(material);
  31860. }
  31861. return Promise.all(pending).then(function (originalMaterials) {
  31862. return parser.loadGeometries(primitives).then(function (geometries) {
  31863. var meshes = [];
  31864. for (var i = 0, il = geometries.length; i < il; i++) {
  31865. var geometry = geometries[i];
  31866. var primitive = primitives[i]; // 1. create Mesh
  31867. var mesh;
  31868. var material = originalMaterials[i];
  31869. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  31870. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  31871. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  31872. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  31873. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  31874. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  31875. mesh.normalizeSkinWeights();
  31876. }
  31877. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  31878. mesh.drawMode = _threeModule.TriangleStripDrawMode;
  31879. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  31880. mesh.drawMode = _threeModule.TriangleFanDrawMode;
  31881. }
  31882. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  31883. mesh = new _threeModule.LineSegments(geometry, material);
  31884. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  31885. mesh = new _threeModule.Line(geometry, material);
  31886. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  31887. mesh = new _threeModule.LineLoop(geometry, material);
  31888. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  31889. mesh = new _threeModule.Points(geometry, material);
  31890. } else {
  31891. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  31892. }
  31893. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  31894. updateMorphTargets(mesh, meshDef);
  31895. }
  31896. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  31897. if (geometries.length > 1) mesh.name += '_' + i;
  31898. assignExtrasToUserData(mesh, meshDef);
  31899. parser.assignFinalMaterial(mesh);
  31900. meshes.push(mesh);
  31901. }
  31902. if (meshes.length === 1) {
  31903. return meshes[0];
  31904. }
  31905. var group = new _threeModule.Group();
  31906. for (var i = 0, il = meshes.length; i < il; i++) {
  31907. group.add(meshes[i]);
  31908. }
  31909. return group;
  31910. });
  31911. });
  31912. };
  31913. /**
  31914. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  31915. * @param {number} cameraIndex
  31916. * @return {Promise<THREE.Camera>}
  31917. */
  31918. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  31919. var camera;
  31920. var cameraDef = this.json.cameras[cameraIndex];
  31921. var params = cameraDef[cameraDef.type];
  31922. if (!params) {
  31923. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  31924. return;
  31925. }
  31926. if (cameraDef.type === 'perspective') {
  31927. camera = new _threeModule.PerspectiveCamera(_threeModule.Math.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  31928. } else if (cameraDef.type === 'orthographic') {
  31929. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  31930. }
  31931. if (cameraDef.name !== undefined) camera.name = cameraDef.name;
  31932. assignExtrasToUserData(camera, cameraDef);
  31933. return Promise.resolve(camera);
  31934. };
  31935. /**
  31936. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  31937. * @param {number} skinIndex
  31938. * @return {Promise<Object>}
  31939. */
  31940. GLTFParser.prototype.loadSkin = function (skinIndex) {
  31941. var skinDef = this.json.skins[skinIndex];
  31942. var skinEntry = {
  31943. joints: skinDef.joints
  31944. };
  31945. if (skinDef.inverseBindMatrices === undefined) {
  31946. return Promise.resolve(skinEntry);
  31947. }
  31948. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  31949. skinEntry.inverseBindMatrices = accessor;
  31950. return skinEntry;
  31951. });
  31952. };
  31953. /**
  31954. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  31955. * @param {number} animationIndex
  31956. * @return {Promise<AnimationClip>}
  31957. */
  31958. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  31959. var json = this.json;
  31960. var animationDef = json.animations[animationIndex];
  31961. var pendingNodes = [];
  31962. var pendingInputAccessors = [];
  31963. var pendingOutputAccessors = [];
  31964. var pendingSamplers = [];
  31965. var pendingTargets = [];
  31966. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  31967. var channel = animationDef.channels[i];
  31968. var sampler = animationDef.samplers[channel.sampler];
  31969. var target = channel.target;
  31970. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  31971. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  31972. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  31973. pendingNodes.push(this.getDependency('node', name));
  31974. pendingInputAccessors.push(this.getDependency('accessor', input));
  31975. pendingOutputAccessors.push(this.getDependency('accessor', output));
  31976. pendingSamplers.push(sampler);
  31977. pendingTargets.push(target);
  31978. }
  31979. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  31980. var nodes = dependencies[0];
  31981. var inputAccessors = dependencies[1];
  31982. var outputAccessors = dependencies[2];
  31983. var samplers = dependencies[3];
  31984. var targets = dependencies[4];
  31985. var tracks = [];
  31986. for (var i = 0, il = nodes.length; i < il; i++) {
  31987. var node = nodes[i];
  31988. var inputAccessor = inputAccessors[i];
  31989. var outputAccessor = outputAccessors[i];
  31990. var sampler = samplers[i];
  31991. var target = targets[i];
  31992. if (node === undefined) continue;
  31993. node.updateMatrix();
  31994. node.matrixAutoUpdate = true;
  31995. var TypedKeyframeTrack;
  31996. switch (PATH_PROPERTIES[target.path]) {
  31997. case PATH_PROPERTIES.weights:
  31998. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  31999. break;
  32000. case PATH_PROPERTIES.rotation:
  32001. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  32002. break;
  32003. case PATH_PROPERTIES.position:
  32004. case PATH_PROPERTIES.scale:
  32005. default:
  32006. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  32007. break;
  32008. }
  32009. var targetName = node.name ? node.name : node.uuid;
  32010. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  32011. var targetNames = [];
  32012. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  32013. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  32014. node.traverse(function (object) {
  32015. if (object.isMesh === true && object.morphTargetInfluences) {
  32016. targetNames.push(object.name ? object.name : object.uuid);
  32017. }
  32018. });
  32019. } else {
  32020. targetNames.push(targetName);
  32021. }
  32022. var outputArray = outputAccessor.array;
  32023. if (outputAccessor.normalized) {
  32024. var scale;
  32025. if (outputArray.constructor === Int8Array) {
  32026. scale = 1 / 127;
  32027. } else if (outputArray.constructor === Uint8Array) {
  32028. scale = 1 / 255;
  32029. } else if (outputArray.constructor == Int16Array) {
  32030. scale = 1 / 32767;
  32031. } else if (outputArray.constructor === Uint16Array) {
  32032. scale = 1 / 65535;
  32033. } else {
  32034. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  32035. }
  32036. var scaled = new Float32Array(outputArray.length);
  32037. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  32038. scaled[j] = outputArray[j] * scale;
  32039. }
  32040. outputArray = scaled;
  32041. }
  32042. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  32043. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  32044. if (sampler.interpolation === 'CUBICSPLINE') {
  32045. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  32046. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  32047. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  32048. // must be divided by three to get the interpolant's sampleSize argument.
  32049. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  32050. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  32051. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  32052. }
  32053. tracks.push(track);
  32054. }
  32055. }
  32056. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  32057. return new _threeModule.AnimationClip(name, undefined, tracks);
  32058. });
  32059. };
  32060. /**
  32061. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  32062. * @param {number} nodeIndex
  32063. * @return {Promise<Object3D>}
  32064. */
  32065. GLTFParser.prototype.loadNode = function (nodeIndex) {
  32066. var json = this.json;
  32067. var extensions = this.extensions;
  32068. var parser = this;
  32069. var meshReferences = json.meshReferences;
  32070. var meshUses = json.meshUses;
  32071. var nodeDef = json.nodes[nodeIndex];
  32072. return function () {
  32073. var pending = [];
  32074. if (nodeDef.mesh !== undefined) {
  32075. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  32076. var node;
  32077. if (meshReferences[nodeDef.mesh] > 1) {
  32078. var instanceNum = meshUses[nodeDef.mesh]++;
  32079. node = mesh.clone();
  32080. node.name += '_instance_' + instanceNum; // onBeforeRender copy for Specular-Glossiness
  32081. node.onBeforeRender = mesh.onBeforeRender;
  32082. for (var i = 0, il = node.children.length; i < il; i++) {
  32083. node.children[i].name += '_instance_' + instanceNum;
  32084. node.children[i].onBeforeRender = mesh.children[i].onBeforeRender;
  32085. }
  32086. } else {
  32087. node = mesh;
  32088. } // if weights are provided on the node, override weights on the mesh.
  32089. if (nodeDef.weights !== undefined) {
  32090. node.traverse(function (o) {
  32091. if (!o.isMesh) return;
  32092. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  32093. o.morphTargetInfluences[i] = nodeDef.weights[i];
  32094. }
  32095. });
  32096. }
  32097. return node;
  32098. }));
  32099. }
  32100. if (nodeDef.camera !== undefined) {
  32101. pending.push(parser.getDependency('camera', nodeDef.camera));
  32102. }
  32103. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  32104. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  32105. }
  32106. return Promise.all(pending);
  32107. }().then(function (objects) {
  32108. var node; // .isBone isn't in glTF spec. See .markDefs
  32109. if (nodeDef.isBone === true) {
  32110. node = new _threeModule.Bone();
  32111. } else if (objects.length > 1) {
  32112. node = new _threeModule.Group();
  32113. } else if (objects.length === 1) {
  32114. node = objects[0];
  32115. } else {
  32116. node = new _threeModule.Object3D();
  32117. }
  32118. if (node !== objects[0]) {
  32119. for (var i = 0, il = objects.length; i < il; i++) {
  32120. node.add(objects[i]);
  32121. }
  32122. }
  32123. if (nodeDef.name !== undefined) {
  32124. node.userData.name = nodeDef.name;
  32125. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  32126. }
  32127. assignExtrasToUserData(node, nodeDef);
  32128. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  32129. if (nodeDef.matrix !== undefined) {
  32130. var matrix = new _threeModule.Matrix4();
  32131. matrix.fromArray(nodeDef.matrix);
  32132. node.applyMatrix(matrix);
  32133. } else {
  32134. if (nodeDef.translation !== undefined) {
  32135. node.position.fromArray(nodeDef.translation);
  32136. }
  32137. if (nodeDef.rotation !== undefined) {
  32138. node.quaternion.fromArray(nodeDef.rotation);
  32139. }
  32140. if (nodeDef.scale !== undefined) {
  32141. node.scale.fromArray(nodeDef.scale);
  32142. }
  32143. }
  32144. return node;
  32145. });
  32146. };
  32147. /**
  32148. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  32149. * @param {number} sceneIndex
  32150. * @return {Promise<Scene>}
  32151. */
  32152. GLTFParser.prototype.loadScene = function () {
  32153. // scene node hierachy builder
  32154. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  32155. var nodeDef = json.nodes[nodeId];
  32156. return parser.getDependency('node', nodeId).then(function (node) {
  32157. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  32158. var skinEntry;
  32159. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  32160. skinEntry = skin;
  32161. var pendingJoints = [];
  32162. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  32163. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  32164. }
  32165. return Promise.all(pendingJoints);
  32166. }).then(function (jointNodes) {
  32167. node.traverse(function (mesh) {
  32168. if (!mesh.isMesh) return;
  32169. var bones = [];
  32170. var boneInverses = [];
  32171. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  32172. var jointNode = jointNodes[j];
  32173. if (jointNode) {
  32174. bones.push(jointNode);
  32175. var mat = new _threeModule.Matrix4();
  32176. if (skinEntry.inverseBindMatrices !== undefined) {
  32177. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  32178. }
  32179. boneInverses.push(mat);
  32180. } else {
  32181. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  32182. }
  32183. }
  32184. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  32185. });
  32186. return node;
  32187. });
  32188. }).then(function (node) {
  32189. // build node hierachy
  32190. parentObject.add(node);
  32191. var pending = [];
  32192. if (nodeDef.children) {
  32193. var children = nodeDef.children;
  32194. for (var i = 0, il = children.length; i < il; i++) {
  32195. var child = children[i];
  32196. pending.push(buildNodeHierachy(child, node, json, parser));
  32197. }
  32198. }
  32199. return Promise.all(pending);
  32200. });
  32201. }
  32202. return function loadScene(sceneIndex) {
  32203. var json = this.json;
  32204. var extensions = this.extensions;
  32205. var sceneDef = this.json.scenes[sceneIndex];
  32206. var parser = this;
  32207. var scene = new _threeModule.Scene();
  32208. if (sceneDef.name !== undefined) scene.name = sceneDef.name;
  32209. assignExtrasToUserData(scene, sceneDef);
  32210. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  32211. var nodeIds = sceneDef.nodes || [];
  32212. var pending = [];
  32213. for (var i = 0, il = nodeIds.length; i < il; i++) {
  32214. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  32215. }
  32216. return Promise.all(pending).then(function () {
  32217. return scene;
  32218. });
  32219. };
  32220. }();
  32221. return GLTFLoader;
  32222. }();
  32223. exports.GLTFLoader = GLTFLoader;
  32224. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/ThreeB3DMLoader.js":[function(require,module,exports) {
  32225. "use strict";
  32226. Object.defineProperty(exports, "__esModule", {
  32227. value: true
  32228. });
  32229. exports.ThreeB3DMLoader = void 0;
  32230. var _B3DMLoader = require("./B3DMLoader.js");
  32231. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  32232. class ThreeB3DMLoader extends _B3DMLoader.B3DMLoader {
  32233. parse(buffer) {
  32234. const b3dm = super.parse(buffer);
  32235. const gltfBuffer = b3dm.glbBytes.slice().buffer;
  32236. return new Promise((resolve, reject) => {
  32237. new _GLTFLoader.GLTFLoader().parse(gltfBuffer, null, resolve, reject);
  32238. });
  32239. }
  32240. }
  32241. exports.ThreeB3DMLoader = ThreeB3DMLoader;
  32242. },{"./B3DMLoader.js":"../src/B3DMLoader.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/ThreeTilesRenderer.js":[function(require,module,exports) {
  32243. "use strict";
  32244. Object.defineProperty(exports, "__esModule", {
  32245. value: true
  32246. });
  32247. exports.ThreeTilesRenderer = void 0;
  32248. var _TilesRenderer = require("./TilesRenderer.js");
  32249. var _ThreeB3DMLoader = require("./ThreeB3DMLoader.js");
  32250. var _three = require("three");
  32251. const DEG2RAD = _three.Math.DEG2RAD;
  32252. const tempMat = new _three.Matrix4();
  32253. const tempQuaternion = new _three.Quaternion();
  32254. const tempVector = new _three.Vector3();
  32255. const resVector = new _three.Vector2();
  32256. const vecX = new _three.Vector3();
  32257. const vecY = new _three.Vector3();
  32258. const vecZ = new _three.Vector3(); // Specialization of "Group" that only updates world matrices of children if
  32259. // the transform has changed since the last update and ignores the "force"
  32260. // parameter under the assumption that the children tiles will not move.
  32261. class TilesGroup extends _three.Group {
  32262. constructor(tilesRenderer) {
  32263. super();
  32264. this.tilesRenderer = tilesRenderer;
  32265. }
  32266. raycast(raycaster, intersects) {
  32267. // TODO
  32268. const tilesRenderer = this.tilesRenderer;
  32269. }
  32270. updateMatrixWorld(force) {
  32271. if (this.matrixAutoUpdate) {
  32272. this.updateMatrix();
  32273. }
  32274. if (this.matrixWorldNeedsUpdate || force) {
  32275. if (this.parent === null) {
  32276. tempMat.copy(this.matrix);
  32277. } else {
  32278. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  32279. }
  32280. this.matrixWorldNeedsUpdate = false;
  32281. const elA = tempMat.elements;
  32282. const elB = this.matrixWorld.elements;
  32283. let isDifferent = false;
  32284. for (let i = 0; i < 16; i++) {
  32285. const itemA = elA[i];
  32286. const itemB = elB[i];
  32287. const diff = Math.abs(itemA - itemB);
  32288. if (diff > Number.EPSILON) {
  32289. isDifferent = true;
  32290. break;
  32291. }
  32292. }
  32293. if (isDifferent) {
  32294. this.matrixWorld.copy(tempMat); // update children
  32295. // the children will not have to change unless the parent group has updated
  32296. const children = this.children;
  32297. for (let i = 0, l = children.length; i < l; i++) {
  32298. children[i].updateMatrixWorld();
  32299. }
  32300. }
  32301. }
  32302. }
  32303. }
  32304. class ThreeTilesRenderer extends _TilesRenderer.TilesRenderer {
  32305. get displayBounds() {
  32306. return this._displayBounds;
  32307. }
  32308. set displayBounds(val) {
  32309. if (val !== this.displayBounds) {
  32310. this._displayBounds = val;
  32311. this.traverse(t => {
  32312. const scene = t.cached.scene;
  32313. const boxHelper = t.cached.boxHelper;
  32314. if (scene) {
  32315. if (val) {
  32316. scene.add(boxHelper);
  32317. boxHelper.updateMatrixWorld(true);
  32318. } else {
  32319. scene.remove(boxHelper);
  32320. }
  32321. }
  32322. });
  32323. }
  32324. }
  32325. constructor(url, cameras, renderer) {
  32326. super(url);
  32327. this.group = new TilesGroup();
  32328. this.cameras = Array.isArray(cameras) ? cameras : [cameras];
  32329. this.frustums = [];
  32330. this.renderer = renderer;
  32331. this.active = [];
  32332. }
  32333. /* Public API */
  32334. getBounds(box) {
  32335. if (!this.root) {
  32336. return false;
  32337. }
  32338. const d = this.root.boundingVolume.box;
  32339. box.min.set(d[0] - d[3], d[1] - d[7], d[2] - d[11]);
  32340. box.max.set(d[0] + d[3], d[1] + d[7], d[2] + d[11]);
  32341. return true;
  32342. }
  32343. /* Overriden */
  32344. update() {
  32345. const group = this.group;
  32346. const renderer = this.renderer;
  32347. const cameras = this.cameras;
  32348. const frustums = this.frustums; // automatically scale the array of frustums to match the cameras
  32349. while (frustums.length > cameras.length) {
  32350. frustums.pop();
  32351. }
  32352. while (frustums.length < cameras.length) {
  32353. frustums.push(new _three.Frustum());
  32354. } // store the camera frustums
  32355. for (let i = 0, l = frustums.length; i < l; i++) {
  32356. const camera = cameras[i];
  32357. const frustum = frustums[i];
  32358. tempMat.copy(group.matrixWorld);
  32359. tempMat.premultiply(camera.matrixWorldInverse);
  32360. tempMat.premultiply(camera.projectionMatrix);
  32361. frustum.setFromMatrix(tempMat);
  32362. } // store the resolution of the render
  32363. renderer.getSize(resVector);
  32364. resVector.multiplyScalar(renderer.getPixelRatio());
  32365. super.update();
  32366. }
  32367. preprocessNode(tile, parentTile, tileSetDir) {
  32368. super.preprocessNode(tile, parentTile, tileSetDir);
  32369. const transform = new _three.Matrix4();
  32370. if (tile.transform) {
  32371. const transformArr = tile.transform;
  32372. for (let i = 0; i < 16; i++) {
  32373. transform.elements[i] = transformArr[i];
  32374. }
  32375. } else {
  32376. transform.identity();
  32377. }
  32378. let box = null;
  32379. let boxTransform = null;
  32380. if ('box' in tile.boundingVolume) {
  32381. const data = tile.boundingVolume.box;
  32382. box = new _three.Box3();
  32383. boxTransform = new _three.Matrix4(); // get the extents of the bounds in each axis
  32384. vecX.set(data[3], data[4], data[5]);
  32385. vecY.set(data[6], data[7], data[8]);
  32386. vecZ.set(data[9], data[10], data[11]);
  32387. const scaleX = vecX.length();
  32388. const scaleY = vecY.length();
  32389. const scaleZ = vecZ.length();
  32390. vecX.normalize();
  32391. vecY.normalize();
  32392. vecZ.normalize(); // create the oriented frame that the box exists in
  32393. 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
  32394. box.min.set(-scaleX, -scaleY, -scaleZ);
  32395. box.max.set(scaleX, scaleY, scaleZ);
  32396. }
  32397. let sphere = null;
  32398. if ('sphere' in tile.boundingVolume) {
  32399. const data = tile.boundingVolume.sphere;
  32400. sphere = new _three.Sphere();
  32401. sphere.center.set(data[0], data[1], data[2]);
  32402. sphere.radius = data[3];
  32403. } else if ('box' in tile.boundingVolume) {
  32404. sphere = new _three.Sphere();
  32405. box.getBoundingSphere(sphere);
  32406. boxTransform.decompose(sphere.center, tempQuaternion, tempVector);
  32407. }
  32408. let region = null;
  32409. if ('region' in tile.boundingVolume) {
  32410. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  32411. }
  32412. tile.cached = {
  32413. loadIndex: 0,
  32414. transform,
  32415. active: false,
  32416. box,
  32417. boxTransform,
  32418. sphere,
  32419. region,
  32420. boxHelper: null,
  32421. scene: null
  32422. };
  32423. }
  32424. parseTile(buffer, tile) {
  32425. tile._loadIndex = tile._loadIndex || 0;
  32426. tile._loadIndex++; // TODO: 90 degree rotation must be applied to GLTF file to resolve "up"
  32427. const loadIndex = tile._loadIndex;
  32428. return new _ThreeB3DMLoader.ThreeB3DMLoader().parse(buffer).then(res => {
  32429. if (tile._loadIndex !== loadIndex) {
  32430. return;
  32431. }
  32432. const cached = tile.cached;
  32433. const cachedBox = cached.box;
  32434. const cachedBoxMat = cached.boxTransform; // add a helper group to represent the obb rotation matrix
  32435. const boxHelper = new _three.Box3Helper(cachedBox);
  32436. const boxHelperGroup = new _three.Group();
  32437. cachedBoxMat.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  32438. boxHelperGroup.add(boxHelper);
  32439. boxHelperGroup.updateMatrixWorld(true);
  32440. const scene = res.scene;
  32441. cached.transform.decompose(scene.position, scene.quaternion, scene.scale);
  32442. scene.traverse(c => c.frustumCulled = false);
  32443. cached.boxHelper = boxHelperGroup;
  32444. cached.scene = res.scene;
  32445. if (this.displayBounds) {
  32446. cached.scene.add(cached.boxHelper);
  32447. }
  32448. });
  32449. }
  32450. disposeTile(tile) {
  32451. const cached = tile.cached;
  32452. if (cached.scene) {
  32453. const scene = cached.scene;
  32454. if (scene.parent) {
  32455. scene.parent.remove(scene);
  32456. }
  32457. scene.traverse(c => {
  32458. if (c.geometry) {
  32459. c.geometry.dispose();
  32460. }
  32461. if (c.material) {
  32462. c.material.dispose(); // TODO: dispose textures
  32463. }
  32464. });
  32465. cached.scene = null;
  32466. cached.boxHelper = null;
  32467. }
  32468. tile._loadIndex++;
  32469. }
  32470. setTileVisible(tile, visible) {
  32471. const scene = tile.cached.scene;
  32472. if (visible) {
  32473. if (scene && !scene.parent) {
  32474. this.group.add(scene);
  32475. scene.updateMatrixWorld(true);
  32476. }
  32477. } else {
  32478. this.group.remove(scene);
  32479. }
  32480. }
  32481. setTileActive(tile, active) {
  32482. const cached = tile.cached;
  32483. if (active !== cached.active) {
  32484. cached.active = active;
  32485. if (active) {
  32486. this.active.push(cached.scene);
  32487. } else {
  32488. const index = this.active.indexOf(cached.scene);
  32489. this.active.splice(index, 1);
  32490. }
  32491. }
  32492. }
  32493. calculateError(tile) {
  32494. const cached = tile.cached;
  32495. const cameras = this.cameras;
  32496. const group = this.group; // TODO: Use the content bounding volume here?
  32497. const boundingVolume = tile.boundingVolume;
  32498. const groupMatrixWorld = group.matrixWorld;
  32499. const transformMat = cached.transform;
  32500. if ('box' in boundingVolume) {
  32501. const boundingBox = cached.box;
  32502. const obbMat = cached.boxTransform; // TODO: these can likely be cached? Or the world transform mat can be used
  32503. // transformMat can be rolled into oobMat
  32504. tempMat.multiplyMatrices(transformMat, obbMat);
  32505. tempMat.premultiply(groupMatrixWorld);
  32506. tempMat.getInverse(tempMat);
  32507. let minError = Infinity;
  32508. for (let i = 0, l = cameras.length; i < l; i++) {
  32509. const cam = cameras[i];
  32510. tempVector.copy(cam.position);
  32511. tempVector.applyMatrix4(tempMat);
  32512. let error;
  32513. if (cam.isOrthographic) {
  32514. const w = cam.right - cam.left;
  32515. const h = cam.top - cam.bottom;
  32516. const pixelSize = Math.Max(h, w) / Math.Max(resVector.width, resVector.height);
  32517. error = tile.geometricError / pixelSize;
  32518. } else {
  32519. const distance = boundingBox.distanceToPoint(tempVector);
  32520. const sseDenominator = 2 * Math.tan(0.5 * cam.fov * DEG2RAD);
  32521. error = tile.geometricError * resVector.height / (distance * sseDenominator);
  32522. }
  32523. minError = Math.min(minError, error);
  32524. }
  32525. return minError;
  32526. } else if ('sphere' in boundingVolume) {
  32527. const sphere = cached.sphere;
  32528. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  32529. } else if ('region' in boundingVolume) {
  32530. // unsupported
  32531. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  32532. }
  32533. return Infinity;
  32534. }
  32535. tileInView(tile) {
  32536. // TODO: we should use the more precise bounding volumes here if possible
  32537. // cache the root-space planes
  32538. const sphere = tile.cached.sphere;
  32539. if (sphere) {
  32540. const frustums = this.frustums;
  32541. for (let i = 0, l = frustums.length; i < l; i++) {
  32542. const frustum = frustums[i];
  32543. if (frustum.intersectsSphere(sphere)) {
  32544. return true;
  32545. }
  32546. }
  32547. return false;
  32548. }
  32549. return true;
  32550. }
  32551. }
  32552. exports.ThreeTilesRenderer = ThreeTilesRenderer;
  32553. },{"./TilesRenderer.js":"../src/TilesRenderer.js","./ThreeB3DMLoader.js":"../src/ThreeB3DMLoader.js","three":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  32554. "use strict";
  32555. Object.defineProperty(exports, "__esModule", {
  32556. value: true
  32557. });
  32558. exports.MapControls = exports.OrbitControls = void 0;
  32559. var _threeModule = require("../../../build/three.module.js");
  32560. /**
  32561. * @author qiao / https://github.com/qiao
  32562. * @author mrdoob / http://mrdoob.com
  32563. * @author alteredq / http://alteredqualia.com/
  32564. * @author WestLangley / http://github.com/WestLangley
  32565. * @author erich666 / http://erichaines.com
  32566. * @author ScieCode / http://github.com/sciecode
  32567. */
  32568. // This set of controls performs orbiting, dollying (zooming), and panning.
  32569. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  32570. //
  32571. // Orbit - left mouse / touch: one-finger move
  32572. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  32573. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  32574. var OrbitControls = function (object, domElement) {
  32575. this.object = object;
  32576. this.domElement = domElement !== undefined ? domElement : document; // Set to false to disable this control
  32577. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  32578. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  32579. this.minDistance = 0;
  32580. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  32581. this.minZoom = 0;
  32582. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  32583. // Range is 0 to Math.PI radians.
  32584. this.minPolarAngle = 0; // radians
  32585. this.maxPolarAngle = Math.PI; // radians
  32586. // How far you can orbit horizontally, upper and lower limits.
  32587. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  32588. this.minAzimuthAngle = -Infinity; // radians
  32589. this.maxAzimuthAngle = Infinity; // radians
  32590. // Set to true to enable damping (inertia)
  32591. // If damping is enabled, you must call controls.update() in your animation loop
  32592. this.enableDamping = false;
  32593. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  32594. // Set to false to disable zooming
  32595. this.enableZoom = true;
  32596. this.zoomSpeed = 1.0; // Set to false to disable rotating
  32597. this.enableRotate = true;
  32598. this.rotateSpeed = 1.0; // Set to false to disable panning
  32599. this.enablePan = true;
  32600. this.panSpeed = 1.0;
  32601. this.screenSpacePanning = false; // if true, pan in screen-space
  32602. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  32603. // Set to true to automatically rotate around the target
  32604. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  32605. this.autoRotate = false;
  32606. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  32607. // Set to false to disable use of the keys
  32608. this.enableKeys = true; // The four arrow keys
  32609. this.keys = {
  32610. LEFT: 37,
  32611. UP: 38,
  32612. RIGHT: 39,
  32613. BOTTOM: 40
  32614. }; // Mouse buttons
  32615. this.mouseButtons = {
  32616. LEFT: _threeModule.MOUSE.ROTATE,
  32617. MIDDLE: _threeModule.MOUSE.DOLLY,
  32618. RIGHT: _threeModule.MOUSE.PAN
  32619. }; // Touch fingers
  32620. this.touches = {
  32621. ONE: _threeModule.TOUCH.ROTATE,
  32622. TWO: _threeModule.TOUCH.DOLLY_PAN
  32623. }; // for reset
  32624. this.target0 = this.target.clone();
  32625. this.position0 = this.object.position.clone();
  32626. this.zoom0 = this.object.zoom; //
  32627. // public methods
  32628. //
  32629. this.getPolarAngle = function () {
  32630. return spherical.phi;
  32631. };
  32632. this.getAzimuthalAngle = function () {
  32633. return spherical.theta;
  32634. };
  32635. this.saveState = function () {
  32636. scope.target0.copy(scope.target);
  32637. scope.position0.copy(scope.object.position);
  32638. scope.zoom0 = scope.object.zoom;
  32639. };
  32640. this.reset = function () {
  32641. scope.target.copy(scope.target0);
  32642. scope.object.position.copy(scope.position0);
  32643. scope.object.zoom = scope.zoom0;
  32644. scope.object.updateProjectionMatrix();
  32645. scope.dispatchEvent(changeEvent);
  32646. scope.update();
  32647. state = STATE.NONE;
  32648. }; // this method is exposed, but perhaps it would be better if we can make it private...
  32649. this.update = function () {
  32650. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  32651. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  32652. var quatInverse = quat.clone().inverse();
  32653. var lastPosition = new _threeModule.Vector3();
  32654. var lastQuaternion = new _threeModule.Quaternion();
  32655. return function update() {
  32656. var position = scope.object.position;
  32657. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  32658. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  32659. spherical.setFromVector3(offset);
  32660. if (scope.autoRotate && state === STATE.NONE) {
  32661. rotateLeft(getAutoRotationAngle());
  32662. }
  32663. if (scope.enableDamping) {
  32664. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  32665. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  32666. } else {
  32667. spherical.theta += sphericalDelta.theta;
  32668. spherical.phi += sphericalDelta.phi;
  32669. } // restrict theta to be between desired limits
  32670. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  32671. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  32672. spherical.makeSafe();
  32673. spherical.radius *= scale; // restrict radius to be between desired limits
  32674. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  32675. if (scope.enableDamping === true) {
  32676. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  32677. } else {
  32678. scope.target.add(panOffset);
  32679. }
  32680. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  32681. offset.applyQuaternion(quatInverse);
  32682. position.copy(scope.target).add(offset);
  32683. scope.object.lookAt(scope.target);
  32684. if (scope.enableDamping === true) {
  32685. sphericalDelta.theta *= 1 - scope.dampingFactor;
  32686. sphericalDelta.phi *= 1 - scope.dampingFactor;
  32687. panOffset.multiplyScalar(1 - scope.dampingFactor);
  32688. } else {
  32689. sphericalDelta.set(0, 0, 0);
  32690. panOffset.set(0, 0, 0);
  32691. }
  32692. scale = 1; // update condition is:
  32693. // min(camera displacement, camera rotation in radians)^2 > EPS
  32694. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  32695. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  32696. scope.dispatchEvent(changeEvent);
  32697. lastPosition.copy(scope.object.position);
  32698. lastQuaternion.copy(scope.object.quaternion);
  32699. zoomChanged = false;
  32700. return true;
  32701. }
  32702. return false;
  32703. };
  32704. }();
  32705. this.dispose = function () {
  32706. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  32707. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  32708. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  32709. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  32710. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  32711. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  32712. document.removeEventListener('mousemove', onMouseMove, false);
  32713. document.removeEventListener('mouseup', onMouseUp, false);
  32714. window.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  32715. }; //
  32716. // internals
  32717. //
  32718. var scope = this;
  32719. var changeEvent = {
  32720. type: 'change'
  32721. };
  32722. var startEvent = {
  32723. type: 'start'
  32724. };
  32725. var endEvent = {
  32726. type: 'end'
  32727. };
  32728. var STATE = {
  32729. NONE: -1,
  32730. ROTATE: 0,
  32731. DOLLY: 1,
  32732. PAN: 2,
  32733. TOUCH_ROTATE: 3,
  32734. TOUCH_PAN: 4,
  32735. TOUCH_DOLLY_PAN: 5,
  32736. TOUCH_DOLLY_ROTATE: 6
  32737. };
  32738. var state = STATE.NONE;
  32739. var EPS = 0.000001; // current position in spherical coordinates
  32740. var spherical = new _threeModule.Spherical();
  32741. var sphericalDelta = new _threeModule.Spherical();
  32742. var scale = 1;
  32743. var panOffset = new _threeModule.Vector3();
  32744. var zoomChanged = false;
  32745. var rotateStart = new _threeModule.Vector2();
  32746. var rotateEnd = new _threeModule.Vector2();
  32747. var rotateDelta = new _threeModule.Vector2();
  32748. var panStart = new _threeModule.Vector2();
  32749. var panEnd = new _threeModule.Vector2();
  32750. var panDelta = new _threeModule.Vector2();
  32751. var dollyStart = new _threeModule.Vector2();
  32752. var dollyEnd = new _threeModule.Vector2();
  32753. var dollyDelta = new _threeModule.Vector2();
  32754. function getAutoRotationAngle() {
  32755. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  32756. }
  32757. function getZoomScale() {
  32758. return Math.pow(0.95, scope.zoomSpeed);
  32759. }
  32760. function rotateLeft(angle) {
  32761. sphericalDelta.theta -= angle;
  32762. }
  32763. function rotateUp(angle) {
  32764. sphericalDelta.phi -= angle;
  32765. }
  32766. var panLeft = function () {
  32767. var v = new _threeModule.Vector3();
  32768. return function panLeft(distance, objectMatrix) {
  32769. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  32770. v.multiplyScalar(-distance);
  32771. panOffset.add(v);
  32772. };
  32773. }();
  32774. var panUp = function () {
  32775. var v = new _threeModule.Vector3();
  32776. return function panUp(distance, objectMatrix) {
  32777. if (scope.screenSpacePanning === true) {
  32778. v.setFromMatrixColumn(objectMatrix, 1);
  32779. } else {
  32780. v.setFromMatrixColumn(objectMatrix, 0);
  32781. v.crossVectors(scope.object.up, v);
  32782. }
  32783. v.multiplyScalar(distance);
  32784. panOffset.add(v);
  32785. };
  32786. }(); // deltaX and deltaY are in pixels; right and down are positive
  32787. var pan = function () {
  32788. var offset = new _threeModule.Vector3();
  32789. return function pan(deltaX, deltaY) {
  32790. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32791. if (scope.object.isPerspectiveCamera) {
  32792. // perspective
  32793. var position = scope.object.position;
  32794. offset.copy(position).sub(scope.target);
  32795. var targetDistance = offset.length(); // half of the fov is center to top of screen
  32796. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  32797. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  32798. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  32799. } else if (scope.object.isOrthographicCamera) {
  32800. // orthographic
  32801. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  32802. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  32803. } else {
  32804. // camera neither orthographic nor perspective
  32805. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  32806. scope.enablePan = false;
  32807. }
  32808. };
  32809. }();
  32810. function dollyIn(dollyScale) {
  32811. if (scope.object.isPerspectiveCamera) {
  32812. scale /= dollyScale;
  32813. } else if (scope.object.isOrthographicCamera) {
  32814. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  32815. scope.object.updateProjectionMatrix();
  32816. zoomChanged = true;
  32817. } else {
  32818. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  32819. scope.enableZoom = false;
  32820. }
  32821. }
  32822. function dollyOut(dollyScale) {
  32823. if (scope.object.isPerspectiveCamera) {
  32824. scale *= dollyScale;
  32825. } else if (scope.object.isOrthographicCamera) {
  32826. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  32827. scope.object.updateProjectionMatrix();
  32828. zoomChanged = true;
  32829. } else {
  32830. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  32831. scope.enableZoom = false;
  32832. }
  32833. } //
  32834. // event callbacks - update the object state
  32835. //
  32836. function handleMouseDownRotate(event) {
  32837. rotateStart.set(event.clientX, event.clientY);
  32838. }
  32839. function handleMouseDownDolly(event) {
  32840. dollyStart.set(event.clientX, event.clientY);
  32841. }
  32842. function handleMouseDownPan(event) {
  32843. panStart.set(event.clientX, event.clientY);
  32844. }
  32845. function handleMouseMoveRotate(event) {
  32846. rotateEnd.set(event.clientX, event.clientY);
  32847. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  32848. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32849. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  32850. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  32851. rotateStart.copy(rotateEnd);
  32852. scope.update();
  32853. }
  32854. function handleMouseMoveDolly(event) {
  32855. dollyEnd.set(event.clientX, event.clientY);
  32856. dollyDelta.subVectors(dollyEnd, dollyStart);
  32857. if (dollyDelta.y > 0) {
  32858. dollyIn(getZoomScale());
  32859. } else if (dollyDelta.y < 0) {
  32860. dollyOut(getZoomScale());
  32861. }
  32862. dollyStart.copy(dollyEnd);
  32863. scope.update();
  32864. }
  32865. function handleMouseMovePan(event) {
  32866. panEnd.set(event.clientX, event.clientY);
  32867. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  32868. pan(panDelta.x, panDelta.y);
  32869. panStart.copy(panEnd);
  32870. scope.update();
  32871. }
  32872. function handleMouseUp()
  32873. /*event*/
  32874. {// no-op
  32875. }
  32876. function handleMouseWheel(event) {
  32877. if (event.deltaY < 0) {
  32878. dollyOut(getZoomScale());
  32879. } else if (event.deltaY > 0) {
  32880. dollyIn(getZoomScale());
  32881. }
  32882. scope.update();
  32883. }
  32884. function handleKeyDown(event) {
  32885. var needsUpdate = false;
  32886. switch (event.keyCode) {
  32887. case scope.keys.UP:
  32888. pan(0, scope.keyPanSpeed);
  32889. needsUpdate = true;
  32890. break;
  32891. case scope.keys.BOTTOM:
  32892. pan(0, -scope.keyPanSpeed);
  32893. needsUpdate = true;
  32894. break;
  32895. case scope.keys.LEFT:
  32896. pan(scope.keyPanSpeed, 0);
  32897. needsUpdate = true;
  32898. break;
  32899. case scope.keys.RIGHT:
  32900. pan(-scope.keyPanSpeed, 0);
  32901. needsUpdate = true;
  32902. break;
  32903. }
  32904. if (needsUpdate) {
  32905. // prevent the browser from scrolling on cursor keys
  32906. event.preventDefault();
  32907. scope.update();
  32908. }
  32909. }
  32910. function handleTouchStartRotate(event) {
  32911. if (event.touches.length == 1) {
  32912. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  32913. } else {
  32914. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  32915. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  32916. rotateStart.set(x, y);
  32917. }
  32918. }
  32919. function handleTouchStartPan(event) {
  32920. if (event.touches.length == 1) {
  32921. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  32922. } else {
  32923. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  32924. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  32925. panStart.set(x, y);
  32926. }
  32927. }
  32928. function handleTouchStartDolly(event) {
  32929. var dx = event.touches[0].pageX - event.touches[1].pageX;
  32930. var dy = event.touches[0].pageY - event.touches[1].pageY;
  32931. var distance = Math.sqrt(dx * dx + dy * dy);
  32932. dollyStart.set(0, distance);
  32933. }
  32934. function handleTouchStartDollyPan(event) {
  32935. if (scope.enableZoom) handleTouchStartDolly(event);
  32936. if (scope.enablePan) handleTouchStartPan(event);
  32937. }
  32938. function handleTouchStartDollyRotate(event) {
  32939. if (scope.enableZoom) handleTouchStartDolly(event);
  32940. if (scope.enableRotate) handleTouchStartRotate(event);
  32941. }
  32942. function handleTouchMoveRotate(event) {
  32943. if (event.touches.length == 1) {
  32944. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  32945. } else {
  32946. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  32947. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  32948. rotateEnd.set(x, y);
  32949. }
  32950. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  32951. var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
  32952. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  32953. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  32954. rotateStart.copy(rotateEnd);
  32955. }
  32956. function handleTouchMovePan(event) {
  32957. if (event.touches.length == 1) {
  32958. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  32959. } else {
  32960. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  32961. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  32962. panEnd.set(x, y);
  32963. }
  32964. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  32965. pan(panDelta.x, panDelta.y);
  32966. panStart.copy(panEnd);
  32967. }
  32968. function handleTouchMoveDolly(event) {
  32969. var dx = event.touches[0].pageX - event.touches[1].pageX;
  32970. var dy = event.touches[0].pageY - event.touches[1].pageY;
  32971. var distance = Math.sqrt(dx * dx + dy * dy);
  32972. dollyEnd.set(0, distance);
  32973. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  32974. dollyIn(dollyDelta.y);
  32975. dollyStart.copy(dollyEnd);
  32976. }
  32977. function handleTouchMoveDollyPan(event) {
  32978. if (scope.enableZoom) handleTouchMoveDolly(event);
  32979. if (scope.enablePan) handleTouchMovePan(event);
  32980. }
  32981. function handleTouchMoveDollyRotate(event) {
  32982. if (scope.enableZoom) handleTouchMoveDolly(event);
  32983. if (scope.enableRotate) handleTouchMoveRotate(event);
  32984. }
  32985. function handleTouchEnd()
  32986. /*event*/
  32987. {} // no-op
  32988. //
  32989. // event handlers - FSM: listen for events and reset state
  32990. //
  32991. function onMouseDown(event) {
  32992. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  32993. event.preventDefault(); // Manually set the focus since calling preventDefault above
  32994. // prevents the browser from setting it automatically.
  32995. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  32996. switch (event.button) {
  32997. case 0:
  32998. switch (scope.mouseButtons.LEFT) {
  32999. case _threeModule.MOUSE.ROTATE:
  33000. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33001. if (scope.enablePan === false) return;
  33002. handleMouseDownPan(event);
  33003. state = STATE.PAN;
  33004. } else {
  33005. if (scope.enableRotate === false) return;
  33006. handleMouseDownRotate(event);
  33007. state = STATE.ROTATE;
  33008. }
  33009. break;
  33010. case _threeModule.MOUSE.PAN:
  33011. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  33012. if (scope.enableRotate === false) return;
  33013. handleMouseDownRotate(event);
  33014. state = STATE.ROTATE;
  33015. } else {
  33016. if (scope.enablePan === false) return;
  33017. handleMouseDownPan(event);
  33018. state = STATE.PAN;
  33019. }
  33020. break;
  33021. default:
  33022. state = STATE.NONE;
  33023. }
  33024. break;
  33025. case 1:
  33026. switch (scope.mouseButtons.MIDDLE) {
  33027. case _threeModule.MOUSE.DOLLY:
  33028. if (scope.enableZoom === false) return;
  33029. handleMouseDownDolly(event);
  33030. state = STATE.DOLLY;
  33031. break;
  33032. default:
  33033. state = STATE.NONE;
  33034. }
  33035. break;
  33036. case 2:
  33037. switch (scope.mouseButtons.RIGHT) {
  33038. case _threeModule.MOUSE.ROTATE:
  33039. if (scope.enableRotate === false) return;
  33040. handleMouseDownRotate(event);
  33041. state = STATE.ROTATE;
  33042. break;
  33043. case _threeModule.MOUSE.PAN:
  33044. if (scope.enablePan === false) return;
  33045. handleMouseDownPan(event);
  33046. state = STATE.PAN;
  33047. break;
  33048. default:
  33049. state = STATE.NONE;
  33050. }
  33051. break;
  33052. }
  33053. if (state !== STATE.NONE) {
  33054. document.addEventListener('mousemove', onMouseMove, false);
  33055. document.addEventListener('mouseup', onMouseUp, false);
  33056. scope.dispatchEvent(startEvent);
  33057. }
  33058. }
  33059. function onMouseMove(event) {
  33060. if (scope.enabled === false) return;
  33061. event.preventDefault();
  33062. switch (state) {
  33063. case STATE.ROTATE:
  33064. if (scope.enableRotate === false) return;
  33065. handleMouseMoveRotate(event);
  33066. break;
  33067. case STATE.DOLLY:
  33068. if (scope.enableZoom === false) return;
  33069. handleMouseMoveDolly(event);
  33070. break;
  33071. case STATE.PAN:
  33072. if (scope.enablePan === false) return;
  33073. handleMouseMovePan(event);
  33074. break;
  33075. }
  33076. }
  33077. function onMouseUp(event) {
  33078. if (scope.enabled === false) return;
  33079. handleMouseUp(event);
  33080. document.removeEventListener('mousemove', onMouseMove, false);
  33081. document.removeEventListener('mouseup', onMouseUp, false);
  33082. scope.dispatchEvent(endEvent);
  33083. state = STATE.NONE;
  33084. }
  33085. function onMouseWheel(event) {
  33086. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  33087. event.preventDefault();
  33088. event.stopPropagation();
  33089. scope.dispatchEvent(startEvent);
  33090. handleMouseWheel(event);
  33091. scope.dispatchEvent(endEvent);
  33092. }
  33093. function onKeyDown(event) {
  33094. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  33095. handleKeyDown(event);
  33096. }
  33097. function onTouchStart(event) {
  33098. if (scope.enabled === false) return;
  33099. event.preventDefault();
  33100. switch (event.touches.length) {
  33101. case 1:
  33102. switch (scope.touches.ONE) {
  33103. case _threeModule.TOUCH.ROTATE:
  33104. if (scope.enableRotate === false) return;
  33105. handleTouchStartRotate(event);
  33106. state = STATE.TOUCH_ROTATE;
  33107. break;
  33108. case _threeModule.TOUCH.PAN:
  33109. if (scope.enablePan === false) return;
  33110. handleTouchStartPan(event);
  33111. state = STATE.TOUCH_PAN;
  33112. break;
  33113. default:
  33114. state = STATE.NONE;
  33115. }
  33116. break;
  33117. case 2:
  33118. switch (scope.touches.TWO) {
  33119. case _threeModule.TOUCH.DOLLY_PAN:
  33120. if (scope.enableZoom === false && scope.enablePan === false) return;
  33121. handleTouchStartDollyPan(event);
  33122. state = STATE.TOUCH_DOLLY_PAN;
  33123. break;
  33124. case _threeModule.TOUCH.DOLLY_ROTATE:
  33125. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33126. handleTouchStartDollyRotate(event);
  33127. state = STATE.TOUCH_DOLLY_ROTATE;
  33128. break;
  33129. default:
  33130. state = STATE.NONE;
  33131. }
  33132. break;
  33133. default:
  33134. state = STATE.NONE;
  33135. }
  33136. if (state !== STATE.NONE) {
  33137. scope.dispatchEvent(startEvent);
  33138. }
  33139. }
  33140. function onTouchMove(event) {
  33141. if (scope.enabled === false) return;
  33142. event.preventDefault();
  33143. event.stopPropagation();
  33144. switch (state) {
  33145. case STATE.TOUCH_ROTATE:
  33146. if (scope.enableRotate === false) return;
  33147. handleTouchMoveRotate(event);
  33148. scope.update();
  33149. break;
  33150. case STATE.TOUCH_PAN:
  33151. if (scope.enablePan === false) return;
  33152. handleTouchMovePan(event);
  33153. scope.update();
  33154. break;
  33155. case STATE.TOUCH_DOLLY_PAN:
  33156. if (scope.enableZoom === false && scope.enablePan === false) return;
  33157. handleTouchMoveDollyPan(event);
  33158. scope.update();
  33159. break;
  33160. case STATE.TOUCH_DOLLY_ROTATE:
  33161. if (scope.enableZoom === false && scope.enableRotate === false) return;
  33162. handleTouchMoveDollyRotate(event);
  33163. scope.update();
  33164. break;
  33165. default:
  33166. state = STATE.NONE;
  33167. }
  33168. }
  33169. function onTouchEnd(event) {
  33170. if (scope.enabled === false) return;
  33171. handleTouchEnd(event);
  33172. scope.dispatchEvent(endEvent);
  33173. state = STATE.NONE;
  33174. }
  33175. function onContextMenu(event) {
  33176. if (scope.enabled === false) return;
  33177. event.preventDefault();
  33178. } //
  33179. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  33180. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  33181. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  33182. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  33183. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  33184. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  33185. window.addEventListener('keydown', onKeyDown, false); // force an update at start
  33186. this.update();
  33187. };
  33188. exports.OrbitControls = OrbitControls;
  33189. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33190. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  33191. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  33192. // This is very similar to OrbitControls, another set of touch behavior
  33193. //
  33194. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  33195. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  33196. // Pan - left mouse, or arrow keys / touch: one-finger move
  33197. var MapControls = function (object, domElement) {
  33198. OrbitControls.call(this, object, domElement);
  33199. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  33200. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  33201. this.touches.ONE = _threeModule.TOUCH.PAN;
  33202. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  33203. };
  33204. exports.MapControls = MapControls;
  33205. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  33206. MapControls.prototype.constructor = MapControls;
  33207. },{"../../../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) {
  33208. "use strict";
  33209. Object.defineProperty(exports, "__esModule", {
  33210. value: true
  33211. });
  33212. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  33213. /**
  33214. * dat-gui JavaScript Controller Library
  33215. * http://code.google.com/p/dat-gui
  33216. *
  33217. * Copyright 2011 Data Arts Team, Google Creative Lab
  33218. *
  33219. * Licensed under the Apache License, Version 2.0 (the "License");
  33220. * you may not use this file except in compliance with the License.
  33221. * You may obtain a copy of the License at
  33222. *
  33223. * http://www.apache.org/licenses/LICENSE-2.0
  33224. */
  33225. function ___$insertStyle(css) {
  33226. if (!css) {
  33227. return;
  33228. }
  33229. if (typeof window === 'undefined') {
  33230. return;
  33231. }
  33232. var style = document.createElement('style');
  33233. style.setAttribute('type', 'text/css');
  33234. style.innerHTML = css;
  33235. document.head.appendChild(style);
  33236. return css;
  33237. }
  33238. function colorToString(color, forceCSSHex) {
  33239. var colorFormat = color.__state.conversionName.toString();
  33240. var r = Math.round(color.r);
  33241. var g = Math.round(color.g);
  33242. var b = Math.round(color.b);
  33243. var a = color.a;
  33244. var h = Math.round(color.h);
  33245. var s = color.s.toFixed(1);
  33246. var v = color.v.toFixed(1);
  33247. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  33248. var str = color.hex.toString(16);
  33249. while (str.length < 6) {
  33250. str = '0' + str;
  33251. }
  33252. return '#' + str;
  33253. } else if (colorFormat === 'CSS_RGB') {
  33254. return 'rgb(' + r + ',' + g + ',' + b + ')';
  33255. } else if (colorFormat === 'CSS_RGBA') {
  33256. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  33257. } else if (colorFormat === 'HEX') {
  33258. return '0x' + color.hex.toString(16);
  33259. } else if (colorFormat === 'RGB_ARRAY') {
  33260. return '[' + r + ',' + g + ',' + b + ']';
  33261. } else if (colorFormat === 'RGBA_ARRAY') {
  33262. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  33263. } else if (colorFormat === 'RGB_OBJ') {
  33264. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  33265. } else if (colorFormat === 'RGBA_OBJ') {
  33266. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  33267. } else if (colorFormat === 'HSV_OBJ') {
  33268. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  33269. } else if (colorFormat === 'HSVA_OBJ') {
  33270. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  33271. }
  33272. return 'unknown format';
  33273. }
  33274. var ARR_EACH = Array.prototype.forEach;
  33275. var ARR_SLICE = Array.prototype.slice;
  33276. var Common = {
  33277. BREAK: {},
  33278. extend: function extend(target) {
  33279. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33280. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33281. keys.forEach(function (key) {
  33282. if (!this.isUndefined(obj[key])) {
  33283. target[key] = obj[key];
  33284. }
  33285. }.bind(this));
  33286. }, this);
  33287. return target;
  33288. },
  33289. defaults: function defaults(target) {
  33290. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  33291. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  33292. keys.forEach(function (key) {
  33293. if (this.isUndefined(target[key])) {
  33294. target[key] = obj[key];
  33295. }
  33296. }.bind(this));
  33297. }, this);
  33298. return target;
  33299. },
  33300. compose: function compose() {
  33301. var toCall = ARR_SLICE.call(arguments);
  33302. return function () {
  33303. var args = ARR_SLICE.call(arguments);
  33304. for (var i = toCall.length - 1; i >= 0; i--) {
  33305. args = [toCall[i].apply(this, args)];
  33306. }
  33307. return args[0];
  33308. };
  33309. },
  33310. each: function each(obj, itr, scope) {
  33311. if (!obj) {
  33312. return;
  33313. }
  33314. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  33315. obj.forEach(itr, scope);
  33316. } else if (obj.length === obj.length + 0) {
  33317. var key = void 0;
  33318. var l = void 0;
  33319. for (key = 0, l = obj.length; key < l; key++) {
  33320. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  33321. return;
  33322. }
  33323. }
  33324. } else {
  33325. for (var _key in obj) {
  33326. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  33327. return;
  33328. }
  33329. }
  33330. }
  33331. },
  33332. defer: function defer(fnc) {
  33333. setTimeout(fnc, 0);
  33334. },
  33335. debounce: function debounce(func, threshold, callImmediately) {
  33336. var timeout = void 0;
  33337. return function () {
  33338. var obj = this;
  33339. var args = arguments;
  33340. function delayed() {
  33341. timeout = null;
  33342. if (!callImmediately) func.apply(obj, args);
  33343. }
  33344. var callNow = callImmediately || !timeout;
  33345. clearTimeout(timeout);
  33346. timeout = setTimeout(delayed, threshold);
  33347. if (callNow) {
  33348. func.apply(obj, args);
  33349. }
  33350. };
  33351. },
  33352. toArray: function toArray(obj) {
  33353. if (obj.toArray) return obj.toArray();
  33354. return ARR_SLICE.call(obj);
  33355. },
  33356. isUndefined: function isUndefined(obj) {
  33357. return obj === undefined;
  33358. },
  33359. isNull: function isNull(obj) {
  33360. return obj === null;
  33361. },
  33362. isNaN: function (_isNaN) {
  33363. function isNaN() {
  33364. return _isNaN.apply(this, arguments);
  33365. }
  33366. isNaN.toString = function () {
  33367. return _isNaN.toString();
  33368. };
  33369. return isNaN;
  33370. }(function (obj) {
  33371. return isNaN(obj);
  33372. }),
  33373. isArray: Array.isArray || function (obj) {
  33374. return obj.constructor === Array;
  33375. },
  33376. isObject: function isObject(obj) {
  33377. return obj === Object(obj);
  33378. },
  33379. isNumber: function isNumber(obj) {
  33380. return obj === obj + 0;
  33381. },
  33382. isString: function isString(obj) {
  33383. return obj === obj + '';
  33384. },
  33385. isBoolean: function isBoolean(obj) {
  33386. return obj === false || obj === true;
  33387. },
  33388. isFunction: function isFunction(obj) {
  33389. return Object.prototype.toString.call(obj) === '[object Function]';
  33390. }
  33391. };
  33392. var INTERPRETATIONS = [{
  33393. litmus: Common.isString,
  33394. conversions: {
  33395. THREE_CHAR_HEX: {
  33396. read: function read(original) {
  33397. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  33398. if (test === null) {
  33399. return false;
  33400. }
  33401. return {
  33402. space: 'HEX',
  33403. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  33404. };
  33405. },
  33406. write: colorToString
  33407. },
  33408. SIX_CHAR_HEX: {
  33409. read: function read(original) {
  33410. var test = original.match(/^#([A-F0-9]{6})$/i);
  33411. if (test === null) {
  33412. return false;
  33413. }
  33414. return {
  33415. space: 'HEX',
  33416. hex: parseInt('0x' + test[1].toString(), 0)
  33417. };
  33418. },
  33419. write: colorToString
  33420. },
  33421. CSS_RGB: {
  33422. read: function read(original) {
  33423. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33424. if (test === null) {
  33425. return false;
  33426. }
  33427. return {
  33428. space: 'RGB',
  33429. r: parseFloat(test[1]),
  33430. g: parseFloat(test[2]),
  33431. b: parseFloat(test[3])
  33432. };
  33433. },
  33434. write: colorToString
  33435. },
  33436. CSS_RGBA: {
  33437. read: function read(original) {
  33438. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  33439. if (test === null) {
  33440. return false;
  33441. }
  33442. return {
  33443. space: 'RGB',
  33444. r: parseFloat(test[1]),
  33445. g: parseFloat(test[2]),
  33446. b: parseFloat(test[3]),
  33447. a: parseFloat(test[4])
  33448. };
  33449. },
  33450. write: colorToString
  33451. }
  33452. }
  33453. }, {
  33454. litmus: Common.isNumber,
  33455. conversions: {
  33456. HEX: {
  33457. read: function read(original) {
  33458. return {
  33459. space: 'HEX',
  33460. hex: original,
  33461. conversionName: 'HEX'
  33462. };
  33463. },
  33464. write: function write(color) {
  33465. return color.hex;
  33466. }
  33467. }
  33468. }
  33469. }, {
  33470. litmus: Common.isArray,
  33471. conversions: {
  33472. RGB_ARRAY: {
  33473. read: function read(original) {
  33474. if (original.length !== 3) {
  33475. return false;
  33476. }
  33477. return {
  33478. space: 'RGB',
  33479. r: original[0],
  33480. g: original[1],
  33481. b: original[2]
  33482. };
  33483. },
  33484. write: function write(color) {
  33485. return [color.r, color.g, color.b];
  33486. }
  33487. },
  33488. RGBA_ARRAY: {
  33489. read: function read(original) {
  33490. if (original.length !== 4) return false;
  33491. return {
  33492. space: 'RGB',
  33493. r: original[0],
  33494. g: original[1],
  33495. b: original[2],
  33496. a: original[3]
  33497. };
  33498. },
  33499. write: function write(color) {
  33500. return [color.r, color.g, color.b, color.a];
  33501. }
  33502. }
  33503. }
  33504. }, {
  33505. litmus: Common.isObject,
  33506. conversions: {
  33507. RGBA_OBJ: {
  33508. read: function read(original) {
  33509. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  33510. return {
  33511. space: 'RGB',
  33512. r: original.r,
  33513. g: original.g,
  33514. b: original.b,
  33515. a: original.a
  33516. };
  33517. }
  33518. return false;
  33519. },
  33520. write: function write(color) {
  33521. return {
  33522. r: color.r,
  33523. g: color.g,
  33524. b: color.b,
  33525. a: color.a
  33526. };
  33527. }
  33528. },
  33529. RGB_OBJ: {
  33530. read: function read(original) {
  33531. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  33532. return {
  33533. space: 'RGB',
  33534. r: original.r,
  33535. g: original.g,
  33536. b: original.b
  33537. };
  33538. }
  33539. return false;
  33540. },
  33541. write: function write(color) {
  33542. return {
  33543. r: color.r,
  33544. g: color.g,
  33545. b: color.b
  33546. };
  33547. }
  33548. },
  33549. HSVA_OBJ: {
  33550. read: function read(original) {
  33551. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  33552. return {
  33553. space: 'HSV',
  33554. h: original.h,
  33555. s: original.s,
  33556. v: original.v,
  33557. a: original.a
  33558. };
  33559. }
  33560. return false;
  33561. },
  33562. write: function write(color) {
  33563. return {
  33564. h: color.h,
  33565. s: color.s,
  33566. v: color.v,
  33567. a: color.a
  33568. };
  33569. }
  33570. },
  33571. HSV_OBJ: {
  33572. read: function read(original) {
  33573. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  33574. return {
  33575. space: 'HSV',
  33576. h: original.h,
  33577. s: original.s,
  33578. v: original.v
  33579. };
  33580. }
  33581. return false;
  33582. },
  33583. write: function write(color) {
  33584. return {
  33585. h: color.h,
  33586. s: color.s,
  33587. v: color.v
  33588. };
  33589. }
  33590. }
  33591. }
  33592. }];
  33593. var result = void 0;
  33594. var toReturn = void 0;
  33595. var interpret = function interpret() {
  33596. toReturn = false;
  33597. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  33598. Common.each(INTERPRETATIONS, function (family) {
  33599. if (family.litmus(original)) {
  33600. Common.each(family.conversions, function (conversion, conversionName) {
  33601. result = conversion.read(original);
  33602. if (toReturn === false && result !== false) {
  33603. toReturn = result;
  33604. result.conversionName = conversionName;
  33605. result.conversion = conversion;
  33606. return Common.BREAK;
  33607. }
  33608. });
  33609. return Common.BREAK;
  33610. }
  33611. });
  33612. return toReturn;
  33613. };
  33614. var tmpComponent = void 0;
  33615. var ColorMath = {
  33616. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  33617. var hi = Math.floor(h / 60) % 6;
  33618. var f = h / 60 - Math.floor(h / 60);
  33619. var p = v * (1.0 - s);
  33620. var q = v * (1.0 - f * s);
  33621. var t = v * (1.0 - (1.0 - f) * s);
  33622. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  33623. return {
  33624. r: c[0] * 255,
  33625. g: c[1] * 255,
  33626. b: c[2] * 255
  33627. };
  33628. },
  33629. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  33630. var min = Math.min(r, g, b);
  33631. var max = Math.max(r, g, b);
  33632. var delta = max - min;
  33633. var h = void 0;
  33634. var s = void 0;
  33635. if (max !== 0) {
  33636. s = delta / max;
  33637. } else {
  33638. return {
  33639. h: NaN,
  33640. s: 0,
  33641. v: 0
  33642. };
  33643. }
  33644. if (r === max) {
  33645. h = (g - b) / delta;
  33646. } else if (g === max) {
  33647. h = 2 + (b - r) / delta;
  33648. } else {
  33649. h = 4 + (r - g) / delta;
  33650. }
  33651. h /= 6;
  33652. if (h < 0) {
  33653. h += 1;
  33654. }
  33655. return {
  33656. h: h * 360,
  33657. s: s,
  33658. v: max / 255
  33659. };
  33660. },
  33661. rgb_to_hex: function rgb_to_hex(r, g, b) {
  33662. var hex = this.hex_with_component(0, 2, r);
  33663. hex = this.hex_with_component(hex, 1, g);
  33664. hex = this.hex_with_component(hex, 0, b);
  33665. return hex;
  33666. },
  33667. component_from_hex: function component_from_hex(hex, componentIndex) {
  33668. return hex >> componentIndex * 8 & 0xFF;
  33669. },
  33670. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  33671. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  33672. }
  33673. };
  33674. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  33675. return typeof obj;
  33676. } : function (obj) {
  33677. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  33678. };
  33679. var classCallCheck = function (instance, Constructor) {
  33680. if (!(instance instanceof Constructor)) {
  33681. throw new TypeError("Cannot call a class as a function");
  33682. }
  33683. };
  33684. var createClass = function () {
  33685. function defineProperties(target, props) {
  33686. for (var i = 0; i < props.length; i++) {
  33687. var descriptor = props[i];
  33688. descriptor.enumerable = descriptor.enumerable || false;
  33689. descriptor.configurable = true;
  33690. if ("value" in descriptor) descriptor.writable = true;
  33691. Object.defineProperty(target, descriptor.key, descriptor);
  33692. }
  33693. }
  33694. return function (Constructor, protoProps, staticProps) {
  33695. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  33696. if (staticProps) defineProperties(Constructor, staticProps);
  33697. return Constructor;
  33698. };
  33699. }();
  33700. var get = function get(object, property, receiver) {
  33701. if (object === null) object = Function.prototype;
  33702. var desc = Object.getOwnPropertyDescriptor(object, property);
  33703. if (desc === undefined) {
  33704. var parent = Object.getPrototypeOf(object);
  33705. if (parent === null) {
  33706. return undefined;
  33707. } else {
  33708. return get(parent, property, receiver);
  33709. }
  33710. } else if ("value" in desc) {
  33711. return desc.value;
  33712. } else {
  33713. var getter = desc.get;
  33714. if (getter === undefined) {
  33715. return undefined;
  33716. }
  33717. return getter.call(receiver);
  33718. }
  33719. };
  33720. var inherits = function (subClass, superClass) {
  33721. if (typeof superClass !== "function" && superClass !== null) {
  33722. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  33723. }
  33724. subClass.prototype = Object.create(superClass && superClass.prototype, {
  33725. constructor: {
  33726. value: subClass,
  33727. enumerable: false,
  33728. writable: true,
  33729. configurable: true
  33730. }
  33731. });
  33732. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  33733. };
  33734. var possibleConstructorReturn = function (self, call) {
  33735. if (!self) {
  33736. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  33737. }
  33738. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  33739. };
  33740. var Color = function () {
  33741. function Color() {
  33742. classCallCheck(this, Color);
  33743. this.__state = interpret.apply(this, arguments);
  33744. if (this.__state === false) {
  33745. throw new Error('Failed to interpret color arguments');
  33746. }
  33747. this.__state.a = this.__state.a || 1;
  33748. }
  33749. createClass(Color, [{
  33750. key: 'toString',
  33751. value: function toString() {
  33752. return colorToString(this);
  33753. }
  33754. }, {
  33755. key: 'toHexString',
  33756. value: function toHexString() {
  33757. return colorToString(this, true);
  33758. }
  33759. }, {
  33760. key: 'toOriginal',
  33761. value: function toOriginal() {
  33762. return this.__state.conversion.write(this);
  33763. }
  33764. }]);
  33765. return Color;
  33766. }();
  33767. function defineRGBComponent(target, component, componentHexIndex) {
  33768. Object.defineProperty(target, component, {
  33769. get: function get$$1() {
  33770. if (this.__state.space === 'RGB') {
  33771. return this.__state[component];
  33772. }
  33773. Color.recalculateRGB(this, component, componentHexIndex);
  33774. return this.__state[component];
  33775. },
  33776. set: function set$$1(v) {
  33777. if (this.__state.space !== 'RGB') {
  33778. Color.recalculateRGB(this, component, componentHexIndex);
  33779. this.__state.space = 'RGB';
  33780. }
  33781. this.__state[component] = v;
  33782. }
  33783. });
  33784. }
  33785. function defineHSVComponent(target, component) {
  33786. Object.defineProperty(target, component, {
  33787. get: function get$$1() {
  33788. if (this.__state.space === 'HSV') {
  33789. return this.__state[component];
  33790. }
  33791. Color.recalculateHSV(this);
  33792. return this.__state[component];
  33793. },
  33794. set: function set$$1(v) {
  33795. if (this.__state.space !== 'HSV') {
  33796. Color.recalculateHSV(this);
  33797. this.__state.space = 'HSV';
  33798. }
  33799. this.__state[component] = v;
  33800. }
  33801. });
  33802. }
  33803. Color.recalculateRGB = function (color, component, componentHexIndex) {
  33804. if (color.__state.space === 'HEX') {
  33805. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  33806. } else if (color.__state.space === 'HSV') {
  33807. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  33808. } else {
  33809. throw new Error('Corrupted color state');
  33810. }
  33811. };
  33812. Color.recalculateHSV = function (color) {
  33813. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  33814. Common.extend(color.__state, {
  33815. s: result.s,
  33816. v: result.v
  33817. });
  33818. if (!Common.isNaN(result.h)) {
  33819. color.__state.h = result.h;
  33820. } else if (Common.isUndefined(color.__state.h)) {
  33821. color.__state.h = 0;
  33822. }
  33823. };
  33824. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  33825. defineRGBComponent(Color.prototype, 'r', 2);
  33826. defineRGBComponent(Color.prototype, 'g', 1);
  33827. defineRGBComponent(Color.prototype, 'b', 0);
  33828. defineHSVComponent(Color.prototype, 'h');
  33829. defineHSVComponent(Color.prototype, 's');
  33830. defineHSVComponent(Color.prototype, 'v');
  33831. Object.defineProperty(Color.prototype, 'a', {
  33832. get: function get$$1() {
  33833. return this.__state.a;
  33834. },
  33835. set: function set$$1(v) {
  33836. this.__state.a = v;
  33837. }
  33838. });
  33839. Object.defineProperty(Color.prototype, 'hex', {
  33840. get: function get$$1() {
  33841. if (!this.__state.space !== 'HEX') {
  33842. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  33843. }
  33844. return this.__state.hex;
  33845. },
  33846. set: function set$$1(v) {
  33847. this.__state.space = 'HEX';
  33848. this.__state.hex = v;
  33849. }
  33850. });
  33851. var Controller = function () {
  33852. function Controller(object, property) {
  33853. classCallCheck(this, Controller);
  33854. this.initialValue = object[property];
  33855. this.domElement = document.createElement('div');
  33856. this.object = object;
  33857. this.property = property;
  33858. this.__onChange = undefined;
  33859. this.__onFinishChange = undefined;
  33860. }
  33861. createClass(Controller, [{
  33862. key: 'onChange',
  33863. value: function onChange(fnc) {
  33864. this.__onChange = fnc;
  33865. return this;
  33866. }
  33867. }, {
  33868. key: 'onFinishChange',
  33869. value: function onFinishChange(fnc) {
  33870. this.__onFinishChange = fnc;
  33871. return this;
  33872. }
  33873. }, {
  33874. key: 'setValue',
  33875. value: function setValue(newValue) {
  33876. this.object[this.property] = newValue;
  33877. if (this.__onChange) {
  33878. this.__onChange.call(this, newValue);
  33879. }
  33880. this.updateDisplay();
  33881. return this;
  33882. }
  33883. }, {
  33884. key: 'getValue',
  33885. value: function getValue() {
  33886. return this.object[this.property];
  33887. }
  33888. }, {
  33889. key: 'updateDisplay',
  33890. value: function updateDisplay() {
  33891. return this;
  33892. }
  33893. }, {
  33894. key: 'isModified',
  33895. value: function isModified() {
  33896. return this.initialValue !== this.getValue();
  33897. }
  33898. }]);
  33899. return Controller;
  33900. }();
  33901. var EVENT_MAP = {
  33902. HTMLEvents: ['change'],
  33903. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  33904. KeyboardEvents: ['keydown']
  33905. };
  33906. var EVENT_MAP_INV = {};
  33907. Common.each(EVENT_MAP, function (v, k) {
  33908. Common.each(v, function (e) {
  33909. EVENT_MAP_INV[e] = k;
  33910. });
  33911. });
  33912. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  33913. function cssValueToPixels(val) {
  33914. if (val === '0' || Common.isUndefined(val)) {
  33915. return 0;
  33916. }
  33917. var match = val.match(CSS_VALUE_PIXELS);
  33918. if (!Common.isNull(match)) {
  33919. return parseFloat(match[1]);
  33920. }
  33921. return 0;
  33922. }
  33923. var dom = {
  33924. makeSelectable: function makeSelectable(elem, selectable) {
  33925. if (elem === undefined || elem.style === undefined) return;
  33926. elem.onselectstart = selectable ? function () {
  33927. return false;
  33928. } : function () {};
  33929. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  33930. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  33931. elem.unselectable = selectable ? 'on' : 'off';
  33932. },
  33933. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  33934. var vertical = vert;
  33935. var horizontal = hor;
  33936. if (Common.isUndefined(horizontal)) {
  33937. horizontal = true;
  33938. }
  33939. if (Common.isUndefined(vertical)) {
  33940. vertical = true;
  33941. }
  33942. elem.style.position = 'absolute';
  33943. if (horizontal) {
  33944. elem.style.left = 0;
  33945. elem.style.right = 0;
  33946. }
  33947. if (vertical) {
  33948. elem.style.top = 0;
  33949. elem.style.bottom = 0;
  33950. }
  33951. },
  33952. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  33953. var params = pars || {};
  33954. var className = EVENT_MAP_INV[eventType];
  33955. if (!className) {
  33956. throw new Error('Event type ' + eventType + ' not supported.');
  33957. }
  33958. var evt = document.createEvent(className);
  33959. switch (className) {
  33960. case 'MouseEvents':
  33961. {
  33962. var clientX = params.x || params.clientX || 0;
  33963. var clientY = params.y || params.clientY || 0;
  33964. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  33965. break;
  33966. }
  33967. case 'KeyboardEvents':
  33968. {
  33969. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  33970. Common.defaults(params, {
  33971. cancelable: true,
  33972. ctrlKey: false,
  33973. altKey: false,
  33974. shiftKey: false,
  33975. metaKey: false,
  33976. keyCode: undefined,
  33977. charCode: undefined
  33978. });
  33979. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  33980. break;
  33981. }
  33982. default:
  33983. {
  33984. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  33985. break;
  33986. }
  33987. }
  33988. Common.defaults(evt, aux);
  33989. elem.dispatchEvent(evt);
  33990. },
  33991. bind: function bind(elem, event, func, newBool) {
  33992. var bool = newBool || false;
  33993. if (elem.addEventListener) {
  33994. elem.addEventListener(event, func, bool);
  33995. } else if (elem.attachEvent) {
  33996. elem.attachEvent('on' + event, func);
  33997. }
  33998. return dom;
  33999. },
  34000. unbind: function unbind(elem, event, func, newBool) {
  34001. var bool = newBool || false;
  34002. if (elem.removeEventListener) {
  34003. elem.removeEventListener(event, func, bool);
  34004. } else if (elem.detachEvent) {
  34005. elem.detachEvent('on' + event, func);
  34006. }
  34007. return dom;
  34008. },
  34009. addClass: function addClass(elem, className) {
  34010. if (elem.className === undefined) {
  34011. elem.className = className;
  34012. } else if (elem.className !== className) {
  34013. var classes = elem.className.split(/ +/);
  34014. if (classes.indexOf(className) === -1) {
  34015. classes.push(className);
  34016. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  34017. }
  34018. }
  34019. return dom;
  34020. },
  34021. removeClass: function removeClass(elem, className) {
  34022. if (className) {
  34023. if (elem.className === className) {
  34024. elem.removeAttribute('class');
  34025. } else {
  34026. var classes = elem.className.split(/ +/);
  34027. var index = classes.indexOf(className);
  34028. if (index !== -1) {
  34029. classes.splice(index, 1);
  34030. elem.className = classes.join(' ');
  34031. }
  34032. }
  34033. } else {
  34034. elem.className = undefined;
  34035. }
  34036. return dom;
  34037. },
  34038. hasClass: function hasClass(elem, className) {
  34039. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  34040. },
  34041. getWidth: function getWidth(elem) {
  34042. var style = getComputedStyle(elem);
  34043. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  34044. },
  34045. getHeight: function getHeight(elem) {
  34046. var style = getComputedStyle(elem);
  34047. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  34048. },
  34049. getOffset: function getOffset(el) {
  34050. var elem = el;
  34051. var offset = {
  34052. left: 0,
  34053. top: 0
  34054. };
  34055. if (elem.offsetParent) {
  34056. do {
  34057. offset.left += elem.offsetLeft;
  34058. offset.top += elem.offsetTop;
  34059. elem = elem.offsetParent;
  34060. } while (elem);
  34061. }
  34062. return offset;
  34063. },
  34064. isActive: function isActive(elem) {
  34065. return elem === document.activeElement && (elem.type || elem.href);
  34066. }
  34067. };
  34068. var BooleanController = function (_Controller) {
  34069. inherits(BooleanController, _Controller);
  34070. function BooleanController(object, property) {
  34071. classCallCheck(this, BooleanController);
  34072. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  34073. var _this = _this2;
  34074. _this2.__prev = _this2.getValue();
  34075. _this2.__checkbox = document.createElement('input');
  34076. _this2.__checkbox.setAttribute('type', 'checkbox');
  34077. function onChange() {
  34078. _this.setValue(!_this.__prev);
  34079. }
  34080. dom.bind(_this2.__checkbox, 'change', onChange, false);
  34081. _this2.domElement.appendChild(_this2.__checkbox);
  34082. _this2.updateDisplay();
  34083. return _this2;
  34084. }
  34085. createClass(BooleanController, [{
  34086. key: 'setValue',
  34087. value: function setValue(v) {
  34088. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  34089. if (this.__onFinishChange) {
  34090. this.__onFinishChange.call(this, this.getValue());
  34091. }
  34092. this.__prev = this.getValue();
  34093. return toReturn;
  34094. }
  34095. }, {
  34096. key: 'updateDisplay',
  34097. value: function updateDisplay() {
  34098. if (this.getValue() === true) {
  34099. this.__checkbox.setAttribute('checked', 'checked');
  34100. this.__checkbox.checked = true;
  34101. this.__prev = true;
  34102. } else {
  34103. this.__checkbox.checked = false;
  34104. this.__prev = false;
  34105. }
  34106. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  34107. }
  34108. }]);
  34109. return BooleanController;
  34110. }(Controller);
  34111. var OptionController = function (_Controller) {
  34112. inherits(OptionController, _Controller);
  34113. function OptionController(object, property, opts) {
  34114. classCallCheck(this, OptionController);
  34115. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  34116. var options = opts;
  34117. var _this = _this2;
  34118. _this2.__select = document.createElement('select');
  34119. if (Common.isArray(options)) {
  34120. var map = {};
  34121. Common.each(options, function (element) {
  34122. map[element] = element;
  34123. });
  34124. options = map;
  34125. }
  34126. Common.each(options, function (value, key) {
  34127. var opt = document.createElement('option');
  34128. opt.innerHTML = key;
  34129. opt.setAttribute('value', value);
  34130. _this.__select.appendChild(opt);
  34131. });
  34132. _this2.updateDisplay();
  34133. dom.bind(_this2.__select, 'change', function () {
  34134. var desiredValue = this.options[this.selectedIndex].value;
  34135. _this.setValue(desiredValue);
  34136. });
  34137. _this2.domElement.appendChild(_this2.__select);
  34138. return _this2;
  34139. }
  34140. createClass(OptionController, [{
  34141. key: 'setValue',
  34142. value: function setValue(v) {
  34143. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  34144. if (this.__onFinishChange) {
  34145. this.__onFinishChange.call(this, this.getValue());
  34146. }
  34147. return toReturn;
  34148. }
  34149. }, {
  34150. key: 'updateDisplay',
  34151. value: function updateDisplay() {
  34152. if (dom.isActive(this.__select)) return this;
  34153. this.__select.value = this.getValue();
  34154. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  34155. }
  34156. }]);
  34157. return OptionController;
  34158. }(Controller);
  34159. var StringController = function (_Controller) {
  34160. inherits(StringController, _Controller);
  34161. function StringController(object, property) {
  34162. classCallCheck(this, StringController);
  34163. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  34164. var _this = _this2;
  34165. function onChange() {
  34166. _this.setValue(_this.__input.value);
  34167. }
  34168. function onBlur() {
  34169. if (_this.__onFinishChange) {
  34170. _this.__onFinishChange.call(_this, _this.getValue());
  34171. }
  34172. }
  34173. _this2.__input = document.createElement('input');
  34174. _this2.__input.setAttribute('type', 'text');
  34175. dom.bind(_this2.__input, 'keyup', onChange);
  34176. dom.bind(_this2.__input, 'change', onChange);
  34177. dom.bind(_this2.__input, 'blur', onBlur);
  34178. dom.bind(_this2.__input, 'keydown', function (e) {
  34179. if (e.keyCode === 13) {
  34180. this.blur();
  34181. }
  34182. });
  34183. _this2.updateDisplay();
  34184. _this2.domElement.appendChild(_this2.__input);
  34185. return _this2;
  34186. }
  34187. createClass(StringController, [{
  34188. key: 'updateDisplay',
  34189. value: function updateDisplay() {
  34190. if (!dom.isActive(this.__input)) {
  34191. this.__input.value = this.getValue();
  34192. }
  34193. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  34194. }
  34195. }]);
  34196. return StringController;
  34197. }(Controller);
  34198. function numDecimals(x) {
  34199. var _x = x.toString();
  34200. if (_x.indexOf('.') > -1) {
  34201. return _x.length - _x.indexOf('.') - 1;
  34202. }
  34203. return 0;
  34204. }
  34205. var NumberController = function (_Controller) {
  34206. inherits(NumberController, _Controller);
  34207. function NumberController(object, property, params) {
  34208. classCallCheck(this, NumberController);
  34209. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  34210. var _params = params || {};
  34211. _this.__min = _params.min;
  34212. _this.__max = _params.max;
  34213. _this.__step = _params.step;
  34214. if (Common.isUndefined(_this.__step)) {
  34215. if (_this.initialValue === 0) {
  34216. _this.__impliedStep = 1;
  34217. } else {
  34218. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  34219. }
  34220. } else {
  34221. _this.__impliedStep = _this.__step;
  34222. }
  34223. _this.__precision = numDecimals(_this.__impliedStep);
  34224. return _this;
  34225. }
  34226. createClass(NumberController, [{
  34227. key: 'setValue',
  34228. value: function setValue(v) {
  34229. var _v = v;
  34230. if (this.__min !== undefined && _v < this.__min) {
  34231. _v = this.__min;
  34232. } else if (this.__max !== undefined && _v > this.__max) {
  34233. _v = this.__max;
  34234. }
  34235. if (this.__step !== undefined && _v % this.__step !== 0) {
  34236. _v = Math.round(_v / this.__step) * this.__step;
  34237. }
  34238. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  34239. }
  34240. }, {
  34241. key: 'min',
  34242. value: function min(minValue) {
  34243. this.__min = minValue;
  34244. return this;
  34245. }
  34246. }, {
  34247. key: 'max',
  34248. value: function max(maxValue) {
  34249. this.__max = maxValue;
  34250. return this;
  34251. }
  34252. }, {
  34253. key: 'step',
  34254. value: function step(stepValue) {
  34255. this.__step = stepValue;
  34256. this.__impliedStep = stepValue;
  34257. this.__precision = numDecimals(stepValue);
  34258. return this;
  34259. }
  34260. }]);
  34261. return NumberController;
  34262. }(Controller);
  34263. function roundToDecimal(value, decimals) {
  34264. var tenTo = Math.pow(10, decimals);
  34265. return Math.round(value * tenTo) / tenTo;
  34266. }
  34267. var NumberControllerBox = function (_NumberController) {
  34268. inherits(NumberControllerBox, _NumberController);
  34269. function NumberControllerBox(object, property, params) {
  34270. classCallCheck(this, NumberControllerBox);
  34271. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  34272. _this2.__truncationSuspended = false;
  34273. var _this = _this2;
  34274. var prevY = void 0;
  34275. function onChange() {
  34276. var attempted = parseFloat(_this.__input.value);
  34277. if (!Common.isNaN(attempted)) {
  34278. _this.setValue(attempted);
  34279. }
  34280. }
  34281. function onFinish() {
  34282. if (_this.__onFinishChange) {
  34283. _this.__onFinishChange.call(_this, _this.getValue());
  34284. }
  34285. }
  34286. function onBlur() {
  34287. onFinish();
  34288. }
  34289. function onMouseDrag(e) {
  34290. var diff = prevY - e.clientY;
  34291. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  34292. prevY = e.clientY;
  34293. }
  34294. function onMouseUp() {
  34295. dom.unbind(window, 'mousemove', onMouseDrag);
  34296. dom.unbind(window, 'mouseup', onMouseUp);
  34297. onFinish();
  34298. }
  34299. function onMouseDown(e) {
  34300. dom.bind(window, 'mousemove', onMouseDrag);
  34301. dom.bind(window, 'mouseup', onMouseUp);
  34302. prevY = e.clientY;
  34303. }
  34304. _this2.__input = document.createElement('input');
  34305. _this2.__input.setAttribute('type', 'text');
  34306. dom.bind(_this2.__input, 'change', onChange);
  34307. dom.bind(_this2.__input, 'blur', onBlur);
  34308. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  34309. dom.bind(_this2.__input, 'keydown', function (e) {
  34310. if (e.keyCode === 13) {
  34311. _this.__truncationSuspended = true;
  34312. this.blur();
  34313. _this.__truncationSuspended = false;
  34314. onFinish();
  34315. }
  34316. });
  34317. _this2.updateDisplay();
  34318. _this2.domElement.appendChild(_this2.__input);
  34319. return _this2;
  34320. }
  34321. createClass(NumberControllerBox, [{
  34322. key: 'updateDisplay',
  34323. value: function updateDisplay() {
  34324. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  34325. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  34326. }
  34327. }]);
  34328. return NumberControllerBox;
  34329. }(NumberController);
  34330. function map(v, i1, i2, o1, o2) {
  34331. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  34332. }
  34333. var NumberControllerSlider = function (_NumberController) {
  34334. inherits(NumberControllerSlider, _NumberController);
  34335. function NumberControllerSlider(object, property, min, max, step) {
  34336. classCallCheck(this, NumberControllerSlider);
  34337. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  34338. min: min,
  34339. max: max,
  34340. step: step
  34341. }));
  34342. var _this = _this2;
  34343. _this2.__background = document.createElement('div');
  34344. _this2.__foreground = document.createElement('div');
  34345. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  34346. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  34347. dom.addClass(_this2.__background, 'slider');
  34348. dom.addClass(_this2.__foreground, 'slider-fg');
  34349. function onMouseDown(e) {
  34350. document.activeElement.blur();
  34351. dom.bind(window, 'mousemove', onMouseDrag);
  34352. dom.bind(window, 'mouseup', onMouseUp);
  34353. onMouseDrag(e);
  34354. }
  34355. function onMouseDrag(e) {
  34356. e.preventDefault();
  34357. var bgRect = _this.__background.getBoundingClientRect();
  34358. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34359. return false;
  34360. }
  34361. function onMouseUp() {
  34362. dom.unbind(window, 'mousemove', onMouseDrag);
  34363. dom.unbind(window, 'mouseup', onMouseUp);
  34364. if (_this.__onFinishChange) {
  34365. _this.__onFinishChange.call(_this, _this.getValue());
  34366. }
  34367. }
  34368. function onTouchStart(e) {
  34369. if (e.touches.length !== 1) {
  34370. return;
  34371. }
  34372. dom.bind(window, 'touchmove', onTouchMove);
  34373. dom.bind(window, 'touchend', onTouchEnd);
  34374. onTouchMove(e);
  34375. }
  34376. function onTouchMove(e) {
  34377. var clientX = e.touches[0].clientX;
  34378. var bgRect = _this.__background.getBoundingClientRect();
  34379. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  34380. }
  34381. function onTouchEnd() {
  34382. dom.unbind(window, 'touchmove', onTouchMove);
  34383. dom.unbind(window, 'touchend', onTouchEnd);
  34384. if (_this.__onFinishChange) {
  34385. _this.__onFinishChange.call(_this, _this.getValue());
  34386. }
  34387. }
  34388. _this2.updateDisplay();
  34389. _this2.__background.appendChild(_this2.__foreground);
  34390. _this2.domElement.appendChild(_this2.__background);
  34391. return _this2;
  34392. }
  34393. createClass(NumberControllerSlider, [{
  34394. key: 'updateDisplay',
  34395. value: function updateDisplay() {
  34396. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  34397. this.__foreground.style.width = pct * 100 + '%';
  34398. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  34399. }
  34400. }]);
  34401. return NumberControllerSlider;
  34402. }(NumberController);
  34403. var FunctionController = function (_Controller) {
  34404. inherits(FunctionController, _Controller);
  34405. function FunctionController(object, property, text) {
  34406. classCallCheck(this, FunctionController);
  34407. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  34408. var _this = _this2;
  34409. _this2.__button = document.createElement('div');
  34410. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  34411. dom.bind(_this2.__button, 'click', function (e) {
  34412. e.preventDefault();
  34413. _this.fire();
  34414. return false;
  34415. });
  34416. dom.addClass(_this2.__button, 'button');
  34417. _this2.domElement.appendChild(_this2.__button);
  34418. return _this2;
  34419. }
  34420. createClass(FunctionController, [{
  34421. key: 'fire',
  34422. value: function fire() {
  34423. if (this.__onChange) {
  34424. this.__onChange.call(this);
  34425. }
  34426. this.getValue().call(this.object);
  34427. if (this.__onFinishChange) {
  34428. this.__onFinishChange.call(this, this.getValue());
  34429. }
  34430. }
  34431. }]);
  34432. return FunctionController;
  34433. }(Controller);
  34434. var ColorController = function (_Controller) {
  34435. inherits(ColorController, _Controller);
  34436. function ColorController(object, property) {
  34437. classCallCheck(this, ColorController);
  34438. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  34439. _this2.__color = new Color(_this2.getValue());
  34440. _this2.__temp = new Color(0);
  34441. var _this = _this2;
  34442. _this2.domElement = document.createElement('div');
  34443. dom.makeSelectable(_this2.domElement, false);
  34444. _this2.__selector = document.createElement('div');
  34445. _this2.__selector.className = 'selector';
  34446. _this2.__saturation_field = document.createElement('div');
  34447. _this2.__saturation_field.className = 'saturation-field';
  34448. _this2.__field_knob = document.createElement('div');
  34449. _this2.__field_knob.className = 'field-knob';
  34450. _this2.__field_knob_border = '2px solid ';
  34451. _this2.__hue_knob = document.createElement('div');
  34452. _this2.__hue_knob.className = 'hue-knob';
  34453. _this2.__hue_field = document.createElement('div');
  34454. _this2.__hue_field.className = 'hue-field';
  34455. _this2.__input = document.createElement('input');
  34456. _this2.__input.type = 'text';
  34457. _this2.__input_textShadow = '0 1px 1px ';
  34458. dom.bind(_this2.__input, 'keydown', function (e) {
  34459. if (e.keyCode === 13) {
  34460. onBlur.call(this);
  34461. }
  34462. });
  34463. dom.bind(_this2.__input, 'blur', onBlur);
  34464. dom.bind(_this2.__selector, 'mousedown', function () {
  34465. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  34466. dom.removeClass(_this.__selector, 'drag');
  34467. });
  34468. });
  34469. dom.bind(_this2.__selector, 'touchstart', function () {
  34470. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  34471. dom.removeClass(_this.__selector, 'drag');
  34472. });
  34473. });
  34474. var valueField = document.createElement('div');
  34475. Common.extend(_this2.__selector.style, {
  34476. width: '122px',
  34477. height: '102px',
  34478. padding: '3px',
  34479. backgroundColor: '#222',
  34480. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  34481. });
  34482. Common.extend(_this2.__field_knob.style, {
  34483. position: 'absolute',
  34484. width: '12px',
  34485. height: '12px',
  34486. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  34487. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  34488. borderRadius: '12px',
  34489. zIndex: 1
  34490. });
  34491. Common.extend(_this2.__hue_knob.style, {
  34492. position: 'absolute',
  34493. width: '15px',
  34494. height: '2px',
  34495. borderRight: '4px solid #fff',
  34496. zIndex: 1
  34497. });
  34498. Common.extend(_this2.__saturation_field.style, {
  34499. width: '100px',
  34500. height: '100px',
  34501. border: '1px solid #555',
  34502. marginRight: '3px',
  34503. display: 'inline-block',
  34504. cursor: 'pointer'
  34505. });
  34506. Common.extend(valueField.style, {
  34507. width: '100%',
  34508. height: '100%',
  34509. background: 'none'
  34510. });
  34511. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  34512. Common.extend(_this2.__hue_field.style, {
  34513. width: '15px',
  34514. height: '100px',
  34515. border: '1px solid #555',
  34516. cursor: 'ns-resize',
  34517. position: 'absolute',
  34518. top: '3px',
  34519. right: '3px'
  34520. });
  34521. hueGradient(_this2.__hue_field);
  34522. Common.extend(_this2.__input.style, {
  34523. outline: 'none',
  34524. textAlign: 'center',
  34525. color: '#fff',
  34526. border: 0,
  34527. fontWeight: 'bold',
  34528. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  34529. });
  34530. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  34531. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  34532. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  34533. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  34534. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  34535. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  34536. function fieldDown(e) {
  34537. setSV(e);
  34538. dom.bind(window, 'mousemove', setSV);
  34539. dom.bind(window, 'touchmove', setSV);
  34540. dom.bind(window, 'mouseup', fieldUpSV);
  34541. dom.bind(window, 'touchend', fieldUpSV);
  34542. }
  34543. function fieldDownH(e) {
  34544. setH(e);
  34545. dom.bind(window, 'mousemove', setH);
  34546. dom.bind(window, 'touchmove', setH);
  34547. dom.bind(window, 'mouseup', fieldUpH);
  34548. dom.bind(window, 'touchend', fieldUpH);
  34549. }
  34550. function fieldUpSV() {
  34551. dom.unbind(window, 'mousemove', setSV);
  34552. dom.unbind(window, 'touchmove', setSV);
  34553. dom.unbind(window, 'mouseup', fieldUpSV);
  34554. dom.unbind(window, 'touchend', fieldUpSV);
  34555. onFinish();
  34556. }
  34557. function fieldUpH() {
  34558. dom.unbind(window, 'mousemove', setH);
  34559. dom.unbind(window, 'touchmove', setH);
  34560. dom.unbind(window, 'mouseup', fieldUpH);
  34561. dom.unbind(window, 'touchend', fieldUpH);
  34562. onFinish();
  34563. }
  34564. function onBlur() {
  34565. var i = interpret(this.value);
  34566. if (i !== false) {
  34567. _this.__color.__state = i;
  34568. _this.setValue(_this.__color.toOriginal());
  34569. } else {
  34570. this.value = _this.__color.toString();
  34571. }
  34572. }
  34573. function onFinish() {
  34574. if (_this.__onFinishChange) {
  34575. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  34576. }
  34577. }
  34578. _this2.__saturation_field.appendChild(valueField);
  34579. _this2.__selector.appendChild(_this2.__field_knob);
  34580. _this2.__selector.appendChild(_this2.__saturation_field);
  34581. _this2.__selector.appendChild(_this2.__hue_field);
  34582. _this2.__hue_field.appendChild(_this2.__hue_knob);
  34583. _this2.domElement.appendChild(_this2.__input);
  34584. _this2.domElement.appendChild(_this2.__selector);
  34585. _this2.updateDisplay();
  34586. function setSV(e) {
  34587. if (e.type.indexOf('touch') === -1) {
  34588. e.preventDefault();
  34589. }
  34590. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  34591. var _ref = e.touches && e.touches[0] || e,
  34592. clientX = _ref.clientX,
  34593. clientY = _ref.clientY;
  34594. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  34595. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34596. if (v > 1) {
  34597. v = 1;
  34598. } else if (v < 0) {
  34599. v = 0;
  34600. }
  34601. if (s > 1) {
  34602. s = 1;
  34603. } else if (s < 0) {
  34604. s = 0;
  34605. }
  34606. _this.__color.v = v;
  34607. _this.__color.s = s;
  34608. _this.setValue(_this.__color.toOriginal());
  34609. return false;
  34610. }
  34611. function setH(e) {
  34612. if (e.type.indexOf('touch') === -1) {
  34613. e.preventDefault();
  34614. }
  34615. var fieldRect = _this.__hue_field.getBoundingClientRect();
  34616. var _ref2 = e.touches && e.touches[0] || e,
  34617. clientY = _ref2.clientY;
  34618. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  34619. if (h > 1) {
  34620. h = 1;
  34621. } else if (h < 0) {
  34622. h = 0;
  34623. }
  34624. _this.__color.h = h * 360;
  34625. _this.setValue(_this.__color.toOriginal());
  34626. return false;
  34627. }
  34628. return _this2;
  34629. }
  34630. createClass(ColorController, [{
  34631. key: 'updateDisplay',
  34632. value: function updateDisplay() {
  34633. var i = interpret(this.getValue());
  34634. if (i !== false) {
  34635. var mismatch = false;
  34636. Common.each(Color.COMPONENTS, function (component) {
  34637. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  34638. mismatch = true;
  34639. return {};
  34640. }
  34641. }, this);
  34642. if (mismatch) {
  34643. Common.extend(this.__color.__state, i);
  34644. }
  34645. }
  34646. Common.extend(this.__temp.__state, this.__color.__state);
  34647. this.__temp.a = 1;
  34648. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  34649. var _flip = 255 - flip;
  34650. Common.extend(this.__field_knob.style, {
  34651. marginLeft: 100 * this.__color.s - 7 + 'px',
  34652. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  34653. backgroundColor: this.__temp.toHexString(),
  34654. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  34655. });
  34656. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  34657. this.__temp.s = 1;
  34658. this.__temp.v = 1;
  34659. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  34660. this.__input.value = this.__color.toString();
  34661. Common.extend(this.__input.style, {
  34662. backgroundColor: this.__color.toHexString(),
  34663. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  34664. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  34665. });
  34666. }
  34667. }]);
  34668. return ColorController;
  34669. }(Controller);
  34670. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  34671. function linearGradient(elem, x, a, b) {
  34672. elem.style.background = '';
  34673. Common.each(vendors, function (vendor) {
  34674. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  34675. });
  34676. }
  34677. function hueGradient(elem) {
  34678. elem.style.background = '';
  34679. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  34680. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34681. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34682. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34683. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  34684. }
  34685. var css = {
  34686. load: function load(url, indoc) {
  34687. var doc = indoc || document;
  34688. var link = doc.createElement('link');
  34689. link.type = 'text/css';
  34690. link.rel = 'stylesheet';
  34691. link.href = url;
  34692. doc.getElementsByTagName('head')[0].appendChild(link);
  34693. },
  34694. inject: function inject(cssContent, indoc) {
  34695. var doc = indoc || document;
  34696. var injected = document.createElement('style');
  34697. injected.type = 'text/css';
  34698. injected.innerHTML = cssContent;
  34699. var head = doc.getElementsByTagName('head')[0];
  34700. try {
  34701. head.appendChild(injected);
  34702. } catch (e) {}
  34703. }
  34704. };
  34705. 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>";
  34706. var ControllerFactory = function ControllerFactory(object, property) {
  34707. var initialValue = object[property];
  34708. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  34709. return new OptionController(object, property, arguments[2]);
  34710. }
  34711. if (Common.isNumber(initialValue)) {
  34712. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  34713. if (Common.isNumber(arguments[4])) {
  34714. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  34715. }
  34716. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  34717. }
  34718. if (Common.isNumber(arguments[4])) {
  34719. return new NumberControllerBox(object, property, {
  34720. min: arguments[2],
  34721. max: arguments[3],
  34722. step: arguments[4]
  34723. });
  34724. }
  34725. return new NumberControllerBox(object, property, {
  34726. min: arguments[2],
  34727. max: arguments[3]
  34728. });
  34729. }
  34730. if (Common.isString(initialValue)) {
  34731. return new StringController(object, property);
  34732. }
  34733. if (Common.isFunction(initialValue)) {
  34734. return new FunctionController(object, property, '');
  34735. }
  34736. if (Common.isBoolean(initialValue)) {
  34737. return new BooleanController(object, property);
  34738. }
  34739. return null;
  34740. };
  34741. function requestAnimationFrame(callback) {
  34742. setTimeout(callback, 1000 / 60);
  34743. }
  34744. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  34745. var CenteredDiv = function () {
  34746. function CenteredDiv() {
  34747. classCallCheck(this, CenteredDiv);
  34748. this.backgroundElement = document.createElement('div');
  34749. Common.extend(this.backgroundElement.style, {
  34750. backgroundColor: 'rgba(0,0,0,0.8)',
  34751. top: 0,
  34752. left: 0,
  34753. display: 'none',
  34754. zIndex: '1000',
  34755. opacity: 0,
  34756. WebkitTransition: 'opacity 0.2s linear',
  34757. transition: 'opacity 0.2s linear'
  34758. });
  34759. dom.makeFullscreen(this.backgroundElement);
  34760. this.backgroundElement.style.position = 'fixed';
  34761. this.domElement = document.createElement('div');
  34762. Common.extend(this.domElement.style, {
  34763. position: 'fixed',
  34764. display: 'none',
  34765. zIndex: '1001',
  34766. opacity: 0,
  34767. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  34768. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  34769. });
  34770. document.body.appendChild(this.backgroundElement);
  34771. document.body.appendChild(this.domElement);
  34772. var _this = this;
  34773. dom.bind(this.backgroundElement, 'click', function () {
  34774. _this.hide();
  34775. });
  34776. }
  34777. createClass(CenteredDiv, [{
  34778. key: 'show',
  34779. value: function show() {
  34780. var _this = this;
  34781. this.backgroundElement.style.display = 'block';
  34782. this.domElement.style.display = 'block';
  34783. this.domElement.style.opacity = 0;
  34784. this.domElement.style.webkitTransform = 'scale(1.1)';
  34785. this.layout();
  34786. Common.defer(function () {
  34787. _this.backgroundElement.style.opacity = 1;
  34788. _this.domElement.style.opacity = 1;
  34789. _this.domElement.style.webkitTransform = 'scale(1)';
  34790. });
  34791. }
  34792. }, {
  34793. key: 'hide',
  34794. value: function hide() {
  34795. var _this = this;
  34796. var hide = function hide() {
  34797. _this.domElement.style.display = 'none';
  34798. _this.backgroundElement.style.display = 'none';
  34799. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  34800. dom.unbind(_this.domElement, 'transitionend', hide);
  34801. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  34802. };
  34803. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  34804. dom.bind(this.domElement, 'transitionend', hide);
  34805. dom.bind(this.domElement, 'oTransitionEnd', hide);
  34806. this.backgroundElement.style.opacity = 0;
  34807. this.domElement.style.opacity = 0;
  34808. this.domElement.style.webkitTransform = 'scale(1.1)';
  34809. }
  34810. }, {
  34811. key: 'layout',
  34812. value: function layout() {
  34813. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  34814. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  34815. }
  34816. }]);
  34817. return CenteredDiv;
  34818. }();
  34819. 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");
  34820. css.inject(styleSheet);
  34821. var CSS_NAMESPACE = 'dg';
  34822. var HIDE_KEY_CODE = 72;
  34823. var CLOSE_BUTTON_HEIGHT = 20;
  34824. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  34825. var SUPPORTS_LOCAL_STORAGE = function () {
  34826. try {
  34827. return !!window.localStorage;
  34828. } catch (e) {
  34829. return false;
  34830. }
  34831. }();
  34832. var SAVE_DIALOGUE = void 0;
  34833. var autoPlaceVirgin = true;
  34834. var autoPlaceContainer = void 0;
  34835. var hide = false;
  34836. var hideableGuis = [];
  34837. var GUI = function GUI(pars) {
  34838. var _this = this;
  34839. var params = pars || {};
  34840. this.domElement = document.createElement('div');
  34841. this.__ul = document.createElement('ul');
  34842. this.domElement.appendChild(this.__ul);
  34843. dom.addClass(this.domElement, CSS_NAMESPACE);
  34844. this.__folders = {};
  34845. this.__controllers = [];
  34846. this.__rememberedObjects = [];
  34847. this.__rememberedObjectIndecesToControllers = [];
  34848. this.__listening = [];
  34849. params = Common.defaults(params, {
  34850. closeOnTop: false,
  34851. autoPlace: true,
  34852. width: GUI.DEFAULT_WIDTH
  34853. });
  34854. params = Common.defaults(params, {
  34855. resizable: params.autoPlace,
  34856. hideable: params.autoPlace
  34857. });
  34858. if (!Common.isUndefined(params.load)) {
  34859. if (params.preset) {
  34860. params.load.preset = params.preset;
  34861. }
  34862. } else {
  34863. params.load = {
  34864. preset: DEFAULT_DEFAULT_PRESET_NAME
  34865. };
  34866. }
  34867. if (Common.isUndefined(params.parent) && params.hideable) {
  34868. hideableGuis.push(this);
  34869. }
  34870. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  34871. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  34872. params.scrollable = true;
  34873. }
  34874. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  34875. var saveToLocalStorage = void 0;
  34876. var titleRow = void 0;
  34877. Object.defineProperties(this, {
  34878. parent: {
  34879. get: function get$$1() {
  34880. return params.parent;
  34881. }
  34882. },
  34883. scrollable: {
  34884. get: function get$$1() {
  34885. return params.scrollable;
  34886. }
  34887. },
  34888. autoPlace: {
  34889. get: function get$$1() {
  34890. return params.autoPlace;
  34891. }
  34892. },
  34893. closeOnTop: {
  34894. get: function get$$1() {
  34895. return params.closeOnTop;
  34896. }
  34897. },
  34898. preset: {
  34899. get: function get$$1() {
  34900. if (_this.parent) {
  34901. return _this.getRoot().preset;
  34902. }
  34903. return params.load.preset;
  34904. },
  34905. set: function set$$1(v) {
  34906. if (_this.parent) {
  34907. _this.getRoot().preset = v;
  34908. } else {
  34909. params.load.preset = v;
  34910. }
  34911. setPresetSelectIndex(this);
  34912. _this.revert();
  34913. }
  34914. },
  34915. width: {
  34916. get: function get$$1() {
  34917. return params.width;
  34918. },
  34919. set: function set$$1(v) {
  34920. params.width = v;
  34921. setWidth(_this, v);
  34922. }
  34923. },
  34924. name: {
  34925. get: function get$$1() {
  34926. return params.name;
  34927. },
  34928. set: function set$$1(v) {
  34929. params.name = v;
  34930. if (titleRow) {
  34931. titleRow.innerHTML = params.name;
  34932. }
  34933. }
  34934. },
  34935. closed: {
  34936. get: function get$$1() {
  34937. return params.closed;
  34938. },
  34939. set: function set$$1(v) {
  34940. params.closed = v;
  34941. if (params.closed) {
  34942. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  34943. } else {
  34944. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  34945. }
  34946. this.onResize();
  34947. if (_this.__closeButton) {
  34948. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  34949. }
  34950. }
  34951. },
  34952. load: {
  34953. get: function get$$1() {
  34954. return params.load;
  34955. }
  34956. },
  34957. useLocalStorage: {
  34958. get: function get$$1() {
  34959. return useLocalStorage;
  34960. },
  34961. set: function set$$1(bool) {
  34962. if (SUPPORTS_LOCAL_STORAGE) {
  34963. useLocalStorage = bool;
  34964. if (bool) {
  34965. dom.bind(window, 'unload', saveToLocalStorage);
  34966. } else {
  34967. dom.unbind(window, 'unload', saveToLocalStorage);
  34968. }
  34969. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  34970. }
  34971. }
  34972. }
  34973. });
  34974. if (Common.isUndefined(params.parent)) {
  34975. this.closed = params.closed || false;
  34976. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  34977. dom.makeSelectable(this.domElement, false);
  34978. if (SUPPORTS_LOCAL_STORAGE) {
  34979. if (useLocalStorage) {
  34980. _this.useLocalStorage = true;
  34981. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  34982. if (savedGui) {
  34983. params.load = JSON.parse(savedGui);
  34984. }
  34985. }
  34986. }
  34987. this.__closeButton = document.createElement('div');
  34988. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  34989. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  34990. if (params.closeOnTop) {
  34991. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  34992. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  34993. } else {
  34994. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  34995. this.domElement.appendChild(this.__closeButton);
  34996. }
  34997. dom.bind(this.__closeButton, 'click', function () {
  34998. _this.closed = !_this.closed;
  34999. });
  35000. } else {
  35001. if (params.closed === undefined) {
  35002. params.closed = true;
  35003. }
  35004. var titleRowName = document.createTextNode(params.name);
  35005. dom.addClass(titleRowName, 'controller-name');
  35006. titleRow = addRow(_this, titleRowName);
  35007. var onClickTitle = function onClickTitle(e) {
  35008. e.preventDefault();
  35009. _this.closed = !_this.closed;
  35010. return false;
  35011. };
  35012. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  35013. dom.addClass(titleRow, 'title');
  35014. dom.bind(titleRow, 'click', onClickTitle);
  35015. if (!params.closed) {
  35016. this.closed = false;
  35017. }
  35018. }
  35019. if (params.autoPlace) {
  35020. if (Common.isUndefined(params.parent)) {
  35021. if (autoPlaceVirgin) {
  35022. autoPlaceContainer = document.createElement('div');
  35023. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  35024. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  35025. document.body.appendChild(autoPlaceContainer);
  35026. autoPlaceVirgin = false;
  35027. }
  35028. autoPlaceContainer.appendChild(this.domElement);
  35029. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  35030. }
  35031. if (!this.parent) {
  35032. setWidth(_this, params.width);
  35033. }
  35034. }
  35035. this.__resizeHandler = function () {
  35036. _this.onResizeDebounced();
  35037. };
  35038. dom.bind(window, 'resize', this.__resizeHandler);
  35039. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  35040. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  35041. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  35042. this.onResize();
  35043. if (params.resizable) {
  35044. addResizeHandle(this);
  35045. }
  35046. saveToLocalStorage = function saveToLocalStorage() {
  35047. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  35048. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  35049. }
  35050. };
  35051. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  35052. function resetWidth() {
  35053. var root = _this.getRoot();
  35054. root.width += 1;
  35055. Common.defer(function () {
  35056. root.width -= 1;
  35057. });
  35058. }
  35059. if (!params.parent) {
  35060. resetWidth();
  35061. }
  35062. };
  35063. GUI.toggleHide = function () {
  35064. hide = !hide;
  35065. Common.each(hideableGuis, function (gui) {
  35066. gui.domElement.style.display = hide ? 'none' : '';
  35067. });
  35068. };
  35069. GUI.CLASS_AUTO_PLACE = 'a';
  35070. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  35071. GUI.CLASS_MAIN = 'main';
  35072. GUI.CLASS_CONTROLLER_ROW = 'cr';
  35073. GUI.CLASS_TOO_TALL = 'taller-than-window';
  35074. GUI.CLASS_CLOSED = 'closed';
  35075. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  35076. GUI.CLASS_CLOSE_TOP = 'close-top';
  35077. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  35078. GUI.CLASS_DRAG = 'drag';
  35079. GUI.DEFAULT_WIDTH = 245;
  35080. GUI.TEXT_CLOSED = 'Close Controls';
  35081. GUI.TEXT_OPEN = 'Open Controls';
  35082. GUI._keydownHandler = function (e) {
  35083. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  35084. GUI.toggleHide();
  35085. }
  35086. };
  35087. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  35088. Common.extend(GUI.prototype, {
  35089. add: function add(object, property) {
  35090. return _add(this, object, property, {
  35091. factoryArgs: Array.prototype.slice.call(arguments, 2)
  35092. });
  35093. },
  35094. addColor: function addColor(object, property) {
  35095. return _add(this, object, property, {
  35096. color: true
  35097. });
  35098. },
  35099. remove: function remove(controller) {
  35100. this.__ul.removeChild(controller.__li);
  35101. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  35102. var _this = this;
  35103. Common.defer(function () {
  35104. _this.onResize();
  35105. });
  35106. },
  35107. destroy: function destroy() {
  35108. if (this.parent) {
  35109. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  35110. }
  35111. if (this.autoPlace) {
  35112. autoPlaceContainer.removeChild(this.domElement);
  35113. }
  35114. var _this = this;
  35115. Common.each(this.__folders, function (subfolder) {
  35116. _this.removeFolder(subfolder);
  35117. });
  35118. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  35119. removeListeners(this);
  35120. },
  35121. addFolder: function addFolder(name) {
  35122. if (this.__folders[name] !== undefined) {
  35123. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  35124. }
  35125. var newGuiParams = {
  35126. name: name,
  35127. parent: this
  35128. };
  35129. newGuiParams.autoPlace = this.autoPlace;
  35130. if (this.load && this.load.folders && this.load.folders[name]) {
  35131. newGuiParams.closed = this.load.folders[name].closed;
  35132. newGuiParams.load = this.load.folders[name];
  35133. }
  35134. var gui = new GUI(newGuiParams);
  35135. this.__folders[name] = gui;
  35136. var li = addRow(this, gui.domElement);
  35137. dom.addClass(li, 'folder');
  35138. return gui;
  35139. },
  35140. removeFolder: function removeFolder(folder) {
  35141. this.__ul.removeChild(folder.domElement.parentElement);
  35142. delete this.__folders[folder.name];
  35143. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  35144. delete this.load.folders[folder.name];
  35145. }
  35146. removeListeners(folder);
  35147. var _this = this;
  35148. Common.each(folder.__folders, function (subfolder) {
  35149. folder.removeFolder(subfolder);
  35150. });
  35151. Common.defer(function () {
  35152. _this.onResize();
  35153. });
  35154. },
  35155. open: function open() {
  35156. this.closed = false;
  35157. },
  35158. close: function close() {
  35159. this.closed = true;
  35160. },
  35161. hide: function hide() {
  35162. this.domElement.style.display = 'none';
  35163. },
  35164. show: function show() {
  35165. this.domElement.style.display = '';
  35166. },
  35167. onResize: function onResize() {
  35168. var root = this.getRoot();
  35169. if (root.scrollable) {
  35170. var top = dom.getOffset(root.__ul).top;
  35171. var h = 0;
  35172. Common.each(root.__ul.childNodes, function (node) {
  35173. if (!(root.autoPlace && node === root.__save_row)) {
  35174. h += dom.getHeight(node);
  35175. }
  35176. });
  35177. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  35178. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  35179. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  35180. } else {
  35181. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  35182. root.__ul.style.height = 'auto';
  35183. }
  35184. }
  35185. if (root.__resize_handle) {
  35186. Common.defer(function () {
  35187. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  35188. });
  35189. }
  35190. if (root.__closeButton) {
  35191. root.__closeButton.style.width = root.width + 'px';
  35192. }
  35193. },
  35194. onResizeDebounced: Common.debounce(function () {
  35195. this.onResize();
  35196. }, 50),
  35197. remember: function remember() {
  35198. if (Common.isUndefined(SAVE_DIALOGUE)) {
  35199. SAVE_DIALOGUE = new CenteredDiv();
  35200. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  35201. }
  35202. if (this.parent) {
  35203. throw new Error('You can only call remember on a top level GUI.');
  35204. }
  35205. var _this = this;
  35206. Common.each(Array.prototype.slice.call(arguments), function (object) {
  35207. if (_this.__rememberedObjects.length === 0) {
  35208. addSaveMenu(_this);
  35209. }
  35210. if (_this.__rememberedObjects.indexOf(object) === -1) {
  35211. _this.__rememberedObjects.push(object);
  35212. }
  35213. });
  35214. if (this.autoPlace) {
  35215. setWidth(this, this.width);
  35216. }
  35217. },
  35218. getRoot: function getRoot() {
  35219. var gui = this;
  35220. while (gui.parent) {
  35221. gui = gui.parent;
  35222. }
  35223. return gui;
  35224. },
  35225. getSaveObject: function getSaveObject() {
  35226. var toReturn = this.load;
  35227. toReturn.closed = this.closed;
  35228. if (this.__rememberedObjects.length > 0) {
  35229. toReturn.preset = this.preset;
  35230. if (!toReturn.remembered) {
  35231. toReturn.remembered = {};
  35232. }
  35233. toReturn.remembered[this.preset] = getCurrentPreset(this);
  35234. }
  35235. toReturn.folders = {};
  35236. Common.each(this.__folders, function (element, key) {
  35237. toReturn.folders[key] = element.getSaveObject();
  35238. });
  35239. return toReturn;
  35240. },
  35241. save: function save() {
  35242. if (!this.load.remembered) {
  35243. this.load.remembered = {};
  35244. }
  35245. this.load.remembered[this.preset] = getCurrentPreset(this);
  35246. markPresetModified(this, false);
  35247. this.saveToLocalStorageIfPossible();
  35248. },
  35249. saveAs: function saveAs(presetName) {
  35250. if (!this.load.remembered) {
  35251. this.load.remembered = {};
  35252. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  35253. }
  35254. this.load.remembered[presetName] = getCurrentPreset(this);
  35255. this.preset = presetName;
  35256. addPresetOption(this, presetName, true);
  35257. this.saveToLocalStorageIfPossible();
  35258. },
  35259. revert: function revert(gui) {
  35260. Common.each(this.__controllers, function (controller) {
  35261. if (!this.getRoot().load.remembered) {
  35262. controller.setValue(controller.initialValue);
  35263. } else {
  35264. recallSavedValue(gui || this.getRoot(), controller);
  35265. }
  35266. if (controller.__onFinishChange) {
  35267. controller.__onFinishChange.call(controller, controller.getValue());
  35268. }
  35269. }, this);
  35270. Common.each(this.__folders, function (folder) {
  35271. folder.revert(folder);
  35272. });
  35273. if (!gui) {
  35274. markPresetModified(this.getRoot(), false);
  35275. }
  35276. },
  35277. listen: function listen(controller) {
  35278. var init = this.__listening.length === 0;
  35279. this.__listening.push(controller);
  35280. if (init) {
  35281. updateDisplays(this.__listening);
  35282. }
  35283. },
  35284. updateDisplay: function updateDisplay() {
  35285. Common.each(this.__controllers, function (controller) {
  35286. controller.updateDisplay();
  35287. });
  35288. Common.each(this.__folders, function (folder) {
  35289. folder.updateDisplay();
  35290. });
  35291. }
  35292. });
  35293. function addRow(gui, newDom, liBefore) {
  35294. var li = document.createElement('li');
  35295. if (newDom) {
  35296. li.appendChild(newDom);
  35297. }
  35298. if (liBefore) {
  35299. gui.__ul.insertBefore(li, liBefore);
  35300. } else {
  35301. gui.__ul.appendChild(li);
  35302. }
  35303. gui.onResize();
  35304. return li;
  35305. }
  35306. function removeListeners(gui) {
  35307. dom.unbind(window, 'resize', gui.__resizeHandler);
  35308. if (gui.saveToLocalStorageIfPossible) {
  35309. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  35310. }
  35311. }
  35312. function markPresetModified(gui, modified) {
  35313. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  35314. if (modified) {
  35315. opt.innerHTML = opt.value + '*';
  35316. } else {
  35317. opt.innerHTML = opt.value;
  35318. }
  35319. }
  35320. function augmentController(gui, li, controller) {
  35321. controller.__li = li;
  35322. controller.__gui = gui;
  35323. Common.extend(controller, {
  35324. options: function options(_options) {
  35325. if (arguments.length > 1) {
  35326. var nextSibling = controller.__li.nextElementSibling;
  35327. controller.remove();
  35328. return _add(gui, controller.object, controller.property, {
  35329. before: nextSibling,
  35330. factoryArgs: [Common.toArray(arguments)]
  35331. });
  35332. }
  35333. if (Common.isArray(_options) || Common.isObject(_options)) {
  35334. var _nextSibling = controller.__li.nextElementSibling;
  35335. controller.remove();
  35336. return _add(gui, controller.object, controller.property, {
  35337. before: _nextSibling,
  35338. factoryArgs: [_options]
  35339. });
  35340. }
  35341. },
  35342. name: function name(_name) {
  35343. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  35344. return controller;
  35345. },
  35346. listen: function listen() {
  35347. controller.__gui.listen(controller);
  35348. return controller;
  35349. },
  35350. remove: function remove() {
  35351. controller.__gui.remove(controller);
  35352. return controller;
  35353. }
  35354. });
  35355. if (controller instanceof NumberControllerSlider) {
  35356. var box = new NumberControllerBox(controller.object, controller.property, {
  35357. min: controller.__min,
  35358. max: controller.__max,
  35359. step: controller.__step
  35360. });
  35361. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  35362. var pc = controller[method];
  35363. var pb = box[method];
  35364. controller[method] = box[method] = function () {
  35365. var args = Array.prototype.slice.call(arguments);
  35366. pb.apply(box, args);
  35367. return pc.apply(controller, args);
  35368. };
  35369. });
  35370. dom.addClass(li, 'has-slider');
  35371. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  35372. } else if (controller instanceof NumberControllerBox) {
  35373. var r = function r(returned) {
  35374. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  35375. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  35376. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  35377. controller.remove();
  35378. var newController = _add(gui, controller.object, controller.property, {
  35379. before: controller.__li.nextElementSibling,
  35380. factoryArgs: [controller.__min, controller.__max, controller.__step]
  35381. });
  35382. newController.name(oldName);
  35383. if (wasListening) newController.listen();
  35384. return newController;
  35385. }
  35386. return returned;
  35387. };
  35388. controller.min = Common.compose(r, controller.min);
  35389. controller.max = Common.compose(r, controller.max);
  35390. } else if (controller instanceof BooleanController) {
  35391. dom.bind(li, 'click', function () {
  35392. dom.fakeEvent(controller.__checkbox, 'click');
  35393. });
  35394. dom.bind(controller.__checkbox, 'click', function (e) {
  35395. e.stopPropagation();
  35396. });
  35397. } else if (controller instanceof FunctionController) {
  35398. dom.bind(li, 'click', function () {
  35399. dom.fakeEvent(controller.__button, 'click');
  35400. });
  35401. dom.bind(li, 'mouseover', function () {
  35402. dom.addClass(controller.__button, 'hover');
  35403. });
  35404. dom.bind(li, 'mouseout', function () {
  35405. dom.removeClass(controller.__button, 'hover');
  35406. });
  35407. } else if (controller instanceof ColorController) {
  35408. dom.addClass(li, 'color');
  35409. controller.updateDisplay = Common.compose(function (val) {
  35410. li.style.borderLeftColor = controller.__color.toString();
  35411. return val;
  35412. }, controller.updateDisplay);
  35413. controller.updateDisplay();
  35414. }
  35415. controller.setValue = Common.compose(function (val) {
  35416. if (gui.getRoot().__preset_select && controller.isModified()) {
  35417. markPresetModified(gui.getRoot(), true);
  35418. }
  35419. return val;
  35420. }, controller.setValue);
  35421. }
  35422. function recallSavedValue(gui, controller) {
  35423. var root = gui.getRoot();
  35424. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  35425. if (matchedIndex !== -1) {
  35426. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  35427. if (controllerMap === undefined) {
  35428. controllerMap = {};
  35429. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  35430. }
  35431. controllerMap[controller.property] = controller;
  35432. if (root.load && root.load.remembered) {
  35433. var presetMap = root.load.remembered;
  35434. var preset = void 0;
  35435. if (presetMap[gui.preset]) {
  35436. preset = presetMap[gui.preset];
  35437. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  35438. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  35439. } else {
  35440. return;
  35441. }
  35442. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  35443. var value = preset[matchedIndex][controller.property];
  35444. controller.initialValue = value;
  35445. controller.setValue(value);
  35446. }
  35447. }
  35448. }
  35449. }
  35450. function _add(gui, object, property, params) {
  35451. if (object[property] === undefined) {
  35452. throw new Error('Object "' + object + '" has no property "' + property + '"');
  35453. }
  35454. var controller = void 0;
  35455. if (params.color) {
  35456. controller = new ColorController(object, property);
  35457. } else {
  35458. var factoryArgs = [object, property].concat(params.factoryArgs);
  35459. controller = ControllerFactory.apply(gui, factoryArgs);
  35460. }
  35461. if (params.before instanceof Controller) {
  35462. params.before = params.before.__li;
  35463. }
  35464. recallSavedValue(gui, controller);
  35465. dom.addClass(controller.domElement, 'c');
  35466. var name = document.createElement('span');
  35467. dom.addClass(name, 'property-name');
  35468. name.innerHTML = controller.property;
  35469. var container = document.createElement('div');
  35470. container.appendChild(name);
  35471. container.appendChild(controller.domElement);
  35472. var li = addRow(gui, container, params.before);
  35473. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  35474. if (controller instanceof ColorController) {
  35475. dom.addClass(li, 'color');
  35476. } else {
  35477. dom.addClass(li, _typeof(controller.getValue()));
  35478. }
  35479. augmentController(gui, li, controller);
  35480. gui.__controllers.push(controller);
  35481. return controller;
  35482. }
  35483. function getLocalStorageHash(gui, key) {
  35484. return document.location.href + '.' + key;
  35485. }
  35486. function addPresetOption(gui, name, setSelected) {
  35487. var opt = document.createElement('option');
  35488. opt.innerHTML = name;
  35489. opt.value = name;
  35490. gui.__preset_select.appendChild(opt);
  35491. if (setSelected) {
  35492. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  35493. }
  35494. }
  35495. function showHideExplain(gui, explain) {
  35496. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  35497. }
  35498. function addSaveMenu(gui) {
  35499. var div = gui.__save_row = document.createElement('li');
  35500. dom.addClass(gui.domElement, 'has-save');
  35501. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  35502. dom.addClass(div, 'save-row');
  35503. var gears = document.createElement('span');
  35504. gears.innerHTML = '&nbsp;';
  35505. dom.addClass(gears, 'button gears');
  35506. var button = document.createElement('span');
  35507. button.innerHTML = 'Save';
  35508. dom.addClass(button, 'button');
  35509. dom.addClass(button, 'save');
  35510. var button2 = document.createElement('span');
  35511. button2.innerHTML = 'New';
  35512. dom.addClass(button2, 'button');
  35513. dom.addClass(button2, 'save-as');
  35514. var button3 = document.createElement('span');
  35515. button3.innerHTML = 'Revert';
  35516. dom.addClass(button3, 'button');
  35517. dom.addClass(button3, 'revert');
  35518. var select = gui.__preset_select = document.createElement('select');
  35519. if (gui.load && gui.load.remembered) {
  35520. Common.each(gui.load.remembered, function (value, key) {
  35521. addPresetOption(gui, key, key === gui.preset);
  35522. });
  35523. } else {
  35524. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  35525. }
  35526. dom.bind(select, 'change', function () {
  35527. for (var index = 0; index < gui.__preset_select.length; index++) {
  35528. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  35529. }
  35530. gui.preset = this.value;
  35531. });
  35532. div.appendChild(select);
  35533. div.appendChild(gears);
  35534. div.appendChild(button);
  35535. div.appendChild(button2);
  35536. div.appendChild(button3);
  35537. if (SUPPORTS_LOCAL_STORAGE) {
  35538. var explain = document.getElementById('dg-local-explain');
  35539. var localStorageCheckBox = document.getElementById('dg-local-storage');
  35540. var saveLocally = document.getElementById('dg-save-locally');
  35541. saveLocally.style.display = 'block';
  35542. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  35543. localStorageCheckBox.setAttribute('checked', 'checked');
  35544. }
  35545. showHideExplain(gui, explain);
  35546. dom.bind(localStorageCheckBox, 'change', function () {
  35547. gui.useLocalStorage = !gui.useLocalStorage;
  35548. showHideExplain(gui, explain);
  35549. });
  35550. }
  35551. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  35552. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  35553. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  35554. SAVE_DIALOGUE.hide();
  35555. }
  35556. });
  35557. dom.bind(gears, 'click', function () {
  35558. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  35559. SAVE_DIALOGUE.show();
  35560. newConstructorTextArea.focus();
  35561. newConstructorTextArea.select();
  35562. });
  35563. dom.bind(button, 'click', function () {
  35564. gui.save();
  35565. });
  35566. dom.bind(button2, 'click', function () {
  35567. var presetName = prompt('Enter a new preset name.');
  35568. if (presetName) {
  35569. gui.saveAs(presetName);
  35570. }
  35571. });
  35572. dom.bind(button3, 'click', function () {
  35573. gui.revert();
  35574. });
  35575. }
  35576. function addResizeHandle(gui) {
  35577. var pmouseX = void 0;
  35578. gui.__resize_handle = document.createElement('div');
  35579. Common.extend(gui.__resize_handle.style, {
  35580. width: '6px',
  35581. marginLeft: '-3px',
  35582. height: '200px',
  35583. cursor: 'ew-resize',
  35584. position: 'absolute'
  35585. });
  35586. function drag(e) {
  35587. e.preventDefault();
  35588. gui.width += pmouseX - e.clientX;
  35589. gui.onResize();
  35590. pmouseX = e.clientX;
  35591. return false;
  35592. }
  35593. function dragStop() {
  35594. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  35595. dom.unbind(window, 'mousemove', drag);
  35596. dom.unbind(window, 'mouseup', dragStop);
  35597. }
  35598. function dragStart(e) {
  35599. e.preventDefault();
  35600. pmouseX = e.clientX;
  35601. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  35602. dom.bind(window, 'mousemove', drag);
  35603. dom.bind(window, 'mouseup', dragStop);
  35604. return false;
  35605. }
  35606. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  35607. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  35608. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  35609. }
  35610. function setWidth(gui, w) {
  35611. gui.domElement.style.width = w + 'px';
  35612. if (gui.__save_row && gui.autoPlace) {
  35613. gui.__save_row.style.width = w + 'px';
  35614. }
  35615. if (gui.__closeButton) {
  35616. gui.__closeButton.style.width = w + 'px';
  35617. }
  35618. }
  35619. function getCurrentPreset(gui, useInitialValues) {
  35620. var toReturn = {};
  35621. Common.each(gui.__rememberedObjects, function (val, index) {
  35622. var savedValues = {};
  35623. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  35624. Common.each(controllerMap, function (controller, property) {
  35625. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  35626. });
  35627. toReturn[index] = savedValues;
  35628. });
  35629. return toReturn;
  35630. }
  35631. function setPresetSelectIndex(gui) {
  35632. for (var index = 0; index < gui.__preset_select.length; index++) {
  35633. if (gui.__preset_select[index].value === gui.preset) {
  35634. gui.__preset_select.selectedIndex = index;
  35635. }
  35636. }
  35637. }
  35638. function updateDisplays(controllerArray) {
  35639. if (controllerArray.length !== 0) {
  35640. requestAnimationFrame$1.call(window, function () {
  35641. updateDisplays(controllerArray);
  35642. });
  35643. }
  35644. Common.each(controllerArray, function (c) {
  35645. c.updateDisplay();
  35646. });
  35647. }
  35648. var color = {
  35649. Color: Color,
  35650. math: ColorMath,
  35651. interpret: interpret
  35652. };
  35653. exports.color = color;
  35654. var controllers = {
  35655. Controller: Controller,
  35656. BooleanController: BooleanController,
  35657. OptionController: OptionController,
  35658. StringController: StringController,
  35659. NumberController: NumberController,
  35660. NumberControllerBox: NumberControllerBox,
  35661. NumberControllerSlider: NumberControllerSlider,
  35662. FunctionController: FunctionController,
  35663. ColorController: ColorController
  35664. };
  35665. exports.controllers = controllers;
  35666. var dom$1 = {
  35667. dom: dom
  35668. };
  35669. exports.dom = dom$1;
  35670. var gui = {
  35671. GUI: GUI
  35672. };
  35673. exports.gui = gui;
  35674. var GUI$1 = GUI;
  35675. exports.GUI = GUI$1;
  35676. var index = {
  35677. color: color,
  35678. controllers: controllers,
  35679. dom: dom$1,
  35680. gui: gui,
  35681. GUI: GUI$1
  35682. };
  35683. var _default = index;
  35684. exports.default = _default;
  35685. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  35686. "use strict";
  35687. Object.defineProperty(exports, "__esModule", {
  35688. value: true
  35689. });
  35690. exports.default = void 0;
  35691. /**
  35692. * @author mrdoob / http://mrdoob.com/
  35693. */
  35694. var Stats = function () {
  35695. var mode = 0;
  35696. var container = document.createElement('div');
  35697. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  35698. container.addEventListener('click', function (event) {
  35699. event.preventDefault();
  35700. showPanel(++mode % container.children.length);
  35701. }, false); //
  35702. function addPanel(panel) {
  35703. container.appendChild(panel.dom);
  35704. return panel;
  35705. }
  35706. function showPanel(id) {
  35707. for (var i = 0; i < container.children.length; i++) {
  35708. container.children[i].style.display = i === id ? 'block' : 'none';
  35709. }
  35710. mode = id;
  35711. } //
  35712. var beginTime = (performance || Date).now(),
  35713. prevTime = beginTime,
  35714. frames = 0;
  35715. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  35716. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  35717. if (self.performance && self.performance.memory) {
  35718. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  35719. }
  35720. showPanel(0);
  35721. return {
  35722. REVISION: 16,
  35723. dom: container,
  35724. addPanel: addPanel,
  35725. showPanel: showPanel,
  35726. begin: function () {
  35727. beginTime = (performance || Date).now();
  35728. },
  35729. end: function () {
  35730. frames++;
  35731. var time = (performance || Date).now();
  35732. msPanel.update(time - beginTime, 200);
  35733. if (time >= prevTime + 1000) {
  35734. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  35735. prevTime = time;
  35736. frames = 0;
  35737. if (memPanel) {
  35738. var memory = performance.memory;
  35739. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  35740. }
  35741. }
  35742. return time;
  35743. },
  35744. update: function () {
  35745. beginTime = this.end();
  35746. },
  35747. // Backwards Compatibility
  35748. domElement: container,
  35749. setMode: showPanel
  35750. };
  35751. };
  35752. Stats.Panel = function (name, fg, bg) {
  35753. var min = Infinity,
  35754. max = 0,
  35755. round = Math.round;
  35756. var PR = round(window.devicePixelRatio || 1);
  35757. var WIDTH = 80 * PR,
  35758. HEIGHT = 48 * PR,
  35759. TEXT_X = 3 * PR,
  35760. TEXT_Y = 2 * PR,
  35761. GRAPH_X = 3 * PR,
  35762. GRAPH_Y = 15 * PR,
  35763. GRAPH_WIDTH = 74 * PR,
  35764. GRAPH_HEIGHT = 30 * PR;
  35765. var canvas = document.createElement('canvas');
  35766. canvas.width = WIDTH;
  35767. canvas.height = HEIGHT;
  35768. canvas.style.cssText = 'width:80px;height:48px';
  35769. var context = canvas.getContext('2d');
  35770. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  35771. context.textBaseline = 'top';
  35772. context.fillStyle = bg;
  35773. context.fillRect(0, 0, WIDTH, HEIGHT);
  35774. context.fillStyle = fg;
  35775. context.fillText(name, TEXT_X, TEXT_Y);
  35776. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  35777. context.fillStyle = bg;
  35778. context.globalAlpha = 0.9;
  35779. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  35780. return {
  35781. dom: canvas,
  35782. update: function (value, maxValue) {
  35783. min = Math.min(min, value);
  35784. max = Math.max(max, value);
  35785. context.fillStyle = bg;
  35786. context.globalAlpha = 1;
  35787. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  35788. context.fillStyle = fg;
  35789. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  35790. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  35791. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  35792. context.fillStyle = bg;
  35793. context.globalAlpha = 0.9;
  35794. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  35795. }
  35796. };
  35797. };
  35798. var _default = Stats;
  35799. exports.default = _default;
  35800. },{}],"index.js":[function(require,module,exports) {
  35801. "use strict";
  35802. var _ThreeTilesRenderer = require("../src/ThreeTilesRenderer.js");
  35803. var _three = require("three");
  35804. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  35805. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  35806. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  35807. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  35808. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  35809. 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; }
  35810. let camera, controls, scene, renderer, tiles, cameraHelper;
  35811. let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  35812. let box;
  35813. let statsContainer, stats;
  35814. let params = {
  35815. 'errorTarget': 6,
  35816. 'errorThreshold': 60,
  35817. 'maxDepth': 15,
  35818. 'loadSiblings': true,
  35819. 'displayBounds': false,
  35820. 'showThirdPerson': true,
  35821. 'reload': reinstantiateTiles
  35822. };
  35823. init();
  35824. animate();
  35825. function reinstantiateTiles() {
  35826. if (tiles) {
  35827. scene.remove(tiles.group);
  35828. }
  35829. tiles = new _ThreeTilesRenderer.ThreeTilesRenderer('https://m20-rps-asttro-terrain.s3-us-gov-west-1.amazonaws.com/sol/00000/ids/tileset/0000_0020536/0000_0020536_tileset.json', camera, renderer);
  35830. scene.add(tiles.group);
  35831. tiles.group.rotation.x = Math.PI / 2;
  35832. }
  35833. function init() {
  35834. // Third person camera view
  35835. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 3000);
  35836. thirdPersonCamera.position.set(50, 40, 40);
  35837. thirdPersonCamera.lookAt(0, 0, 0);
  35838. thirdPersonRenderer = new _three.WebGLRenderer({
  35839. antialias: true
  35840. });
  35841. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  35842. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  35843. thirdPersonRenderer.setClearColor(0xdddddd);
  35844. document.body.appendChild(thirdPersonRenderer.domElement);
  35845. thirdPersonRenderer.domElement.style.position = 'fixed';
  35846. thirdPersonRenderer.domElement.style.left = '5px';
  35847. thirdPersonRenderer.domElement.style.bottom = '5px';
  35848. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  35849. thirdPersonControls.screenSpacePanning = false;
  35850. thirdPersonControls.minDistance = 1;
  35851. thirdPersonControls.maxDistance = 2000; // primary camera view
  35852. scene = new _three.Scene();
  35853. renderer = new _three.WebGLRenderer({
  35854. antialias: true
  35855. });
  35856. renderer.setPixelRatio(window.devicePixelRatio);
  35857. renderer.setSize(window.innerWidth, window.innerHeight);
  35858. renderer.setClearColor(0xcccccc);
  35859. renderer.gammaInput = true;
  35860. renderer.gameOutput = true;
  35861. document.body.appendChild(renderer.domElement);
  35862. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
  35863. camera.position.set(100, 100, 100);
  35864. cameraHelper = new _three.CameraHelper(camera);
  35865. scene.add(cameraHelper); // controls
  35866. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  35867. controls.screenSpacePanning = false;
  35868. controls.minDistance = 1;
  35869. controls.maxDistance = 2000; // lights
  35870. var dirLight = new _three.DirectionalLight(0xffffff);
  35871. dirLight.position.set(1, 1, 1);
  35872. scene.add(dirLight);
  35873. var ambLight = new _three.AmbientLight(0x222222);
  35874. scene.add(ambLight);
  35875. box = new _three.Box3();
  35876. reinstantiateTiles();
  35877. onWindowResize();
  35878. window.addEventListener('resize', onWindowResize, false); // GUI
  35879. const gui = new dat.GUI();
  35880. const tiles = gui.addFolder('Tiles Options');
  35881. tiles.add(params, 'loadSiblings');
  35882. tiles.add(params, 'errorTarget').min(0).max(50);
  35883. tiles.add(params, 'errorThreshold').min(0).max(1000);
  35884. tiles.add(params, 'maxDepth').min(1).max(100);
  35885. tiles.open();
  35886. gui.add(params, 'displayBounds');
  35887. gui.add(params, 'showThirdPerson');
  35888. gui.add(params, 'reload');
  35889. gui.open(); // TilesRenderer stats display
  35890. let textShadow = [];
  35891. for (let x = -1; x <= 1; x++) {
  35892. for (let y = -1; y <= 1; y++) {
  35893. let valX = x;
  35894. let valY = y;
  35895. if (valX !== 0 && valY !== 0) {
  35896. valX *= Math.cos(Math.PI / 4);
  35897. valY *= Math.sin(Math.PI / 4);
  35898. }
  35899. valX *= 1.5;
  35900. valY *= 1.5;
  35901. textShadow.push(`white ${valX}px ${valY}px 0`);
  35902. }
  35903. }
  35904. statsContainer = document.createElement('div');
  35905. statsContainer.style.position = 'absolute';
  35906. statsContainer.style.top = 0;
  35907. statsContainer.style.left = 0;
  35908. statsContainer.style.width = '100%';
  35909. statsContainer.style.textAlign = 'center';
  35910. statsContainer.style.textShadow = textShadow.join(',');
  35911. statsContainer.style.padding = '10px';
  35912. document.body.appendChild(statsContainer); // Stats
  35913. stats = new _statsModule.default();
  35914. stats.showPanel(0);
  35915. document.body.appendChild(stats.dom);
  35916. }
  35917. function onWindowResize() {
  35918. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  35919. thirdPersonCamera.updateProjectionMatrix();
  35920. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  35921. camera.aspect = window.innerWidth / window.innerHeight;
  35922. camera.updateProjectionMatrix();
  35923. renderer.setSize(window.innerWidth, window.innerHeight);
  35924. }
  35925. function animate() {
  35926. // update options
  35927. tiles.errorTarget = params.errorTarget;
  35928. tiles.errorThreshold = params.errorThreshold;
  35929. tiles.loadSiblings = params.loadSiblings;
  35930. tiles.maxDepth = params.maxDepth;
  35931. tiles.displayBounds = params.displayBounds; // update tiles
  35932. tiles.update();
  35933. window.tiles = tiles; // update tiles center
  35934. if (tiles.getBounds(box)) {
  35935. box.getCenter(tiles.group.position);
  35936. tiles.group.position.multiplyScalar(-1);
  35937. }
  35938. stats.begin();
  35939. render();
  35940. stats.end();
  35941. requestAnimationFrame(animate);
  35942. }
  35943. function render() {
  35944. // render primary view
  35945. cameraHelper.visible = false;
  35946. renderer.render(scene, camera); // render third person view
  35947. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  35948. if (params.showThirdPerson) {
  35949. cameraHelper.visible = true;
  35950. thirdPersonRenderer.render(scene, thirdPersonCamera);
  35951. }
  35952. statsContainer.innerText = `Downloading: ${tiles.stats.downloading} Parsing: ${tiles.stats.parsing} Visible: ${tiles.group.children.length}`;
  35953. }
  35954. },{"../src/ThreeTilesRenderer.js":"../src/ThreeTilesRenderer.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) {
  35955. var global = arguments[3];
  35956. var OVERLAY_ID = '__parcel__error__overlay__';
  35957. var OldModule = module.bundle.Module;
  35958. function Module(moduleName) {
  35959. OldModule.call(this, moduleName);
  35960. this.hot = {
  35961. data: module.bundle.hotData,
  35962. _acceptCallbacks: [],
  35963. _disposeCallbacks: [],
  35964. accept: function (fn) {
  35965. this._acceptCallbacks.push(fn || function () {});
  35966. },
  35967. dispose: function (fn) {
  35968. this._disposeCallbacks.push(fn);
  35969. }
  35970. };
  35971. module.bundle.hotData = null;
  35972. }
  35973. module.bundle.Module = Module;
  35974. var checkedAssets, assetsToAccept;
  35975. var parent = module.bundle.parent;
  35976. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  35977. var hostname = "" || location.hostname;
  35978. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  35979. var ws = new WebSocket(protocol + '://' + hostname + ':' + "63925" + '/');
  35980. ws.onmessage = function (event) {
  35981. checkedAssets = {};
  35982. assetsToAccept = [];
  35983. var data = JSON.parse(event.data);
  35984. if (data.type === 'update') {
  35985. var handled = false;
  35986. data.assets.forEach(function (asset) {
  35987. if (!asset.isNew) {
  35988. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  35989. if (didAccept) {
  35990. handled = true;
  35991. }
  35992. }
  35993. }); // Enable HMR for CSS by default.
  35994. handled = handled || data.assets.every(function (asset) {
  35995. return asset.type === 'css' && asset.generated.js;
  35996. });
  35997. if (handled) {
  35998. console.clear();
  35999. data.assets.forEach(function (asset) {
  36000. hmrApply(global.parcelRequire, asset);
  36001. });
  36002. assetsToAccept.forEach(function (v) {
  36003. hmrAcceptRun(v[0], v[1]);
  36004. });
  36005. } else if (location.reload) {
  36006. // `location` global exists in a web worker context but lacks `.reload()` function.
  36007. location.reload();
  36008. }
  36009. }
  36010. if (data.type === 'reload') {
  36011. ws.close();
  36012. ws.onclose = function () {
  36013. location.reload();
  36014. };
  36015. }
  36016. if (data.type === 'error-resolved') {
  36017. console.log('[parcel] ✨ Error resolved');
  36018. removeErrorOverlay();
  36019. }
  36020. if (data.type === 'error') {
  36021. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  36022. removeErrorOverlay();
  36023. var overlay = createErrorOverlay(data);
  36024. document.body.appendChild(overlay);
  36025. }
  36026. };
  36027. }
  36028. function removeErrorOverlay() {
  36029. var overlay = document.getElementById(OVERLAY_ID);
  36030. if (overlay) {
  36031. overlay.remove();
  36032. }
  36033. }
  36034. function createErrorOverlay(data) {
  36035. var overlay = document.createElement('div');
  36036. overlay.id = OVERLAY_ID; // html encode message and stack trace
  36037. var message = document.createElement('div');
  36038. var stackTrace = document.createElement('pre');
  36039. message.innerText = data.error.message;
  36040. stackTrace.innerText = data.error.stack;
  36041. 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>';
  36042. return overlay;
  36043. }
  36044. function getParents(bundle, id) {
  36045. var modules = bundle.modules;
  36046. if (!modules) {
  36047. return [];
  36048. }
  36049. var parents = [];
  36050. var k, d, dep;
  36051. for (k in modules) {
  36052. for (d in modules[k][1]) {
  36053. dep = modules[k][1][d];
  36054. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  36055. parents.push(k);
  36056. }
  36057. }
  36058. }
  36059. if (bundle.parent) {
  36060. parents = parents.concat(getParents(bundle.parent, id));
  36061. }
  36062. return parents;
  36063. }
  36064. function hmrApply(bundle, asset) {
  36065. var modules = bundle.modules;
  36066. if (!modules) {
  36067. return;
  36068. }
  36069. if (modules[asset.id] || !bundle.parent) {
  36070. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  36071. asset.isNew = !modules[asset.id];
  36072. modules[asset.id] = [fn, asset.deps];
  36073. } else if (bundle.parent) {
  36074. hmrApply(bundle.parent, asset);
  36075. }
  36076. }
  36077. function hmrAcceptCheck(bundle, id) {
  36078. var modules = bundle.modules;
  36079. if (!modules) {
  36080. return;
  36081. }
  36082. if (!modules[id] && bundle.parent) {
  36083. return hmrAcceptCheck(bundle.parent, id);
  36084. }
  36085. if (checkedAssets[id]) {
  36086. return;
  36087. }
  36088. checkedAssets[id] = true;
  36089. var cached = bundle.cache[id];
  36090. assetsToAccept.push([bundle, id]);
  36091. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36092. return true;
  36093. }
  36094. return getParents(global.parcelRequire, id).some(function (id) {
  36095. return hmrAcceptCheck(global.parcelRequire, id);
  36096. });
  36097. }
  36098. function hmrAcceptRun(bundle, id) {
  36099. var cached = bundle.cache[id];
  36100. bundle.hotData = {};
  36101. if (cached) {
  36102. cached.hot.data = bundle.hotData;
  36103. }
  36104. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  36105. cached.hot._disposeCallbacks.forEach(function (cb) {
  36106. cb(bundle.hotData);
  36107. });
  36108. }
  36109. delete bundle.cache[id];
  36110. bundle(id);
  36111. cached = bundle.cache[id];
  36112. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  36113. cached.hot._acceptCallbacks.forEach(function (cb) {
  36114. cb();
  36115. });
  36116. return true;
  36117. }
  36118. }
  36119. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","index.js"], null)
  36120. //# sourceMappingURL=example.e31bb0bc.js.map